0% found this document useful (0 votes)
26 views12 pages

Java Collections, Strings & Exceptions Guide

This document covers Java basics including string operations, collections, and exception handling. It details string creation, methods, concatenation, and comparison, as well as various collection types such as lists, sets, and maps, along with their operations. Additionally, it explains exception handling techniques, including try-catch blocks, throwing exceptions, and file I/O operations.

Uploaded by

Aniket Deshpande
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views12 pages

Java Collections, Strings & Exceptions Guide

This document covers Java basics including string operations, collections, and exception handling. It details string creation, methods, concatenation, and comparison, as well as various collection types such as lists, sets, and maps, along with their operations. Additionally, it explains exception handling techniques, including try-catch blocks, throwing exceptions, and file I/O operations.

Uploaded by

Aniket Deshpande
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Basics - Part 5: Collections, Strings & Ex-

ception Handling
String Operations
String Creation
String str1 = "Hello";
String str2 = new String("Hello");
String str3 = [Link](123);
String str4 = [Link]("Value: %d", 42);

String Methods
String text = " Hello World ";

// Length
int length = [Link]();

// Case conversion
String upper = [Link]();
String lower = [Link]();

// Trimming
String trimmed = [Link]();

// Substring
String sub1 = [Link](0, 5); // "Hello"
String sub2 = [Link](6); // "World"

// Character access
char first = [Link](0);

// Searching
boolean contains = [Link]("World");
int index = [Link]("o");
int lastIndex = [Link]("o");
boolean startsWith = [Link]("Hello");
boolean endsWith = [Link]("World");

// Replacement
String replaced = [Link]("World", "Java");
String replacedAll = [Link]("o", "0");

// Splitting
String[] parts = [Link](" ");

1
// Joining
String joined = [Link]("-", "Hello", "World", "Java");

String Concatenation
String firstName = "John";
String lastName = "Doe";

// Using + operator
String fullName1 = firstName + " " + lastName;

// Using concat method


String fullName2 = [Link](" ").concat(lastName);

// Using StringBuilder
StringBuilder sb = new StringBuilder();
[Link](firstName).append(" ").append(lastName);
String fullName3 = [Link]();

