0% found this document useful (0 votes)
3 views14 pages

CorejavaInterviewBooster20

The document discusses various methods to compare strings in Java 8 without using `Comparator` or `Comparable`, including `Objects.equals()`, character-by-character comparison using `Stream`, and leveraging `reduce()`. It also covers how to create immutable lists using `Collections.unmodifiableList()`, `List.of()`, Guava's `ImmutableList`, and `List.copyOf()`. Additionally, it explains the try-with-resources feature introduced in Java 7 for automatic resource management, providing examples and benefits of its use.

Uploaded by

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

CorejavaInterviewBooster20

The document discusses various methods to compare strings in Java 8 without using `Comparator` or `Comparable`, including `Objects.equals()`, character-by-character comparison using `Stream`, and leveraging `reduce()`. It also covers how to create immutable lists using `Collections.unmodifiableList()`, `List.of()`, Guava's `ImmutableList`, and `List.copyOf()`. Additionally, it explains the try-with-resources feature introduced in Java 7 for automatic resource management, providing examples and benefits of its use.

Uploaded by

tellapuri.naresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

In Java 8, you can compare two strings without using `Comparator` or `Comparable`

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`.

Here’s how you can do it:

### 1. Using `Objects.equals()` method (without `Comparator` or `Comparable`):

Java provides a utility method `Objects.equals()` in the `java.util.Objects` class


to compare two strings safely, handling `null` values.

```java
import java.util.Objects;

public class CompareStrings {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";

if (Objects.equals(str1, str2)) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```

- `Objects.equals(str1, str2)` will return `true` if both strings are equal,


considering `null` handling.

### 2. Using `Stream` to Compare Character by Character:

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;

public class CompareStringsWithStream {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";

boolean areEqual = IntStream.range(0, Math.min(str1.length(),


str2.length()))
.allMatch(i -> str1.charAt(i) == str2.charAt(i)) && str1.length() ==
str2.length();

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()`.

### 3. Using `Stream` and `reduce()` to Compare Strings:

You can also use the `reduce()` function from `Stream` to compare two strings.

```java
import java.util.stream.IntStream;

public class CompareStringsWithReduce {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";

boolean areEqual = IntStream.range(0, Math.min(str1.length(),


str2.length()))
.mapToObj(i -> str1.charAt(i) == str2.charAt(i))
.reduce(true, (a, b) -> a && b) && str1.length() == str2.length();

if (areEqual) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```

- **`reduce()`** is used to combine the results of the individual comparisons. We


initialize the comparison as `true` and combine with the `&&` operation to ensure
all characters match.

### 4. Using `String.chars()` to Compare Character by Character:

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";

boolean areEqual = str1.chars().toArray().length ==


str2.chars().toArray().length
&& IntStream.range(0, str1.length())
.allMatch(i -> str1.charAt(i) == str2.charAt(i));

if (areEqual) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
}
}
```

- **`str1.chars()`** creates an `IntStream` of the string's characters. You can use


`allMatch()` to check if all characters are equal.

### Summary:

- **`Objects.equals()`**: The simplest and safest way to compare two strings.


- **Stream APIs**: `IntStream` and `Stream` allow you to compare strings by their
individual characters, providing more flexibility for custom comparisons.
- **`reduce()` and `allMatch()`**: Both can be used for comparing strings without
using `Comparator` or `Comparable`.

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:

### 1. Using `Collections.unmodifiableList()`


This is one of the simplest ways to make a list immutable. It wraps the list in an
unmodifiable view, so any attempts to modify it (such as adding or removing
elements) will throw an `UnsupportedOperationException`.

#### Example:
```java
import java.util.*;

