Java Basics - Part 5: Collections, Strings & Ex-
ception Handling
String Operations
String Creation
String str1 = "Hello";
String str2 = new String("Hello");
String str3 = String.valueOf(123);
String str4 = String.format("Value: %d", 42);
String Methods
String text = " Hello World ";
// Length
int length = text.length();
// Case conversion
String upper = text.toUpperCase();
String lower = text.toLowerCase();
// Trimming
String trimmed = text.trim();
// Substring
String sub1 = text.substring(0, 5); // "Hello"
String sub2 = text.substring(6); // "World"
// Character access
char first = text.charAt(0);
// Searching
boolean contains = text.contains("World");
int index = text.indexOf("o");
int lastIndex = text.lastIndexOf("o");
boolean startsWith = text.startsWith("Hello");
boolean endsWith = text.endsWith("World");
// Replacement
String replaced = text.replace("World", "Java");
String replacedAll = text.replaceAll("o", "0");
// Splitting
String[] parts = text.split(" ");
1
// Joining
String joined = String.join("-", "Hello", "World", "Java");
String Concatenation
String firstName = "John";
String lastName = "Doe";
// Using + operator
String fullName1 = firstName + " " + lastName;
// Using concat method
String fullName2 = firstName.concat(" ").concat(lastName);
// Using StringBuilder
StringBuilder sb = new StringBuilder();
sb.append(firstName).append(" ").append(lastName);
String fullName3 = sb.toString();
// Using String.format
String fullName4 = String.format("%s %s", firstName, lastName);
String Comparison
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
// == compares references
boolean refEqual = (str1 == str2); // true (same literal)
boolean refEqual2 = (str1 == str3); // false (different objects)
// equals() compares content
boolean contentEqual = str1.equals(str2); // true
boolean contentEqual2 = str1.equals(str3); // true
// equalsIgnoreCase() ignores case
boolean ignoreCase = "Hello".equalsIgnoreCase("hello"); // true
// compareTo() for ordering
int comparison = "apple".compareTo("banana"); // negative
int comparison2 = "banana".compareTo("apple"); // positive
2
StringBuilder and StringBuffer
// StringBuilder (not thread-safe, faster)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
// StringBuffer (thread-safe, slower)
StringBuffer buffer = new StringBuffer();
buffer.append("Hello");
buffer.append(" ");
buffer.append("World");
String result2 = buffer.toString();
// StringBuilder methods
StringBuilder sb2 = new StringBuilder("Hello");
sb2.insert(5, " World"); // "Hello World"
sb2.delete(5, 11); // "Hello"
sb2.reverse(); // "olleH"
sb2.setCharAt(0, 'H'); // "HlleH"
Collections
List Interface
// ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
// LinkedList
List<String> linkedList = new LinkedList<>();
linkedList.add("Dog");
linkedList.add("Cat");
linkedList.add("Bird");
// Common List operations
arrayList.add(1, "Orange"); // Insert at index
String fruit = arrayList.get(0); // Get element
arrayList.set(0, "Mango"); // Set element
arrayList.remove(1); // Remove by index
arrayList.remove("Cherry"); // Remove by object
3
int size = arrayList.size(); // Get size
boolean empty = arrayList.isEmpty(); // Check if empty
boolean contains = arrayList.contains("Apple");
int index = arrayList.indexOf("Banana");
// Iterating
for (String item : arrayList) {
System.out.println(item);
}
// Using iterator
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}
Set Interface
// HashSet (unordered, no duplicates)
Set<String> hashSet = new HashSet<>();
hashSet.add("Red");
hashSet.add("Green");
hashSet.add("Blue");
hashSet.add("Red"); // Duplicate ignored
// TreeSet (ordered, no duplicates)
Set<String> treeSet = new TreeSet<>();
treeSet.add("Zebra");
treeSet.add("Apple");
treeSet.add("Banana");
// Automatically sorted: Apple, Banana, Zebra
// LinkedHashSet (insertion order, no duplicates)
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("First");
linkedHashSet.add("Second");
linkedHashSet.add("Third");
// Set operations
Set<String> set1 = new HashSet<>(Arrays.asList("A", "B", "C"));
Set<String> set2 = new HashSet<>(Arrays.asList("B", "C", "D"));
// Union
Set<String> union = new HashSet<>(set1);
union.addAll(set2);
4
// Intersection
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
// Difference
Set<String> difference = new HashSet<>(set1);
difference.removeAll(set2);
Map Interface
// HashMap
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 1);
hashMap.put("Banana", 2);
hashMap.put("Cherry", 3);
// TreeMap (sorted by keys)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Zebra", 1);
treeMap.put("Apple", 2);
treeMap.put("Banana", 3);
// LinkedHashMap (insertion order)
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("First", 1);
linkedHashMap.put("Second", 2);
linkedHashMap.put("Third", 3);
// Common Map operations
Integer value = hashMap.get("Apple"); // Get value
hashMap.put("Orange", 4); // Add/Update
hashMap.remove("Banana"); // Remove
boolean containsKey = hashMap.containsKey("Apple");
boolean containsValue = hashMap.containsValue(1);
int size = hashMap.size();
Set<String> keys = hashMap.keySet();
Collection<Integer> values = hashMap.values();
Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
// Iterating through map
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Using forEach (Java 8+)
5
hashMap.forEach((key, value) -> System.out.println(key + ": " + value));
Queue Interface
// LinkedList as Queue
Queue<String> queue = new LinkedList<>();
queue.offer("First");
queue.offer("Second");
queue.offer("Third");
String first = queue.peek(); // View first element
String removed = queue.poll(); // Remove and return first element
// PriorityQueue
Queue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(5);
priorityQueue.offer(1);
priorityQueue.offer(3);
// Automatically ordered: 1, 3, 5
// Deque (double-ended queue)
Deque<String> deque = new LinkedList<>();
deque.addFirst("First");
deque.addLast("Last");
String firstElement = deque.removeFirst();
String lastElement = deque.removeLast();
Collections Utility Methods
List<String> list = Arrays.asList("Zebra", "Apple", "Banana");
// Sorting
Collections.sort(list);
// Reversing
Collections.reverse(list);
// Shuffling
Collections.shuffle(list);
// Finding min/max
String min = Collections.min(list);
String max = Collections.max(list);
// Filling
Collections.fill(list, "Default");
6
// Frequency
int frequency = Collections.frequency(list, "Apple");
// Binary search (list must be sorted)
Collections.sort(list);
int index = Collections.binarySearch(list, "Apple");
// Creating unmodifiable collections
List<String> unmodifiableList = Collections.unmodifiableList(list);
Set<String> unmodifiableSet = Collections.unmodifiableSet(new HashSet<>(list));
Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(new HashMap<>());
Exception Handling
Try-Catch Blocks
try {
int result = 10 / 0;
System.out.println("This won't execute");
} catch (ArithmeticException e) {
System.out.println("Division by zero: " + e.getMessage());
} catch (Exception e) {
System.out.println("General exception: " + e.getMessage());
} finally {
System.out.println("This always executes");
}
Multiple Exceptions
try {
// Some code that might throw exceptions
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
System.out.println("Array or arithmetic error: " + e.getMessage());
}
Throwing Exceptions
public void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
7
int result = a / b;
System.out.println("Result: " + result);
}
// Custom exception
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public void validateAge(int age) throws CustomException {
if (age < 0 || age > 150) {
throw new CustomException("Invalid age: " + age);
}
}
Try-With-Resources
// Automatically closes resources
try (FileInputStream fis = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
// Custom resource
public class CustomResource implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("Closing custom resource");
}
}
try (CustomResource resource = new CustomResource()) {
// Use resource
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
Common Exception Types
// Checked exceptions (must be handled)
try {
8
File file = new File("nonexistent.txt");
FileReader reader = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
// Unchecked exceptions (RuntimeException and subclasses)
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
// NullPointerException
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Null pointer: " + e.getMessage());
}
// NumberFormatException
try {
int number = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + e.getMessage());
}
File I/O
Reading Files
// Reading with BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Reading with Scanner
try (Scanner scanner = new Scanner(new File("input.txt"))) {
9
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Reading all lines at once (Java 8+)
try {
List<String> lines = Files.readAllLines(Paths.get("input.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Writing Files
// Writing with BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("Hello World");
bw.newLine();
bw.write("This is a test");
} catch (IOException e) {
e.printStackTrace();
}
// Writing with PrintWriter
try (PrintWriter pw = new PrintWriter(new FileWriter("output.txt"))) {
pw.println("Hello World");
pw.println("This is a test");
pw.printf("Number: %d, String: %s", 42, "test");
} catch (IOException e) {
e.printStackTrace();
}
// Writing with Files (Java 8+)
try {
List<String> lines = Arrays.asList("Line 1", "Line 2", "Line 3");
Files.write(Paths.get("output.txt"), lines);
} catch (IOException e) {
e.printStackTrace();
}
10
File Operations
File file = new File("test.txt");
// File information
boolean exists = file.exists();
boolean isFile = file.isFile();
boolean isDirectory = file.isDirectory();
long size = file.length();
String name = file.getName();
String path = file.getPath();
String absolutePath = file.getAbsolutePath();
// File operations
boolean created = file.createNewFile();
boolean deleted = file.delete();
boolean renamed = file.renameTo(new File("newtest.txt"));
// Directory operations
File dir = new File("mydir");
boolean dirCreated = dir.mkdir();
boolean dirsCreated = dir.mkdirs(); // Creates parent directories too
// Listing files
File[] files = dir.listFiles();
for (File f : files) {
System.out.println(f.getName());
}
// File filtering
File[] txtFiles = dir.listFiles((d, name) -> name.endsWith(".txt"));
Quick Reference
String Summary
• Creation: "literal", new String(), String.valueOf()
• Methods: length(), charAt(), substring(), indexOf(), contains()
• Comparison: equals(), equalsIgnoreCase(), compareTo()
• Concatenation: +, concat(), StringBuilder
Collections Summary
• List: ArrayList, LinkedList - ordered, allows duplicates
• Set: HashSet, TreeSet, LinkedHashSet - no duplicates
11
• Map: HashMap, TreeMap, LinkedHashMap - key-value pairs
• Queue: LinkedList, PriorityQueue - FIFO/LIFO operations
Exception Handling Summary
• try-catch: Handle exceptions
• finally: Always executes
• throw: Throw exception
• throws: Declare exception
• try-with-resources: Auto-close resources
Best Practices
1. Use StringBuilder for string concatenation in loops
2. Choose appropriate collection type for your needs
3. Handle exceptions properly
4. Use try-with-resources for file operations
5. Close resources explicitly when needed
6. Use meaningful exception messages
7. Don’t catch and ignore exceptions
8. Use generics for type safety
9. Prefer interfaces over concrete implementations
10. Use utility methods from Collections class
12