CorejavaInterviewBooster20
CorejavaInterviewBooster20
by utilizing **lambda expressions** and the `Stream` API. A few approaches can
achieve this comparison, such as using `Objects.equals()`, `Stream`, or even
leveraging `IntStream`.
```java
import java.util.Objects;
if (Objects.equals(str1, str2)) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```
In Java 8, you can use the `Stream` API to compare the two strings character by
character. This method gives more flexibility in customization.
```java
import java.util.stream.IntStream;
if (areEqual) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```
### Explanation:
- **`IntStream.range()`** generates a stream of indices for the string, and we
compare each character one by one.
- **`allMatch()`** ensures that all characters match.
- The comparison also checks that both strings have the same length with
`str1.length() == str2.length()`.
You can also use the `reduce()` function from `Stream` to compare two strings.
```java
import java.util.stream.IntStream;
if (areEqual) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```
You can convert each string to an `IntStream` and compare the character values:
```java
public class CompareStringsWithChars {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
if (areEqual) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```
### Summary:
These are all modern, Java 8 approaches to comparing strings without using
`Comparator` or `Comparable`.
============================================
In Java, you can make a list immutable using several different approaches. Here are
a few methods to create an immutable list:
#### Example:
```java
import java.util.*;
#### Example:
```java
import java.util.*;
#### Example:
```java
import com.google.common.collect.ImmutableList;
### Summary:
```java
try (ResourceType resource = new ResourceType()) {
// Use the resource
} catch (ExceptionType e) {
// Handle exception
} finally {
// Optional block; try-with-resources will auto-close the resource
}
```
Here:
- **`ResourceType resource = new ResourceType()`**: The resource to be used within
the try block.
- The **resource** will be automatically closed once the try block is exited,
either normally or due to an exception.
- The **`AutoCloseable` interface** ensures that the resource is closed
automatically when the try block finishes.
```java
import java.io.*;
```java
import java.io.*;
- Both the `BufferedReader` and `PrintWriter` will be automatically closed when the
try block finishes, even if an exception occurs.
You can also create your own custom resources that implement the `AutoCloseable`
interface, which will allow them to be used in a try-with-resources block.
```java
class MyResource implements AutoCloseable {
public MyResource() {
System.out.println("Resource acquired!");
}
@Override
public void close() {
System.out.println("Resource released!");
}
}
If an exception occurs while closing the resource, it will be suppressed. You can
access the suppressed exceptions via the `getSuppressed()` method of the
`Throwable` class.
```java
import java.io.*;
```java
try {
// Some code
} catch (Exception e) {
Throwable[] suppressed = e.getSuppressed();
for (Throwable t : suppressed) {
t.printStackTrace();
}
}
```
### **Conclusion:**
Static and final methods can be accessed using the class name.
Example:
```java
String[] arr = {"A", "B", "C"};
List<String> list = Arrays.asList(arr);
// Modifying an element
list.set(0, "X");
System.out.println(list); // Output: [X, B, C]
```
Example:
```java
list.add("D"); // This will throw UnsupportedOperationException
```
### 3. **Removing elements**:
- You **cannot remove** elements from the list because it has a fixed size.
- Trying to remove an element using `remove()` will also throw an
`UnsupportedOperationException`.
Example:
```java
list.remove(1); // This will throw UnsupportedOperationException
```
### Summary:
- **Modifying elements**: Yes, you can modify the elements in the list.
- **Adding/removing elements**: No, you cannot add or remove elements.
The list created by `Arrays.asList()` is backed by the array, and its size is fixed
to the size of the array. While you can modify the elements in the list (because
it's still backed by an array), adding or removing elements is not supported, as
that would require changing the size of the underlying array.
==============================================
In Java, there are several ways to read files, each serving different use cases
depending on the requirements (like efficiency, simplicity, or handling large
files). Here are some of the most common methods:
```java
import java.io.*;
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
}
}
```
`FileInputStream` reads files as byte streams, useful for binary files. If you want
to buffer input and make the reading more efficient, you can use
`BufferedInputStream`.
```java
import java.io.*;
int data;
while ((data = bufferedInputStream.read()) != -1) {
System.out.print((char) data);
}
bufferedInputStream.close();
fileInputStream.close();
}
}
```
```java
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
```java
import java.nio.file.*;
import java.io.IOException;
The `Scanner` class can be used to read files line by line, and it can handle
different types of data (like strings, numbers). It's often used for reading simple
text files or parsing.
```java
import java.io.*;
import java.util.Scanner;
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
```
```java
import java.io.*;
`DataInputStream` is used when you need to read primitive data types (like `int`,
`float`, `double`) from a file.
```java
import java.io.*;
dataInputStream.close();
}
}
```
```java
import java.io.*;
objectInputStream.close();
}
}
```
### 8. **Using `BufferedReader` with `FileReader` for Reading Large Files Line by
Line**
When reading large files, using `BufferedReader` with `FileReader` ensures that the
file is read efficiently and that resources are properly managed.
```java
import java.io.*;
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
```
You can use `Files.lines()` to create a stream of lines and then process them with
stream operations, including parallel processing.
```java
import java.nio.file.*;
import java.io.IOException;
import java.util.stream.Stream;
Apache Commons IO provides many utility methods for file operations. The
`FileUtils` class in this library makes reading files easier.
```java
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
### 11. **Using Java 8 Streams for File Reading and Processing**
Java 8 streams can be used to read files line by line and process them in a
functional style.
```java
import java.nio.file.*;
import java.io.IOException;
### Summary:
1. **Character Streams**: `FileReader`, `BufferedReader`
2. **Byte Streams**: `FileInputStream`, `BufferedInputStream`
3. **NIO (New I/O)**: `Files.readAllLines()`, `Files.readAllBytes()`,
`Files.lines()`
4. **Scanner**: Simplified reading, good for parsing.
5. **Random Access**: `RandomAccessFile`
6. **Primitive Data Types**: `DataInputStream`
7. **Object Serialization**: `ObjectInputStream`
8. **Apache Commons IO**: FileUtils (External Library)
9. **Java 8 Streams**: Use `Files.lines()` and process with streams.