public class ImmutableListExample {


public static void main(String[] args) {
List<String> originalList = new ArrayList<>();
originalList.add("Apple");
originalList.add("Banana");
originalList.add("Cherry");

// Make the list immutable


List<String> immutableList = Collections.unmodifiableList(originalList);

System.out.println("Immutable List: " + immutableList);

// Trying to modify the immutable list will throw


UnsupportedOperationException
// immutableList.add("Date"); // This will throw an exception
}
}
```

### Key Points:


- `Collections.unmodifiableList()` creates an unmodifiable view of the list. It
doesn't make the list itself immutable, but it prevents any modification to it
through the reference to the unmodifiable list.
- The underlying list (`originalList` in this case) can still be modified directly
if you have access to it, so if you want to make it fully immutable, consider
copying the list into an unmodifiable one.

### 2. Using `List.of()` (Java 9 and later)


In Java 9 and later, you can use the `List.of()` method to create an immutable list
directly. This method returns an unmodifiable list, meaning that no modifications
(like `add`, `remove`, or `set`) can be performed.

#### Example:
```java
import java.util.*;

public class ImmutableListExample {


public static void main(String[] args) {
// Create an immutable list using List.of()
List<String> immutableList = List.of("Apple", "Banana", "Cherry");

System.out.println("Immutable List: " + immutableList);

// Trying to modify the immutable list will throw


UnsupportedOperationException
// immutableList.add("Date"); // This will throw an exception
}
}
```

### Key Points:


- `List.of()` creates an immutable list directly, and no modification is allowed.
This is a preferred option for Java 9 and beyond.
- You can pass any number of elements to `List.of()`, and it creates a list that is
immutable.

### 3. Using `ImmutableList` from Google Guava (External Library)


If you're using the **Guava** library by Google, it provides the `ImmutableList`
class, which makes it very easy to create immutable lists.

#### Example:
```java
import com.google.common.collect.ImmutableList;

public class ImmutableListExample {


public static void main(String[] args) {
// Create an immutable list using Guava's ImmutableList
ImmutableList<String> immutableList = ImmutableList.of("Apple", "Banana",
"Cherry");

System.out.println("Immutable List: " + immutableList);

// Trying to modify the immutable list will throw


UnsupportedOperationException
// immutableList.add("Date"); // This will throw an exception
}
}
```

### Key Points:


- Guava's `ImmutableList` is a great option if you want a robust, high-performance,
immutable collection.
- It ensures complete immutability—no modifications can be made to the list after
it's created.

### 4. Using `Java 9+ `List.copyOf()` (Another Way)


In Java 9 and later, `List.copyOf()` can be used to create an immutable copy of a
list. This is useful when you have an existing list and want to make an immutable
copy of it.
#### Example:
```java
import java.util.*;

public class ImmutableListExample {


public static void main(String[] args) {
List<String> originalList = new ArrayList<>();
originalList.add("Apple");
originalList.add("Banana");
originalList.add("Cherry");

// Make a copy of the list and make it immutable


List<String> immutableList = List.copyOf(originalList);

System.out.println("Immutable List: " + immutableList);

// Trying to modify the immutable list will throw


UnsupportedOperationException
// immutableList.add("Date"); // This will throw an exception
}
}
```

### Key Points:


- `List.copyOf()` creates an immutable copy of the given collection (like an
`ArrayList` or `LinkedList`), and no modification is allowed.

### Summary:

- **`Collections.unmodifiableList()`**: Wraps an existing list in an unmodifiable


view.
- **`List.of()`** (Java 9+): Directly creates an immutable list.
- **`ImmutableList` from Guava**: Provides an immutable list with excellent
performance and guarantees.
- **`List.copyOf()`** (Java 9+): Creates an immutable copy of an existing list.

If you're using Java 9 or later, `List.of()` or `List.copyOf()` are often the


simplest and most efficient ways to create an immutable list. For earlier versions
of Java, `Collections.unmodifiableList()` or third-party libraries like Guava can
be used.
============================================
### **Try-with-Resources in Java**

Introduced in **Java 7**, **try-with-resources** is a feature that simplifies


handling resources (like files, network connections, database connections, etc.)
that need to be closed after use. Before this feature, you would need to explicitly
close resources in a `finally` block, which could be error-prone and verbose.

With **try-with-resources**, Java ensures that resources are automatically closed


when the `try` block finishes, whether normally or because of an exception. This
reduces boilerplate code and prevents potential resource leaks.

### **What is a Resource?**


A resource is any object that needs to be explicitly closed after use. Common
examples include:

- **InputStream/OutputStream** (e.g., `FileInputStream`, `FileOutputStream`)