// Using [Link]
String fullName4 = [Link]("%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 = [Link](str2); // true
boolean contentEqual2 = [Link](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();
[Link]("Hello");
[Link](" ");
[Link]("World");
String result = [Link]();

// StringBuffer (thread-safe, slower)


StringBuffer buffer = new StringBuffer();
[Link]("Hello");
[Link](" ");
[Link]("World");
String result2 = [Link]();

// StringBuilder methods
StringBuilder sb2 = new StringBuilder("Hello");
[Link](5, " World"); // "Hello World"
[Link](5, 11); // "Hello"
[Link](); // "olleH"
[Link](0, 'H'); // "HlleH"

Collections
List Interface
// ArrayList
List<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

// LinkedList
List<String> linkedList = new LinkedList<>();
[Link]("Dog");
[Link]("Cat");
[Link]("Bird");

// Common List operations


[Link](1, "Orange"); // Insert at index
String fruit = [Link](0); // Get element
[Link](0, "Mango"); // Set element
[Link](1); // Remove by index
[Link]("Cherry"); // Remove by object

3
int size = [Link](); // Get size
boolean empty = [Link](); // Check if empty
boolean contains = [Link]("Apple");
int index = [Link]("Banana");

// Iterating
for (String item : arrayList) {
[Link](item);
}

// Using iterator
Iterator<String> iterator = [Link]();
while ([Link]()) {
String item = [Link]();
[Link](item);
}

Set Interface
// HashSet (unordered, no duplicates)
Set<String> hashSet = new HashSet<>();
[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("Red"); // Duplicate ignored

// TreeSet (ordered, no duplicates)


Set<String> treeSet = new TreeSet<>();
[Link]("Zebra");
[Link]("Apple");
[Link]("Banana");
// Automatically sorted: Apple, Banana, Zebra

// LinkedHashSet (insertion order, no duplicates)


Set<String> linkedHashSet = new LinkedHashSet<>();
[Link]("First");
[Link]("Second");
[Link]("Third");

// Set operations
Set<String> set1 = new HashSet<>([Link]("A", "B", "C"));
Set<String> set2 = new HashSet<>([Link]("B", "C", "D"));

// Union
Set<String> union = new HashSet<>(set1);
[Link](set2);

4
// Intersection
Set<String> intersection = new HashSet<>(set1);
[Link](set2);

// Difference
Set<String> difference = new HashSet<>(set1);
[Link](set2);

Map Interface
// HashMap
Map<String, Integer> hashMap = new HashMap<>();
[Link]("Apple", 1);
[Link]("Banana", 2);
[Link]("Cherry", 3);

// TreeMap (sorted by keys)


Map<String, Integer> treeMap = new TreeMap<>();
[Link]("Zebra", 1);
[Link]("Apple", 2);
[Link]("Banana", 3);

// LinkedHashMap (insertion order)


Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
[Link]("First", 1);
[Link]("Second", 2);
[Link]("Third", 3);

// Common Map operations


Integer value = [Link]("Apple"); // Get value
[Link]("Orange", 4); // Add/Update
[Link]("Banana"); // Remove
boolean containsKey = [Link]("Apple");
boolean containsValue = [Link](1);
int size = [Link]();
Set<String> keys = [Link]();
Collection<Integer> values = [Link]();
Set<[Link]<String, Integer>> entries = [Link]();

// Iterating through map


for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + ": " + [Link]());
}

// Using forEach (Java 8+)

5
[Link]((key, value) -> [Link](key + ": " + value));

Queue Interface
// LinkedList as Queue
Queue<String> queue = new LinkedList<>();
[Link]("First");
[Link]("Second");
[Link]("Third");

String first = [Link](); // View first element


String removed = [Link](); // Remove and return first element

// PriorityQueue
Queue<Integer> priorityQueue = new PriorityQueue<>();
[Link](5);
[Link](1);
[Link](3);
// Automatically ordered: 1, 3, 5

// Deque (double-ended queue)


Deque<String> deque = new LinkedList<>();
[Link]("First");
[Link]("Last");
String firstElement = [Link]();
String lastElement = [Link]();

Collections Utility Methods


List<String> list = [Link]("Zebra", "Apple", "Banana");

// Sorting
[Link](list);

// Reversing
[Link](list);

// Shuffling
[Link](list);

// Finding min/max
String min = [Link](list);
String max = [Link](list);

// Filling
[Link](list, "Default");

6
// Frequency
int frequency = [Link](list, "Apple");

// Binary search (list must be sorted)


[Link](list);
int index = [Link](list, "Apple");

// Creating unmodifiable collections


List<String> unmodifiableList = [Link](list);
Set<String> unmodifiableSet = [Link](new HashSet<>(list));
Map<String, Integer> unmodifiableMap = [Link](new HashMap<>());

Exception Handling
Try-Catch Blocks
try {
int result = 10 / 0;
[Link]("This won't execute");
} catch (ArithmeticException e) {
[Link]("Division by zero: " + [Link]());
} catch (Exception e) {
[Link]("General exception: " + [Link]());
} finally {
[Link]("This always executes");
}

Multiple Exceptions
try {
// Some code that might throw exceptions
int[] numbers = {1, 2, 3};
[Link](numbers[5]);
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
[Link]("Array or arithmetic error: " + [Link]());
}

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;
[Link]("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("[Link]");
BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
String line = [Link]();
[Link](line);
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}

// Custom resource
public class CustomResource implements AutoCloseable {
@Override
public void close() throws Exception {
[Link]("Closing custom resource");
}
}

try (CustomResource resource = new CustomResource()) {


// Use resource
} catch (Exception e) {
[Link]("Error: " + [Link]());
}

Common Exception Types


// Checked exceptions (must be handled)
try {

8
File file = new File("[Link]");
FileReader reader = new FileReader(file);
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
}

// Unchecked exceptions (RuntimeException and subclasses)


try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds: " + [Link]());
}

// NullPointerException
try {
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Null pointer: " + [Link]());
}

// NumberFormatException
try {
int number = [Link]("abc");
} catch (NumberFormatException e) {
[Link]("Invalid number format: " + [Link]());
}

File I/O
Reading Files
// Reading with BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}

// Reading with Scanner


try (Scanner scanner = new Scanner(new File("[Link]"))) {

9
while ([Link]()) {
String line = [Link]();
[Link](line);
}
} catch (FileNotFoundException e) {
[Link]();
}

// Reading all lines at once (Java 8+)


try {
List<String> lines = [Link]([Link]("[Link]"));
for (String line : lines) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}

Writing Files
// Writing with BufferedWriter
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello World");
[Link]();
[Link]("This is a test");
} catch (IOException e) {
[Link]();
}

// Writing with PrintWriter


