Java Interview Questions and Answers –
Java 7 (Full Version)
Java 7 – 100+ Interview Questions and Answers (Preview)
1. 1. What is the Diamond Operator introduced in Java 7?
Java 7 introduced the diamond operator `<>` to simplify the instantiation of generic classes.
It allows the compiler to infer the type arguments from the context, reducing verbosity and
improving readability.
Example:
```java
List<String> names = new ArrayList<>();
```
2. 2. Explain try-with-resources in Java 7.
The try-with-resources statement automatically closes resources that implement the
`AutoCloseable` interface.
Example:
```java
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
return reader.readLine();
}
```
3. 3. What is the purpose of multi-catch in Java 7?
Multi-catch allows catching multiple exceptions in a single block using `|`.
Example:
```java
try {
// code
} catch (IOException | SQLException ex) {
ex.printStackTrace();
}
```
4. 4. How does Java 7 support Strings in switch statements?
Java 7 allows the use of `String` in switch-case constructs.
Example:
```java
switch (status) {
case "OPEN": break;
case "CLOSED": break;
}
```
5. 5. What is NIO.2 introduced in Java 7?
Java 7’s `java.nio.file` offers powerful file I/O capabilities like walking a directory tree and
watching for file changes.
Example:
```java
Files.walkFileTree(path, new SimpleFileVisitor<Path>() { ... });
```
6. 6. Describe the Fork/Join framework.
Introduced in Java 7, it allows recursive task parallelization for multi-core processors.
```java
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new RecursiveTask<>() { ... });
```
7. 7. What are suppressed exceptions in try-with-resources?
Exceptions thrown in `close()` are suppressed and attached to the primary exception.
Access with:
```java
Throwable[] suppressed = e.getSuppressed();
```
8. 8. How to register file change listeners using WatchService?
Use Java 7’s `WatchService` to monitor changes in a directory.
```java
path.register(watchService, ENTRY_CREATE, ENTRY_DELETE);
```
9. 9. What is @SafeVarargs in Java 7?
Suppresses unchecked warnings in varargs methods that are final, static, or constructors.
```java
@SafeVarargs
public static <T> void safePrint(T... args) { ... }
```
10. 10. Explain binary literals and underscore in numeric literals.
Binary literals use `0b` prefix: `int b = 0b1010;`
Underscores improve readability: `int num = 1_000_000;`