- **Reader/Writer** (e.g., `BufferedReader`, `FileWriter`)
- **Database connections** (e.g., `Connection`, `Statement`)
- **Sockets**
- **Streams** (e.g., `BufferedInputStream`, `ObjectInputStream`)

Any class that implements the `java.lang.AutoCloseable` interface can be used in a


try-with-resources statement.

### **Syntax of Try-with-Resources**


The basic syntax of the try-with-resources statement is as follows:

```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.

### **Example 1: Using Try-with-Resources with Files**

In this example, we use `BufferedReader` to read from a file. The resource


(`BufferedReader`) will be automatically closed after use.

```java
import java.io.*;

public class TryWithResourcesExample {


public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("sample.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

### **Key Points:**


- **Automatic Resource Management (ARM)**: The resource (`BufferedReader` in this
case) is automatically closed when the try block finishes.
- You don’t need to explicitly call `reader.close()` in a `finally` block.
- The `BufferedReader` implements the `AutoCloseable` interface, which makes it
compatible with try-with-resources.

### **Example 2: Using Multiple Resources**


You can manage multiple resources within the same try-with-resources statement by
separating them with semicolons.

```java
import java.io.*;

public class MultipleResourcesExample {


public static void main(String[] args) {
try (
BufferedReader reader = new BufferedReader(new
FileReader("sample.txt"));
PrintWriter writer = new PrintWriter(new FileWriter("output.txt"))
) {
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

- Both the `BufferedReader` and `PrintWriter` will be automatically closed when the
try block finishes, even if an exception occurs.

### **Example 3: Custom AutoCloseable Resource**

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!");
}

public void useResource() {


System.out.println("Using resource...");
}

@Override
public void close() {
System.out.println("Resource released!");
}
}

public class CustomResourceExample {


public static void main(String[] args) {
try (MyResource resource = new MyResource()) {
resource.useResource();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
### **Key Points:**
- **`MyResource`** implements `AutoCloseable` and provides a `close()` method,
which will be automatically invoked at the end of the `try` block.
- The output:
```
Resource acquired!
Using resource...
Resource released!
```

### **How Try-with-Resources Works:**

1. When entering the `try` block, resources are initialized.


2. Once the `try` block exits (either normally or via an exception), the `close()`
method of each resource is called automatically.
3. If an exception is thrown inside the try block, the resource is still closed
before the exception is propagated (even if the exception occurs before the
resource is used).

### **Exception Handling with Try-with-Resources**

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.

Here’s an example that demonstrates suppressed exceptions:

```java
import java.io.*;

public class TryWithResourcesSuppressed {


public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("nonexistent.txt"))) {
reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```

If an exception occurs when trying to close the `BufferedReader`, it will be


**suppressed** and won't be thrown immediately. Instead, you can check for
suppressed exceptions using:

```java
try {
// Some code
} catch (Exception e) {
Throwable[] suppressed = e.getSuppressed();
for (Throwable t : suppressed) {
t.printStackTrace();
}
}
```

### **Benefits of Try-with-Resources:**


1. **Automatic Resource Management**: It reduces the boilerplate code, as you don't
need to manually close resources.
2. **Exception Safety**: It ensures that resources are closed even when exceptions
occur, preventing resource leaks.
3. **Cleaner Code**: It eliminates the need for `finally` blocks to close
resources, making the code more readable and maintainable.

### **Conclusion:**

The **try-with-resources** statement in Java simplifies resource management by


automatically closing resources at the end of the `try` block. It works with any
class that implements the `AutoCloseable` interface, ensuring that resources like
file streams, network connections, and database connections are properly closed
without explicit `finally` blocks.
===============================================
Q6. What is static or final method?
Ans. Static or final method is a method that belongs to a class rather than an
instance of the class.
Static method can be called without creating an instance of the class.

Final method cannot be overridden by a subclass.

Static and final methods can be accessed using the class name.

Example: Math.max() is a static method in the Math class.

Example: String.toUpperCase() is a final method in the String class.


============================
Yes, you're correct! When you use `Arrays.asList()` in Java, it creates a **fixed-
size list** backed by the original array. This list has the following
characteristics:

### 1. **Modifying elements**:


- You **can modify** the elements in the list because it is backed by the
original array.
- For example, you can change the value of an element at a specific index using
the `set()` method.

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]
```

### 2. **Adding elements**:


- You **cannot add** elements to the list because the list size is fixed,
matching the size of the original array.
- For example, trying to add an element using `add()` will throw an
`UnsupportedOperationException`.

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:

### 1. **Using `FileReader` and `BufferedReader` (Character Stream)**

`FileReader` is used for reading character-based files. It reads the file as


characters, and `BufferedReader` can be used to efficiently read lines of text.

```java
import java.io.*;

public class FileReaderExample {


public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
fileReader.close();
}
}
```

### 2. **Using `FileInputStream` and `BufferedInputStream` (Byte Stream)**

`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.*;

public class FileInputStreamExample {


public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("example.txt");
BufferedInputStream bufferedInputStream = new
BufferedInputStream(fileInputStream);

int data;
while ((data = bufferedInputStream.read()) != -1) {
System.out.print((char) data);
}

bufferedInputStream.close();
fileInputStream.close();
}
}
```

### 3. **Using `Files` class in `java.nio.file` package (NIO)**

The `java.nio.file.Files` class provides utility methods for reading files in a


more modern way. It's part of the NIO (New I/O) package and is available from Java
7 onwards. It allows you to read all bytes or lines of a file.

#### Read all lines at once:

```java
import java.nio.file.*;
import java.io.IOException;
import java.util.List;

public class FilesReadAllLines {


public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("example.txt"));
for (String line : lines) {
System.out.println(line);
}
}
}
```

#### Read all bytes at once:

```java
import java.nio.file.*;
import java.io.IOException;

public class FilesReadAllBytes {


public static void main(String[] args) throws IOException {
byte[] bytes = Files.readAllBytes(Paths.get("example.txt"));
System.out.println(new String(bytes));
}
}
```

### 4. **Using `Scanner` (Simpler Reading for Text Files)**

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;

public class ScannerExample {


public static void main(String[] args) throws FileNotFoundException {
File file = new File("example.txt");
Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}

scanner.close();
}
}
```

### 5. **Using `RandomAccessFile` (For Random Access in Files)**

`RandomAccessFile` allows reading from and writing to a file at any position. It is


used when you need to access file contents at a specific location.

```java
import java.io.*;

public class RandomAccessFileExample {


public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("example.txt", "r");
String line;
while ((line = file.readLine()) != null) {
System.out.println(line);
}
file.close();
}
}
```

### 6. **Using `DataInputStream` (For Reading Primitive Data Types)**

`DataInputStream` is used when you need to read primitive data types (like `int`,
`float`, `double`) from a file.

```java
import java.io.*;