try (PrintWriter pw = new PrintWriter(new FileWriter("[Link]"))) {
[Link]("Hello World");
[Link]("This is a test");
[Link]("Number: %d, String: %s", 42, "test");
} catch (IOException e) {
[Link]();
}

// Writing with Files (Java 8+)


try {
List<String> lines = [Link]("Line 1", "Line 2", "Line 3");
[Link]([Link]("[Link]"), lines);
} catch (IOException e) {
[Link]();
}

10
File Operations
File file = new File("[Link]");

// File information
boolean exists = [Link]();
boolean isFile = [Link]();
boolean isDirectory = [Link]();
long size = [Link]();
String name = [Link]();
String path = [Link]();
String absolutePath = [Link]();

// File operations
boolean created = [Link]();
boolean deleted = [Link]();
boolean renamed = [Link](new File("[Link]"));

// Directory operations
File dir = new File("mydir");
boolean dirCreated = [Link]();
boolean dirsCreated = [Link](); // Creates parent directories too

// Listing files
File[] files = [Link]();
for (File f : files) {
[Link]([Link]());
}

// File filtering
File[] txtFiles = [Link]((d, name) -> [Link](".txt"));

Quick Reference
String Summary
• Creation: "literal", new String(), [Link]()
• 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

Common questions

Powered by AI

Exception handling in Java using try-catch-finally blocks is crucial for managing errors and maintaining the robustness of a program. The 'try' block contains code that might cause an exception, while 'catch' blocks contain handlers for specific exception types. The 'finally' block contains cleanup code that always executes after try-catch, whether or not an exception was thrown. This structure helps prevent runtime errors from crashing programs and allows developers to gracefully handle unpredictable exceptions .

A HashSet in Java is a collection that does not allow duplicate elements. It is part of the Set interface and is implemented using a hash table. When an element is added, its hash code is calculated and used to determine where it should be stored. If a duplicate element (i.e., one that is "equal" to an existing element) is added, it will be ignored because the hash table already contains an equivalent element .

HashMap maps keys to values with no specific order and provides average O(1) time complexity for most operations. TreeMap maintains a sorted order of keys (by their natural order or a specified comparator), leading to O(log n) time complexity for insertions, deletions, and lookups. LinkedHashMap maintains insertion order or access order if configured, offering performance similar to HashMap with the additional overhead of maintaining a linked list data structure to preserve order .

In Java, declaring exceptions with the 'throws' keyword in a method signature informs callers of the method about the checked exceptions that could be thrown during the method's execution. It serves as a contract that must be handled either with try-catch blocks or by propagating the exception further up the call stack, ensuring exception awareness at compile time and enhancing program reliability .

StringBuilder and StringBuffer are both used for creating mutable strings in Java, but they differ in terms of performance and thread safety. StringBuilder is faster but not thread-safe, making it suitable for use in a single-threaded context. StringBuffer, on the other hand, is thread-safe and synchronized, making it slower but safe for use in multi-threaded scenarios .

The try-with-resources statement is beneficial in Java I/O operations as it simplifies resource management by automatically closing resources like files and database connections that implement the AutoCloseable interface, thus reducing the possibility of resource leaks. In contrast, a regular try-catch-finally block requires explicitly closing resources, often leading to more complex and error-prone code .

A TreeSet in Java uses a Red-Black tree data structure to store elements, ensuring that they are automatically sorted in natural order (or according to a specified comparator). This property allows for efficient retrieval operations like search, but it may have slower insertion and deletion operations compared to unsorted sets like HashSet. The ordered nature also implies that duplicates are not allowed as they would violate the order .

In Java, equals() is used to compare the content of two strings, checking character sequence equality, while == checks if two string references point to the same object in memory. This distinction is crucial because strings with the same content but created using 'new' or resulting from different expressions may have different references, causing == to return false even if equals() returns true for them .

The compareTo method in Java is defined in the Comparable interface and allows strings to be compared lexicographically (i.e., dictionary order). It returns a negative integer, zero, or a positive integer when the calling string is found to be less than, equal to, or greater than the specified string, respectively. This method is essential for sorting algorithms as it provides the necessary ordering logic for strings .

In Java, a string can be created using literals, the 'new' keyword, the String.valueOf method, or String.format. The literal way (e.g., "Hello") is simple and memory-efficient as Java reuses the same instance for identical string literals. Using 'new String("Hello")' creates a new String object, which is less efficient as it doesn't take advantage of string interning. String.valueOf(123) converts non-string types to strings, and String.format("Value: %d", 42) creates formatted strings but is computationally expensive .

You might also like