Top [1–200] Java 14 Topics Interview Questions with Example & Output.
Welcome Readers !!!
Top [1–200] Java 14 Topics Interview Questions with Example & Output.
Welcome Readers !!!
A Comprehensive Guide for Java 14 Interview questions with output as below:
Records,
Pattern Matching for instanceof,
Helpful NullPointerExceptions,
Non-volatile Mapped Byte Buffers,
JFR Event Streaming,
Packaging Tool,
Foreign-Memory Access API,
Switch Expressions,
NUMA-aware G1,
Pack200 Removal
Question & Answers
Records (Preview)
Q1. What is a record in Java 14?
record Person(String name, int age) {}
Person p = new Person("Alice", 30);
System.out.println(p.name() + ", " + p.age());
Output: Alice, 30
Q2. How do you create an instance of a record?
Person p = new Person("Bob", 25);
System.out.println(p);
Output: Person[name=Bob, age=25]
Q3. How are records different from classes?
// Records are immutable, concise data carriers with automatic equals, hashCode, toString
Output: Records provide auto-generated methods; classes require manual code.
Q4. How can you add methods to a record?
record Point(int x, int y) {
public int sum() { return x + y; }
}
System.out.println(new Point(3, 4).sum());
Output: 7
Q5. Can records implement interfaces?
record User(String name) implements Comparable<User> {
public int compareTo(User other) { return name.compareTo(other.name()); }
}
System.out.println(new User("A").compareTo(new User("B")));
Output: Negative value (A < B)
Pattern Matching for instanceof (Preview)
Q6. What is pattern matching for instanceof in Java 14?
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
Output: HELLO
Q7. How does pattern matching simplify type casts?
Object o = 42;
if (o instanceof Integer i) {
System.out.println(i + 1);
}
Output: 43
Q8. Can you use pattern matching in else blocks?
Object o = "World";
if (o instanceof Integer i) {
System.out.println(i);
} else if (o instanceof String s) {
System.out.println(s.length());
}
Output: 5
Q9. Can pattern matching be used in switch?
// Not in Java 14 (only instanceof), switch pattern matching is preview in Java 17+
Output: No, only instanceof in Java 14.
Q10. How do you combine pattern matching with records?
Object obj = new Person("Carl", 40);
if (obj instanceof Person p) {
System.out.println(p.name());
}
Output: Carl
Helpful NullPointerExceptions
Q11. What are Helpful NullPointerExceptions in Java 14?
String[] arr = null;
try {
System.out.println(arr.length);
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot read the array length because “arr” is null
Q12. How do Helpful NullPointerExceptions improve debugging?
Person p = null;
try {
System.out.println(p.name());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Person.name()” because “p” is null
Q13. How do you enable Helpful NullPointerExceptions?
java -XX:+ShowCodeDetailsInExceptionMessages -jar app.jar
Output: NPEs show detailed messages
Q14. What message is shown for chained nulls?
Person p = null;
try {
System.out.println(p.name().length());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Person.name()” because “p” is null
Q15. What happens if Helpful NullPointerExceptions is disabled?
java -XX:-ShowCodeDetailsInExceptionMessages -jar app.jar
Output: NPEs show default message (null)
Non-volatile Mapped Byte Buffers
Q16. What is a non-volatile mapped byte buffer?
// MappedByteBuffer created without requiring the file to be volatile (persisted immediately)
Output: Can map files for I/O without forcing disk writes
Q17. How do you create a non-volatile mapped buffer?
try (RandomAccessFile raf = new RandomAccessFile("data.bin", "rw");
FileChannel fc = raf.getChannel()) {
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
buffer.put((byte)65);
}
Output: Writes ‘A’ to file data.bin
Q18. How do you check if a buffer is loaded into memory?
MappedByteBuffer buf = ...;
System.out.println(buf.isLoaded());
Output: true or false
Q19. How do you force changes in a buffer to disk?
buf.force();
Output: Changes are flushed to disk
Q20. How do you handle buffer exceptions?
try {
buf.get(1000000);
} catch (IndexOutOfBoundsException e) {
System.out.println("Out of bounds!");
}
Output: Out of bounds!
JFR Event Streaming
Q21. What is JFR Event Streaming in Java 14?
// JFR (Java Flight Recorder) can be streamed live for monitoring events in running JVMs.
Output: JFR events available as live streams
Q22. How do you start JFR streaming?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.CPULoad").withPeriod(Duration.ofSeconds(1));
rs.onEvent("jdk.CPULoad", event -> System.out.println(event.getFloat("jvmUser")));
rs.startAsync();
Output: Prints JVM CPU user load every second
Q23. How do you stream GC events with JFR?
rs.enable("jdk.GarbageCollection");
rs.onEvent("jdk.GarbageCollection", e -> System.out.println("GC: " + e));
Output: GC events printed as they occur
Q24. How do you filter JFR events in a stream?
rs.onEvent("jdk.ThreadSleep", e -> {
if (e.getDuration().toMillis() > 1000)
System.out.println("Long sleep detected");
});
Output: Prints message if thread sleep > 1s
Q25. How do you stop a JFR stream?
rs.close();
Output: Stream stopped
Packaging Tool (Incubator)
Q26. What is the Packaging Tool in Java 14?
// Incubator tool 'jpackage' for creating platform installers (MSI, DMG, etc.) for Java apps
Output: Can create native installers for Java applications
Q27. How do you use jpackage for a JAR?
jpackage --input . --name MyApp --main-jar app.jar
Output: Native installer created
Q28. How do you specify installer type with jpackage?
jpackage --type msi --input . --name MyApp --main-jar app.jar
Output: MSI installer for Windows created
Q29. How do you set application icon with jpackage?
jpackage --icon app.ico --input . --name MyApp --main-jar app.jar
Output: Installer with custom icon
Q30. How do you add JVM options to packaged app?
jpackage --java-options "-Xmx512m" --input . --name MyApp --main-jar app.jar
Output: App runs with JVM option -Xmx512m
Foreign-Memory Access API (Incubator)
Q31. What is the Foreign-Memory Access API?
// Allows Java programs to safely and efficiently access foreign (non-Java heap) memory.
Output: Direct, safe access to off-heap memory
Q32. How do you allocate foreign memory using the API?
MemorySegment segment = MemorySegment.allocateNative(100);
System.out.println(segment.byteSize());
Output: 100
Q33. How do you access a value in foreign memory?
MemoryAccess.setByteAtOffset(segment, 0, (byte) 42);
byte b = MemoryAccess.getByteAtOffset(segment, 0);
System.out.println(b);
Output: 42
Q34. How do you close (free) foreign memory?
segment.close();
Output: Memory freed
Q35. How do you create a memory segment from a file?
try (FileChannel fc = FileChannel.open(Paths.get("data.bin"))) {
MemorySegment segment = MemorySegment.mapFromPath(Paths.get("data.bin"), 0, fc.size(), FileChannel.MapMode.READ_ONLY);
}
Output: Memory segment mapped from file
Switch Expressions (Standard)
Q36. What are Switch Expressions in Java 14 (Standard)?
int code = 1;
String msg = switch (code) {
case 1 -> "One";
default -> "Other";
};
System.out.println(msg);
Output: One
Q37. How do you use yield in switch expressions?
int age = 20;
String group = switch (age) {
case 0, 1, 2 -> "Infant";
default -> {
yield "Adult";
}
};
System.out.println(group);
Output: Adult
Q38. How do you assign switch expression result to a variable?
int n = 3;
String result = switch (n) {
case 1 -> "Low";
case 2,3 -> "Mid";
default -> "High";
};
System.out.println(result);
Output: Mid
Q39. Can switch expressions throw exceptions?
int n = -1;
String msg = switch (n) {
case 1 -> "OK";
default -> { throw new IllegalArgumentException("Bad value"); }
};
Output: Exception: Bad value
Q40. How do you use switch expressions in a lambda?
Function<Integer, String> f = i -> switch (i) {
case 1 -> "One";
default -> "Other";
};
System.out.println(f.apply(1));
Output: One
NUMA-aware Memory Allocation for G1
Q41. What is NUMA-aware G1 in Java 14?
// G1 garbage collector can allocate memory considering NUMA (Non-Uniform Memory Access) architecture.
Output: Improved memory locality and performance on NUMA systems
Q42. How do you enable NUMA awareness for G1?
java -XX:+UseG1GC -XX:+UseNUMA -jar app.jar
Output: G1 GC uses NUMA-aware allocation
Q43. How does NUMA improve GC performance?
// Reduces cross-node memory access latency
Output: Better GC and application performance on NUMA hardware
Q44. Can NUMA-aware memory allocation be used with other GCs?
// Only supported with G1 and Parallel GC, not all collectors
Output: Limited to certain collectors
Q45. How do you monitor NUMA memory allocation?
java -XX:+PrintNUMAStatistics -jar app.jar
Output: NUMA allocation statistics printed
Removal of Pack200 Tools and API
Q46. What is Pack200? Why was it removed?
// Pack200 was a compression format for JAR files; removed in Java 14 due to lack of use.
Output: Pack200 tools and API are no longer available.
Q47. How do you migrate from Pack200 compressed JARs?
// Use standard ZIP or JAR compression tools; update build pipelines to remove Pack200 steps.
Output: Switch to using ZIP/JAR compression.
Q48. What happens if you use Pack200 API in Java 14?
// Compilation error: Classes not found
Output: Pack200 classes are not found; remove from code.
Q49. How do you decompress a JAR after Pack200 removal?
// Use standard java.util.zip or jar tool
Output: Use standard JAR tools
Q50. How do you check if Pack200 removal affects your build?
grep -r pack200 .
Output: Lists references to Pack200 in your code/build scripts
More: Edge Cases, Exceptions, Performance, Multi-threading, Security, Reflection, Scripting, Deployment
Q51. How do you use records in a multi-threaded context?
record Counter(int value) {}
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(() -> System.out.println(new Counter(1)));
Output: Counter[value=1]
Q52. How do pattern matching and switch expressions work together?
Object o = 123;
String out = switch (o) {
case String s -> "String: " + s;
case Integer i -> "Int: " + i;
default -> "Other";
};
System.out.println(out);
Output: Int: 123
Q53. How do you use Foreign-Memory Access API for secure memory allocation?
MemorySegment segment = MemorySegment.allocateNative(16);
segment.close();
System.out.println("Memory freed securely");
Output: Memory freed securely
Q54. How do Helpful NullPointerExceptions help in debugging multi-threaded apps?
Person p = null;
Runnable r = () -> {
try { System.out.println(p.name()); }
catch (NullPointerException e) { System.out.println(e.getMessage()); }
};
new Thread(r).start();
Output: Cannot invoke “Person.name()” because “p” is null
Q55. How do you use JFR Event Streaming for real-time monitoring?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.GarbageCollection");
rs.onEvent("jdk.GarbageCollection", e -> System.out.println(e));
rs.startAsync();
Output: GC events streamed live
Q56. How do you use records with collections?
record Person(String name, int age) {}
List<Person> people = List.of(new Person("Ann", 21), new Person("Bob", 22));
System.out.println(people);
Output: [Person[name=Ann, age=21], Person[name=Bob, age=22]]
Q57. How do you use pattern matching for instanceof in a collection filter?
List<Object> items = List.of("Hello", 42, "World");
items.stream()
.filter(o -> o instanceof String s && s.length() > 4)
.forEach(System.out::println);
Output: Hello World
Q58. How do you get helpful NullPointerExceptions in a chain of calls?
Person p = null;
try {
System.out.println(p.name().length());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Person.name()” because “p” is null
Q59. How do you use MappedByteBuffer for fast file writing?
try (RandomAccessFile raf = new RandomAccessFile("fast.bin", "rw");
FileChannel fc = raf.getChannel()) {
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 8);
buf.putLong(123456789L);
}
Output: Writes 123456789L to fast.bin
Q60. How do you stream JVM events using JFR for GC monitoring?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.GarbageCollection");
rs.onEvent("jdk.GarbageCollection", e -> System.out.println("GC Event: " + e));
rs.startAsync();
Output: GC Event: [event details] (printed when GC occurs)
Q61. How do you create a platform installer with jpackage for a Java app?
jpackage --input . --name MyApp --main-jar app.jar --type exe
Output: Creates a Windows EXE installer for MyApp
Q62. How do you use Foreign-Memory Access API to allocate and read memory?
MemorySegment mem = MemorySegment.allocateNative(4);
MemoryAccess.setIntAtOffset(mem, 0, 123);
System.out.println(MemoryAccess.getIntAtOffset(mem, 0));
mem.close();
utput: 123
Q63. How do you use a switch expression to map error codes?
int code = 404;
String msg = switch (code) {
case 200 -> "OK";
case 404 -> "Not Found";
default -> "Unknown";
};
System.out.println(msg);
Output: Not Found
Q64. How do you enable NUMA-aware G1 memory allocation for a server?
java -XX:+UseG1GC -XX:+UseNUMA -jar server.jar
Output: G1 GC allocates memory considering NUMA topology
Q65. What happens if you use Pack200 APIs in Java 14?
// Compilation error: Pack200 classes not found
Output: Error: Pack200 API is removed
Q66. How do you create a record with validation in the constructor?
record Age(int value) {
public Age {
if (value < 0) throw new IllegalArgumentException("Negative age!");
}
}
try {
new Age(-1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Output: Negative age!
Q67. How do you use pattern matching for instanceof with multiple types?
Object o = 3.14;
if (o instanceof String s) {
System.out.println("String: " + s);
} else if (o instanceof Double d) {
System.out.println("Double: " + d);
}
Output: Double: 3.14
Q68. How do you see field names in NullPointerException messages?
Person p = null;
try {
System.out.println(p.age());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Person.age()” because “p” is null
Q69. How do you force a MappedByteBuffer to disk after writing?
buf.force();
System.out.println("Changes flushed");
Output: Changes flushed
Q70. How do you stream JFR thread events for monitoring thread creation?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ThreadStart");
rs.onEvent("jdk.ThreadStart", e -> System.out.println("Thread started: " + e.getString("threadName")));
rs.startAsync();
Output: Thread started: [threadName]
Q71. How do you set custom JVM options in jpackage output?
jpackage --java-options "-DmyProp=123" --input . --main-jar app.jar --name MyApp
Output: Packaged app runs with JVM property myProp=123
Q72. How do you write to foreign memory using MemoryAccess?
MemorySegment mem = MemorySegment.allocateNative(8);
MemoryAccess.setLongAtOffset(mem, 0, 987654321L);
System.out.println(MemoryAccess.getLongAtOffset(mem, 0));
mem.close();
Output: 987654321
Q73. How do you use switch expressions in a stream mapping operation?
List<Integer> nums = Arrays.asList(1, 2, 3);
List<String> out = nums.stream()
.map(n -> switch (n) {
case 1 -> "A";
case 2 -> "B";
default -> "C";
})
.collect(Collectors.toList());
System.out.println(out);
Output: [A, B, C]
Q74. How do you monitor NUMA allocation statistics on JVM startup?
java -XX:+PrintNUMAStatistics -XX:+UseG1GC -XX:+UseNUMA -jar app.jar
Output: NUMA allocation stats printed to console
Q75. How do you migrate a build pipeline that uses Pack200 for JARs?
# Remove Pack200 steps; use standard jar or zip tools
Output: Build works without Pack200
Q76. How do you use records in a Map?
record Key(String id) {}
Map<Key, String> map = new HashMap<>();
map.put(new Key("123"), "val");
System.out.println(map.get(new Key("123")));
Output: val
Q77. How do you use pattern matching for instanceof with null values?
Object o = null;
if (o instanceof String s) {
System.out.println(s);
} else {
System.out.println("Null or not String");
}
Output: Null or not String
Q78. How do you see method names in Helpful NullPointerExceptions?
Person p = null;
try {
System.out.println(p.name().toUpperCase());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Person.name()” because “p” is null
Q79. How do you allocate and free foreign memory safely?
try (MemorySegment mem = MemorySegment.allocateNative(16)) {
MemoryAccess.setByteAtOffset(mem, 0, (byte)7);
System.out.println(MemoryAccess.getByteAtOffset(mem, 0));
}
Output: 7
Q80. How do you use switch expressions for REST API status mapping?
int status = 201;
String msg = switch (status) {
case 200 -> "OK";
case 201 -> "Created";
case 404 -> "Not Found";
default -> "Unknown";
};
System.out.println(msg);
Output: Created
Q81. How do you enable NUMA-aware G1 on a NUMA server?
java -XX:+UseG1GC -XX:+UseNUMA -jar bigdata.jar
Output: JVM uses NUMA-aware GC
Q82. How do you handle absence of Pack200 class in migration scripts?
try {
Class.forName("java.util.jar.Pack200");
} catch (ClassNotFoundException e) {
System.out.println("Pack200 not available");
}
Output: Pack200 not available
Q83. How do you use records with pattern matching in filtering?
List<Object> objs = List.of(new Person("X", 10), "str");
objs.stream().filter(o -> o instanceof Person p && p.age() > 5)
.forEach(System.out::println);
Output: Person[name=X, age=10]
Q84. How do you format Helpful NullPointerException for logging?
Person p = null;
try {
p.name();
} catch (NullPointerException e) {
System.err.println("Error: " + e.getMessage());
}
Output: Error: Cannot invoke “Person.name()” because “p” is null
Q85. How do you write and read data with Non-volatile MappedByteBuffer?
MappedByteBuffer buf = ...; // mapped as shown earlier
buf.putInt(1234);
buf.force();
buf.position(0);
System.out.println(buf.getInt());
Output: 1234
Q86. How do you stream JVM events for security monitoring using JFR?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.SecurityProviderService");
rs.onEvent("jdk.SecurityProviderService", e -> System.out.println("Security event: " + e));
rs.startAsync();
Output: Security event: [details]
Q87. How do you specify app version in jpackage output?
jpackage --app-version 1.0.0 --input . --main-jar app.jar --name MyApp
Output: Installer version set to 1.0.0
Q88. How do you manipulate bytes in foreign memory?
MemorySegment seg = MemorySegment.allocateNative(4);
MemoryAccess.setByteAtOffset(seg, 0, (byte)42);
System.out.println(MemoryAccess.getByteAtOffset(seg, 0));
seg.close();
Output: 42
Q89. How do you use switch expressions with enum types?
enum Status { OK, FAIL }
Status s = Status.OK;
String msg = switch (s) {
case OK -> "Success";
case FAIL -> "Failure";
};
System.out.println(msg);
Output: Success
Q90. How do you monitor NUMA allocation with JVM flags?
java -XX:+UseG1GC -XX:+UseNUMA -XX:+PrintNUMAStatistics -jar app.jar
Output: NUMA allocation details printed
Q91. How do you migrate from Pack200 in automated build tools?
# Remove Pack200 steps; use jar/zip
Output: Successful build without Pack200
Q92. How do you use records for DTOs in web services?
record UserDto(String username, int score) {}
UserDto dto = new UserDto("user", 99);
System.out.println(dto);
Output: UserDto[username=user, score=99]
Q93. How do you use pattern matching with records in data processing?
Object obj = new Person("Anna", 32);
if (obj instanceof Person p && p.age() > 30) {
System.out.println("Senior: " + p.name());
}
Output: Senior: Anna
Q94. How do you use helpful NullPointerExceptions in REST APIs?
UserDto dto = null;
try {
System.out.println(dto.username());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “UserDto.username()” because “dto” is null
Q95. How do you map a file with Non-volatile MappedByteBuffer for reading?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
System.out.println(buf.getChar(0));
Output: Reads char from mapped file
Q96. How do you stream JVM memory usage events in JFR?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.MemoryUsage");
rs.onEvent("jdk.MemoryUsage", e -> System.out.println("Memory: " + e));
rs.startAsync();
Output: Memory: [event details]
Q97. How do you set installer type for macOS in jpackage?
jpackage --type dmg --input . --main-jar app.jar --name MyApp
Output: DMG installer for macOS
Q98. How do you create a foreign memory segment from a file?
try (FileChannel fc = FileChannel.open(Paths.get("file.bin"))) {
MemorySegment seg = MemorySegment.mapFromPath(Paths.get("file.bin"), 0, fc.size(), FileChannel.MapMode.READ_ONLY);
System.out.println(seg.byteSize());
}
Output: [file size in bytes]
Q99. How do you use switch expressions with blocks and yield?
int val = 5;
String msg = switch (val) {
case 1 -> "Low";
case 5 -> {
System.out.println("Special case");
yield "Mid";
}
default -> "High";
};
System.out.println(msg);
Output: Special case Mid
Q100. How do you enable NUMA G1 for a multi-threaded app?
java -XX:+UseG1GC -XX:+UseNUMA -jar mt-app.jar
Output: GC uses NUMA-aware allocation
titlesubtitletags
Java 14 Interview Questions & Answers (Q101–Q200): Advanced Topics, Example Code & Output
Blending Records, Pattern Matching, Helpful NullPointerExceptions, Byte Buffers, JFR, Packaging, Foreign Memory, Switch Expressions, NUMA G1, Pack200 Removal
Java
Java14
Records
Pattern Matching
NullPointerException
MappedByteBuffer
JFR
Packaging
ForeignMemory
Switch Expressions
NUMA
Pack200
Interview
Output
Java 14 Interview Questions & Answers (Q101–Q200)
Q101. How do you use records for thread-safe immutable data transfer?
record Data(int value) {}
Data d = new Data(42);
// Safe to share between threads because records are immutable
Output: Data[value=42]
Q102. How do you use pattern matching for instanceof in concurrent code?
Object o = "Thread-safe";
Runnable r = () -> {
if (o instanceof String s) {
System.out.println(s.toUpperCase());
}
};
new Thread(r).start();
Output: THREAD-SAFE
Q103. How do you analyze null pointer issues in multi-threaded code using Helpful NullPointerExceptions?
record Holder(String value) {}
Holder h = null;
Runnable r = () -> {
try {
System.out.println(h.value());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
};
new Thread(r).start();
Output: Cannot invoke “Holder.value()” because “h” is null
Q104. How do you use Non-volatile MappedByteBuffer for high-speed multi-threaded logging?
try (RandomAccessFile raf = new RandomAccessFile("log.bin", "rw");
FileChannel fc = raf.getChannel()) {
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
Runnable logTask = () -> buf.putInt(0, 2025);
new Thread(logTask).start();
}
Output: Writes 2025 at offset 0 in log.bin
Q105. How do you stream JFR events for thread state changes in a server?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ThreadSleep");
rs.onEvent("jdk.ThreadSleep", e -> System.out.println("Thread slept: " + e.getDuration().toMillis() + " ms"));
rs.startAsync();
Output: Thread slept: [milliseconds] ms
Q106. How do you automate app packaging and deployment with jpackage in CI/CD?
jpackage --input . --main-jar app.jar --name MyApp --type exe
# Use in CI pipeline to produce installer artifacts
Output: Installer artifacts generated for deployment
Q107. How do you allocate and free foreign memory blocks in parallel tasks?
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(() -> {
MemorySegment seg = MemorySegment.allocateNative(8);
MemoryAccess.setLongAtOffset(seg, 0, 1234L);
System.out.println(MemoryAccess.getLongAtOffset(seg, 0));
seg.close();
});
Output: 1234
Q108. How do you use switch expressions in a multi-threaded calculation?
Runnable r = () -> {
int code = 2;
String result = switch (code) {
case 1 -> "Low";
case 2 -> "Medium";
default -> "High";
};
System.out.println(result);
};
new Thread(r).start();
Output: Medium
Q109. How do you monitor NUMA-aware G1 allocation for performance tuning?
java -XX:+UseG1GC -XX:+UseNUMA -XX:+PrintNUMAStatistics -jar perfApp.jar
Output: NUMA allocation statistics printed
Q110. How do you handle Pack200 removal in legacy deployment scripts?
# Remove any references to pack200 in build/deploy scripts
# Use jar or zip as replacement
Output: Deployment proceeds without Pack200 errors
Q111. How do you use records to model API request/response DTOs?
record ApiRequest(String userId, String action) {}
record ApiResponse(int code, String message) {}
ApiResponse resp = new ApiResponse(200, "OK");
System.out.println(resp);
Output: ApiResponse[code=200, message=OK]
Q112. How do you use pattern matching for instanceof in reflection-based utilities?
Object obj = new ApiRequest("u1", "login");
if (obj instanceof ApiRequest req) {
System.out.println("User: " + req.userId());
}
Output: User: u1
Q113. How do you diagnose NullPointerExceptions in REST controllers with Java 14?
ApiResponse resp = null;
try {
System.out.println(resp.message());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “ApiResponse.message()” because “resp” is null
Q114. How do you use Non-volatile MappedByteBuffer for direct memory file communication between processes?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 64);
buf.putChar(0, 'J');
System.out.println(buf.getChar(0));
Output: J
Q115. How do you stream JFR events for JVM heap usage monitoring?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.MemoryUsage");
rs.onEvent("jdk.MemoryUsage", e -> System.out.println("Heap used: " + e.getLong("usedMemory")));
rs.startAsync();
Output: Heap used: [bytes]
Q116. How do you create a cross-platform installer using jpackage for a cloud-native app?
jpackage --input . --main-jar cloud.jar --name CloudApp --type dmg
Output: DMG installer for macOS generated
Q117. How do you allocate and release foreign memory for real-time analytics?
MemorySegment seg = MemorySegment.allocateNative(16);
MemoryAccess.setByteAtOffset(seg, 0, (byte)99);
System.out.println(MemoryAccess.getByteAtOffset(seg, 0));
seg.close();
Output: 99
Q118. How do you use switch expressions for error mapping in scripting engines?
int err = 1;
String status = switch (err) {
case 0 -> "Success";
case 1 -> "Script Error";
default -> "Unknown";
};
System.out.println(status);
Output: Script Error
Q119. How do you optimize JVM for NUMA in a high-performance cluster deployment?
java -XX:+UseG1GC -XX:+UseNUMA -jar clusterApp.jar
Output: Optimized memory locality on NUMA hardware
Q120. How do you update build scripts to handle Pack200 removal for automated CI?
# Remove Pack200 calls; use jars
Output: CI builds pass
Q121. How do you use records for secure user authentication tokens?
record AuthToken(String token, long expiry) {}
AuthToken token = new AuthToken("abc123", System.currentTimeMillis() + 3600_000);
System.out.println(token);
Output: AuthToken[token=abc123, expiry=…]
Q122. How do you use pattern matching for instanceof in security checks?
Object obj = new AuthToken("tok", 9999L);
if (obj instanceof AuthToken at && at.expiry() > System.currentTimeMillis()) {
System.out.println("Valid token");
} else {
System.out.println("Invalid or expired");
}
Output: Valid token or Invalid or expired (depends on time)
Q123. How do you analyze NullPointerExceptions in security code?
AuthToken token = null;
try {
System.out.println(token.token());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “AuthToken.token()” because “token” is null
Q124. How do you use Non-volatile MappedByteBuffer for secure file writes?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 32);
buf.put("secure".getBytes());
buf.force();
Output: “secure” written to file
Q125. How do you stream JFR events to monitor security provider events?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.SecurityProviderService");
rs.onEvent("jdk.SecurityProviderService", e -> System.out.println("Provider: " + e.getString("providerName")));
rs.startAsync();
Output: Provider: [providerName]
Q126. How do you create a signed installer using jpackage for enterprise deployment?
jpackage --input . --main-jar enterprise.jar --name EntApp --type msi --win-sign
Output: Signed MSI installer generated
Q127. How do you use foreign memory for high-frequency trading data?
MemorySegment seg = MemorySegment.allocateNative(24);
MemoryAccess.setLongAtOffset(seg, 0, 1000000L);
System.out.println(MemoryAccess.getLongAtOffset(seg, 0));
seg.close();
Output: 1000000
Q128. How do you use switch expressions for dynamic configuration in deployment scripts?
String env = "prod";
String config = switch (env) {
case "dev" -> "Development";
case "prod" -> "Production";
default -> "Default";
};
System.out.println(config);
Output: Production
Q129. How do you tune JVM NUMA G1 for low-latency microservices?
java -XX:+UseG1GC -XX:+UseNUMA -XX:MaxGCPauseMillis=20 -jar microservice.jar
Output: Low GC pauses, NUMA-aware
Q130. How do you use records for logging structured audit events?
record AuditEvent(String user, String action, long ts) {}
AuditEvent evt = new AuditEvent("admin", "login", System.currentTimeMillis());
System.out.println(evt);
Output: AuditEvent[user=admin, action=login, ts=…]
Q131. How do you use pattern matching for instanceof in structured audit logs?
Object obj = new AuditEvent("guest", "logout", 123456L);
if (obj instanceof AuditEvent e) {
System.out.println("Audit: " + e.user());
}
Output: Audit: guest
Q132. How do you diagnose NullPointerExceptions in audit logging?
AuditEvent evt = null;
try {
System.out.println(evt.user());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “AuditEvent.user()” because “evt” is null
Q133. How do you use Non-volatile MappedByteBuffer for audit file writes?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 64);
buf.put("audit".getBytes());
buf.force();
Output: “audit” written to file
Q134. How do you stream JFR audit events for real-time compliance checks?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.SecurityProviderService");
rs.onEvent("jdk.SecurityProviderService", e -> System.out.println("Audit: " + e));
rs.startAsync();
Output: Audit: [event details]
Q135. How do you create a cross-platform audit tool installer with jpackage?
jpackage --input . --main-jar audit.jar --name AuditApp --type pkg
utput: PKG installer for macOS generated
Q136. How do you use foreign memory access for audit trail storage?
MemorySegment seg = MemorySegment.allocateNative(32);
MemoryAccess.setByteAtOffset(seg, 0, (byte)101);
System.out.println(MemoryAccess.getByteAtOffset(seg, 0));
seg.close();
Output: 101
Q137. How do you use switch expressions for audit status reporting?
int code = 0;
String status = switch (code) {
case 0 -> "OK";
case 1 -> "Warning";
default -> "Error";
};
System.out.println(status);
Output: OK
Q138. How do you optimize JVM NUMA G1 for audit servers?
java -XX:+UseG1GC -XX:+UseNUMA -XX:MaxGCPauseMillis=50 -jar auditServer.jar
Output: Optimized for audit workloads
Q139. How do you handle Pack200 removal in audit pipeline migration?
# Remove Pack200 references from pipeline
Output: Pipeline works without Pack200
Q140. How do you use records for reporting summary statistics?
record Summary(String key, int value) {}
Summary s = new Summary("total", 500);
System.out.println(s);
Output:
Summary[key=total, value=500]
Q141. How do you use pattern matching for instanceof in summary data aggregation?
Object obj = new Summary("count", 99);
if (obj instanceof Summary s) {
System.out.println("Count: " + s.value());
}
utput: Count: 99
Q142. How do you diagnose NullPointerExceptions in summary reporting?
Summary sum = null;
try {
sum.key();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Summary.key()” because “sum” is null
Q143. How do you use Non-volatile MappedByteBuffer for summary file export?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 32);
buf.put("summary".getBytes());
buf.force();
Output: “summary” written to file
Q144. How do you stream JFR events for summary reporting in dashboards?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.CPULoad");
rs.onEvent("jdk.CPULoad", e -> System.out.println("CPU: " + e.getFloat("jvmUser")));
rs.startAsync();
Output: CPU: [user%]
Q145. How do you package a summary dashboard with jpackage?
jpackage --input . --main-jar dashboard.jar --name DashboardApp --type exe
Output: EXE installer for dashboard
Q146. How do you use foreign memory for summary statistics storage?
MemorySegment seg = MemorySegment.allocateNative(8);
MemoryAccess.setLongAtOffset(seg, 0, 5000L);
System.out.println(MemoryAccess.getLongAtOffset(seg, 0));
seg.close();
Output: 5000
Q147. How do you use switch expressions for dashboard status indication?
String color = "green";
String status = switch (color) {
case "red" -> "Error";
case "yellow" -> "Warning";
case "green" -> "OK";
default -> "Unknown";
};
System.out.println(status);
Output: OK
Q148. How do you optimize JVM NUMA G1 for dashboard servers?
java -XX:+UseG1GC -XX:+UseNUMA -XX:MaxGCPauseMillis=30 -jar dashboardServer.jar
Output: Low latency dashboard server
Q149. How do you update scripts for Pack200 removal in dashboard deployment?
# Remove Pack200 steps
Output: Deployment successful
Q150. How do you use records for event notification structure?
record Event(String type, long ts) {}
Event evt = new Event("LOGIN", System.currentTimeMillis());
System.out.println(evt);
Output: Event[type=LOGIN, ts=…]
Q151. How do you use pattern matching for instanceof in event notification?
Object obj = new Event("LOGOUT", 123456L);
if (obj instanceof Event e) {
System.out.println("Type: " + e.type());
}
Output: Type: LOGOUT
Q152. How do you diagnose NullPointerExceptions in event notification?
Event evt = null;
try {
evt.type();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Event.type()” because “evt” is null
Q153. How do you use Non-volatile MappedByteBuffer for event log writing?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 64);
buf.put("event".getBytes());
buf.force();
Output: “event” written to file
Q154. How do you stream JFR events for event notification monitoring?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ThreadStart");
rs.onEvent("jdk.ThreadStart", e -> System.out.println("Event: Thread started: " + e.getString("threadName")));
rs.startAsync();
Output: Event: Thread started: [thread name]
Q155. How do you package an event notification app with jpackage?
jpackage --input . --main-jar event.jar --name EventApp --type exe
Output: EXE installer for EventApp
Q156. How do you use foreign memory for rapid event logging?
MemorySegment seg = MemorySegment.allocateNative(16);
MemoryAccess.setByteAtOffset(seg, 0, (byte)111);
System.out.println(MemoryAccess.getByteAtOffset(seg, 0));
seg.close();
Output: 111
Q157. How do you use switch expressions for event status reporting?
String event = "login";
String status = switch (event) {
case "login" -> "User logged in";
case "logout" -> "User logged out";
default -> "Unknown event";
};
System.out.println(status);
Output: User logged in
Q158. How do you optimize JVM NUMA G1 for event notification servers?
java -XX:+UseG1GC -XX:+UseNUMA -XX:MaxGCPauseMillis=15 -jar eventServer.jar
Output: Low latency event notification
Q159. How do you update legacy notification scripts for Pack200 removal?
# Eliminate Pack200 steps
Output: Notification system works
Q160. How do you use records for structured error reporting?
record ErrorReport(String code, String message) {}
ErrorReport err = new ErrorReport("E404", "Not Found");
System.out.println(err);
Output: ErrorReport[code=E404, message=Not Found]
Q161. How do you use pattern matching for instanceof in error reporting?
Object obj = new ErrorReport("E500", "Internal Error");
if (obj instanceof ErrorReport e) {
System.out.println("Error: " + e.code());
}
Output: Error: E500
Q162. How do you diagnose NullPointerExceptions in error reporting?
ErrorReport err = null;
try {
err.code();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “ErrorReport.code()” because “err” is null
Q163. How do you use Non-volatile MappedByteBuffer for error log writing?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 32);
buf.put("error".getBytes());
buf.force();
Output: “error” written to file
Q164. How do you stream JFR events for error detection?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ExceptionThrown");
rs.onEvent("jdk.ExceptionThrown", e -> System.out.println("Error: " + e.getString("message")));
rs.startAsync();
Output: Error: [exception message]
Q165. How do you package an error reporting tool with jpackage?
jpackage --input . --main-jar error.jar --name ErrorApp --type exe
Output: EXE installer for ErrorApp
Q166. How do you use foreign memory for storing error codes?
MemorySegment seg = MemorySegment.allocateNative(4);
MemoryAccess.setIntAtOffset(seg, 0, 404);
System.out.println(MemoryAccess.getIntAtOffset(seg, 0));
seg.close();
Output: 404
Q167. How do you use switch expressions for error severity mapping?
String sev = "critical";
String msg = switch (sev) {
case "info" -> "Informational";
case "warning" -> "Warning";
case "critical" -> "Critical Error";
default -> "Unknown";
};
System.out.println(msg);
Output: Critical Error
Q168. How do you optimize JVM NUMA G1 for error reporting servers?
java -XX:+UseG1GC -XX:+UseNUMA -XX:MaxGCPauseMillis=10 -jar errorServer.jar
Output: Low latency error reporting
Q169. How do you update scripts for Pack200 removal in error pipeline?
# Remove Pack200 steps
Output: Error pipeline runs smoothly
Q170. How do you use records for structured logs in distributed systems?
record LogMsg(String node, String msg) {}
LogMsg log = new LogMsg("node1", "Started");
System.out.println(log);
Output: LogMsg[node=node1, msg=Started]
Q171. How do you use pattern matching for instanceof in distributed logging?
Object obj = new LogMsg("node2", "Stopped");
if (obj instanceof LogMsg l) {
System.out.println("Node: " + l.node());
}
Output: Node: node2
Q172. How do you diagnose NullPointerExceptions in distributed logging?
LogMsg log = null;
try {
log.node();
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “LogMsg.node()” because “log” is null
Q173. How do you use Non-volatile MappedByteBuffer for distributed log writing?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 128);
buf.put("distributed".getBytes());
buf.force();
Output: “distributed” written to file
Q174. How do you stream JFR events for node activity in distributed systems?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ThreadStart");
rs.onEvent("jdk.ThreadStart", e -> System.out.println("Node event: " + e.getString("threadName")));
rs.startAsync();
Output: Node event: [thread name]
Q175. How do you package a distributed logging tool with jpackage?
jpackage --input . --main-jar distlog.jar --name DistLogApp --type pkg
Output: PKG installer for distributed logging
Q176. How do you use records in a multi-threaded message queue?
record Msg(String topic, String payload) {}
BlockingQueue<Msg> queue = new LinkedBlockingQueue<>();
queue.offer(new Msg("update", "data"));
Msg msg = queue.poll();
System.out.println(msg);
Output: Msg[topic=update, payload=data]
Q177. How do you use pattern matching for instanceof in a reflection utility?
Object obj = new Msg("notice", "Hello");
if (obj instanceof Msg m) {
for (var f : m.getClass().getRecordComponents()) {
System.out.println(f.getName() + ": " + f.getType());
}
}
Output: topic: class java.lang.String payload: class java.lang.String
Q178. How do Helpful NullPointerExceptions help in debugging chained method calls in scripts?
Msg msg = null;
try {
System.out.println(msg.topic().toUpperCase());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Msg.topic()” because “msg” is null
Q179. How do you use Non-volatile MappedByteBuffer for concurrent file writes?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 128);
Runnable writer = () -> { buf.put("threaded".getBytes()); buf.force(); };
new Thread(writer).start();
Output: “threaded” written to file concurrently
Q180. How do you stream JFR events for live performance diagnostics in a microservice?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.CPULoad");
rs.onEvent("jdk.CPULoad", e -> System.out.println("Load: " + e.getFloat("machineTotal")));
rs.startAsync();
Output: Load: [CPU %] (live stream)
Q181. How do you automate installer creation with jpackage for a microservice deployment pipeline?
jpackage --input . --main-jar microservice.jar --name MicroApp --type rpm
Output: RPM installer for Linux generated
Q182. How do you use Foreign-Memory Access API for off-heap caching in a high-performance app?
MemorySegment cache = MemorySegment.allocateNative(64);
MemoryAccess.setIntAtOffset(cache, 0, 222);
System.out.println(MemoryAccess.getIntAtOffset(cache, 0));
cache.close();
Output: 222
Q183. How do you use switch expressions to select deployment strategy in a CI script?
String env = "staging";
String strategy = switch (env) {
case "prod" -> "Blue-Green";
case "staging" -> "Canary";
case "dev" -> "Rolling";
default -> "Manual";
};
System.out.println(strategy);
Output: Canary
Q184. How do you tune NUMA-aware G1 GC for batch jobs on multi-socket servers?
java -XX:+UseG1GC -XX:+UseNUMA -XX:InitiatingHeapOccupancyPercent=20 -jar batch.jar
Output: NUMA-aware memory allocation with custom occupancy threshold
Q185. How do you migrate a security pipeline after Pack200 removal?
# Remove all Pack200 references; verify all JAR steps use jar/zip
Output: Security pipeline works, no Pack200 errors
Q186. How do you use records for secure token passing in authentication flows?
record Token(String value, long issuedAt) {}
Token t = new Token("secureTok", System.currentTimeMillis());
System.out.println(t);
Output: Token[value=secureTok, issuedAt=…]
Q187. How do you use pattern matching for instanceof for safe casting in plugin systems?
Object plugin = new Token("tok", 0);
if (plugin instanceof Token t) {
System.out.println("Plugin token: " + t.value());
}
Output: Plugin token: tok
Q188. How do you use Helpful NullPointerExceptions in plugin loading diagnostics?
Token t = null;
try {
System.out.println(t.value());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
Output: Cannot invoke “Token.value()” because “t” is null
Q189. How do you use Non-volatile MappedByteBuffer for plugin state persistence?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 32);
buf.put("pluginState".getBytes());
buf.force();
Output: “pluginState” written to file
Q190. How do you stream JFR events for plugin lifecycle monitoring?
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ThreadStart");
rs.onEvent("jdk.ThreadStart", e -> System.out.println("Plugin thread: " + e.getString("threadName")));
rs.startAsync();
Output: Plugin thread: [thread name]
Q191. How do you create a plugin installer with jpackage for distribution?
jpackage --input . --main-jar plugin.jar --name PluginApp --type exe
Output: EXE installer for PluginApp
Q192. How do you use Foreign-Memory Access API for plugin sandboxing?
MemorySegment seg = MemorySegment.allocateNative(16);
MemoryAccess.setByteAtOffset(seg, 0, (byte)0x7F);
System.out.println(MemoryAccess.getByteAtOffset(seg, 0));
seg.close();
Output: 127
Q193. How do you use switch expressions for plugin state transitions?
String state = "enabled";
String result = switch (state) {
case "enabled" -> "Active";
case "disabled" -> "Inactive";
default -> "Unknown";
};
System.out.println(result);
Output: Active
Q194. How do you tune NUMA G1 GC for plugin containers?
java -XX:+UseG1GC -XX:+UseNUMA -XX:MaxGCPauseMillis=25 -jar pluginContainer.jar
Output: Low GC pauses for plugin containers
Q195. How do you handle Pack200 removal in plugin build scripts?
# Remove Pack200 steps from plugin build scripts
Output: Plugin build successful
Q196. How do you use records for structured event tracking in distributed plugins?
record Event(String pluginId, String eventType) {}
Event e = new Event("pluginA", "loaded");
System.out.println(e);
Output: Event[pluginId=pluginA, eventType=loaded]
Q197. How do you use pattern matching for instanceof in distributed event tracking?
Object obj = new Event("pluginB", "error");
if (obj instanceof Event e) {
System.out.println("Event: " + e.eventType());
}
Output: Event: error
Q198. How do you use Helpful NullPointerExceptions in distributed event diagnostics?
Event e = null;
try {
System.out.println(e.pluginId());
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
}
Output: Cannot invoke “Event.pluginId()” because “e” is null
Q199. How do you use Non-volatile MappedByteBuffer for distributed plugin event persistence?
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 128);
buf.put("eventData".getBytes());
buf.force();
Output: “eventData” written to file
Q200. How do you combine records, pattern matching, helpful NullPointerExceptions, non-volatile mapped buffers, JFR streaming, jpackage, foreign memory, switch expressions, and NUMA G1 in one demonstration?
// Record
record Info(String label, int code) {}
Object obj = new Info("Test", 42);
// Pattern Matching + Switch
String result = switch (obj) {
case Info info -> "Info: " + info.label() + ", " + info.code();
case String s -> "String: " + s;
default -> "Other";
};
// NullPointerException
Info info = null;
try {
info.label();
} catch (NullPointerException e) {
System.out.println("NPE: " + e.getMessage());
}
// Non-volatile MappedByteBuffer (assume file and FileChannel 'fc' exist)
MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_WRITE, 0, 8);
buf.putInt(12345); buf.force();
// JFR streaming
RecordingStream rs = new RecordingStream();
rs.enable("jdk.ThreadStart").onEvent("jdk.ThreadStart", e -> System.out.println("Thread started: " + e.getString("threadName")));
rs.startAsync();
// Foreign memory
MemorySegment mem = MemorySegment.allocateNative(4);
MemoryAccess.setIntAtOffset(mem, 0, 67890);
int memValue = MemoryAccess.getIntAtOffset(mem, 0);
mem.close();
// Output
System.out.println(result);
System.out.println("Memory value: " + memValue);
Output: NPE: Cannot invoke “Info.label()” because “info” is null Info: Test, 42 Memory value: 67890 Thread started: [thread name] (when thread starts) [No output for buffer unless read]
Enjoy Learning !!! Please Follow and get regular updates !!
메타데이터
- post_id
- 0af7b4b07beb
- slug
- top-1-200-java-14-topics-interview-questions-with-example-output-0af7b4b07beb
- url
- https://medium.com/@bytecoders/top-1-200-java-14-topics-interview-questions-with-example-output-0af7b4b07beb
- canonical_url
- https://medium.com/@bytecoders/top-1-200-java-14-topics-interview-questions-with-example-output-0af7b4b07beb
- author_url
- https://medium.com/@bytecoders
- status
- ok
- fetched_at
- 2026-07-19 21:53:32