public class DataInputStreamExample {


public static void main(String[] args) throws IOException {
DataInputStream dataInputStream = new DataInputStream(new
FileInputStream("example.txt"));

while (dataInputStream.available() > 0) {


System.out.println(dataInputStream.readInt());
}

dataInputStream.close();
}
}
```

### 7. **Using `ObjectInputStream` (For Reading Objects)**


`ObjectInputStream` is used to read serialized objects from a file.

```java
import java.io.*;

public class ObjectInputStreamExample {


public static void main(String[] args) throws IOException,
ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(new
FileInputStream("example.ser"));

Object object = objectInputStream.readObject();


System.out.println(object);

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.*;

public class BufferedReaderExample {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));

String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

reader.close();
}
}
```

### 9. **Using Streams for Parallel Processing (NIO + Streams)**

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;

public class FilesStreamExample {


public static void main(String[] args) throws IOException {
Stream<String> lines = Files.lines(Paths.get("example.txt"));
lines.parallel().forEach(System.out::println); // Parallel stream
processing
lines.close();
}
}
```

### 10. **Using Apache Commons IO (External Library)**

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;

public class ApacheCommonsFileRead {


public static void main(String[] args) throws IOException {
File file = new File("example.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
System.out.println(content);
}
}
```

### 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;

public class FileStreamExample {


public static void main(String[] args) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("example.txt"))) {
lines.forEach(System.out::println);
}
}
}
```

### 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.

Let me know if you'd like examples of any of the other methods!


=======================================

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy