Nearby lessons

124 of 125

Java - Questions and Answers

📌 What You Will Learn
  • Revise every chapter with quick questions and answers
  • Learn from the common mistakes beginners make
  • Prepare for exams and interviews

Frequently asked Java questions and answers — every MCQ from all 32 chapters with explanations, plus the common mistakes beginners make in each topic.

Chapter 1 — Quick Questions

Q: Who is known as the father of Java?

A: James Gosling — James Gosling created Java. Dennis Ritchie made C, Bjarne Stroustrup made C++.

Q: Java was first released in which year?

A: 1996 — JDK 1.0 was publicly released on 23 January 1996. (1995 is the year Java was first shown publicly.)

Q: Which company now owns Java?

A: Oracle — Oracle bought Sun Microsystems in 2010 and now maintains Java.

Q: What is the output file of the Java compiler?

A: .class file — javac converts .java source into .class bytecode files.

Q: Which of these is the correct full form of JVM?

A: Java Virtual Machine — JVM = Java Virtual Machine, the engine that runs bytecode.

Q: Which Java version is the LATEST Long-Term Support (LTS) version?

A: Java 21 — Java 21 (September 2023) is the latest LTS. Java 8/11/17 are older LTS versions.

Q: Which feature of Java means 'same program runs on any operating system'?

A: Platform independence — Platform independence = Write Once, Run Anywhere.

Q: Which of the following is NOT a feature of Java?

A: Support for pointers — Java does not support pointers. It handles them safely internally.

Q: What is bytecode?

A: Intermediate code that runs on JVM — Bytecode is intermediate code stored in .class files, executed by the JVM.

Q: Which command is used to run a Java program after compilation?

A: java — javac compiles; java runs the compiled .class file.

Chapter 1 — Common Mistakes

Common Mistakes Beginners Make:
  • Confusing Java with JavaScript — they are two completely different languages, and interviewers love to catch this mistake.
  • Mixing up JDK, JRE and JVM — remember the nesting: the JDK contains the JRE, and the JRE contains the JVM.
  • Thinking the .class file is machine code that runs directly on the operating system — it is bytecode that the JVM must run.
  • Installing only a JRE and then finding that javac is missing — from Java 11 onwards there is no separate JRE, so install the JDK which includes everything.
  • Forgetting that Java is case sensitive — Name and name are two different identifiers.
  • Expecting the JVM itself to be platform independent — the Java program is independent, but each operating system has its own JVM.

Chapter 2 — Quick Questions

Q: Which command compiles a Java file?

A: javac — javac is the Java compiler. It produces .class files.

Q: After compiling First.java, which new file is created?

A: First.class — The compiler produces First.class containing bytecode.

Q: Which command runs a compiled Java class named First?

A: java First — We use java with the class name only, no extension.

Q: The file name of a public class must be ___?

A: Same as the class name — A public class must live in a file named exactly after it.

Q: Why is the main method declared as static?

A: So JVM can call it without creating an object — static lets the JVM invoke main before any object is created.

Q: What does System.out.println() do?

A: Prints text and moves to a new line — println prints the text and then a newline.

Q: Which of these is a valid comment in Java?

A: All of the above — All three types of comments are valid in Java.

Q: What happens if you type `java First.class`?

A: It gives an error — The JVM expects the class name First, not the file First.class.

Q: How do you pass command-line arguments to a program?

A: By writing them after the class name in java command — Values typed after the class name go into String[] args.

Q: Which of these is the correct way to declare main?

A: public static void main(String[] args) — public static void main(String[] args) is the exact standard signature.

Chapter 2 — Common Mistakes

Common Mistakes Beginners Make:
  • Running java First.class instead of java First — the JVM wants the class name, not the file name with its extension.
  • Saving the file as First.java.txt because the editor added .txt — always choose All Files as the save type.
  • Typing javac to run the program or java to compile it — javac compiles to a .class file, java runs it.
  • Writing the main method wrongly — missing static or void gives the "main method not found" error.
  • Keeping the file name and the class name different — class First inside Second.java will not compile.
  • Forgetting the semicolon ; at the end of a statement — the compiler reports ';' expected.

Chapter 3 — Quick Questions

Q: How many primitive data types does Java have?

A: 8 — byte, short, int, long, float, double, char, boolean — eight primitives.

Q: Which of these is a valid identifier?

A: _total — _total is valid. Identifiers cannot start with a digit or be keywords.

Q: What is the default value of an int instance variable?

A: 0 — Instance variables get default 0 for int type.

Q: What is the size of the char data type in Java?

A: 2 bytes — char is 2 bytes because Java uses the UNICODE system.

Q: Which conversion needs an explicit cast?

A: double to int — double to int is narrowing (data may be lost), so explicit cast is required.

Q: In Java, the first index of an array is ___?

A: 0 — Array indexes always start from 0.

Q: Which loop will run its body at least once even if the condition is false?

A: do-while — do-while checks the condition after running the body once.

Q: What does the continue statement do?

A: Skips the rest of current round and continues next round — continue skips the current iteration only.

Q: How is an array's size obtained?

A: array.length — length is a property, so no brackets — array.length.

Q: Which of these correctly declares a var-args parameter?

A: void m(int... x) — Three dots (int...) mark a var-args parameter.

Chapter 3 — Common Mistakes

Common Mistakes Beginners Make:
  • Writing an identifier that starts with a digit, like 1name — Java rejects it; an identifier must start with a letter, _ or $.
  • Using a keyword as a variable name — int class = 10; will never compile because class is reserved.
  • Forgetting the L on a long literal or the f on a float literal — 100 alone is an int and 3.14 alone is a double.
  • Doing a narrowing cast without brackets — int x = d; from a double gives a compile error until you write (int) d.
  • Accessing an array index outside its range — marks[5] on an array of size 5 throws ArrayIndexOutOfBoundsException because the last index is 4.
  • Mixing length with length() — arrays use length (no brackets) but String uses length() (with brackets).

Chapter 4 — Quick Questions

Q: In pattern printing, the outer loop controls ___?

A: Rows — Outer loop controls rows; inner loop controls columns.

Q: Which function prints without moving to the next line?

A: System.out.print() — print() keeps the cursor on the same line.

Q: For a left triangle of n rows, the inner loop in row i (0-based) runs how many times?

A: i + 1 — Row i has i+1 elements, so condition is j <= i.

Q: Which of these produces an inverted triangle?

A: j < n - i — j < n - i gives n stars in row 0 and fewer each row.

Q: In the output '1 2 3 / 1 2 3', the printed value depends on ___?

A: j (column) — The columns show 1 2 3, so the value comes from j + 1.

Q: Which statement is used to move to the next row in a pattern program?

A: System.out.println() — println() ends the current line and starts the next row.

Q: Floyd's triangle prints ___?

A: Counting numbers in a triangle — Floyd's triangle prints consecutive counting numbers.

Q: How many loops are needed for a right-aligned triangle (spaces + stars)?

A: 3 — Two value loops (spaces + stars) plus the outer loop = three loops total.

Chapter 4 — Common Mistakes

Common Mistakes Beginners Make:
  • Using System.out.println() for the stars — every star goes on its own line instead of side by side; use print() for columns and println() only after each row.
  • Forgetting the println() after the inner loop — all the rows print on one single line.
  • Writing j < i instead of j <= i in a left triangle — row i prints only i stars instead of i+1, so every row is one star short.
  • Keeping the inner condition as j < n when building a triangle — you get a square because every row has the same number of stars.
  • Printing the spaces loop after the value loop in a right-aligned triangle — the stars come first and the alignment breaks.
  • Using the wrong loop to change a pattern — changing the outer loop changes the number of rows, not the shape of each row.

Chapter 5 — Quick Questions

Q: Which pillar of OOP hides data and only allows access through methods?

A: Encapsulation — Encapsulation wraps data with methods and keeps fields private.

Q: What is the default value given by Java for an object reference?

A: null — Reference variables default to null.

Q: Which keyword is used to inherit a class in Java?

A: extends — A class inherits another class with extends.

Q: Method overloading is decided at ___?

A: Compile time — The compiler decides which overloaded method to call, so it is compile time.

Q: Which of these is true about a constructor?

A: Its name equals the class name — Constructor name matches the class name and has no return type.

Q: Which keyword refers to the current object?

A: this — this refers to the current object inside a class.

Q: A class marked with which keyword cannot be extended?

A: final — final class cannot be inherited (like String).

Q: Which statement correctly creates an object of class Student?

A: Student s = new Student(); — new Student() creates the object and assigns it to reference s.

Q: Interfaces in Java are used to achieve which type of inheritance?

A: Multiple — A class can implement many interfaces, giving multiple inheritance.

Q: In Composition, if the whole is destroyed, the part ___?

A: Is also destroyed — Composition is a strong has-a relation — part dies with the whole.

Chapter 5 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting the parentheses in new Student() — new Student alone is a syntax error; the object is created only with the constructor call.
  • Writing a return type on a constructor, like void Student() — that turns it into a normal method, so the object is never initialised the way you expect.
  • Trying to create an object of an abstract class or interface with new — abstract classes and interfaces cannot be instantiated; create the child class object instead.
  • Writing class A extends B, C to inherit from two classes — Java allows only single inheritance with classes; use interfaces for multiple inheritance.
  • Accessing an instance variable directly inside a static method — a static method belongs to the class and may run when no object exists, so this is a compile error.

Chapter 6 — Quick Questions

Q: An inner class is a class declared ___?

A: Inside another class — Inner classes are declared inside another class.

Q: Which inner class does NOT need an object of the outer class?

A: Static nested class — Static nested class can be created with Outer.Nested directly.

Q: How do you create a member inner class object?

A: outer.new Inner() — Member inner class needs an outer object: outer.new Inner().

Q: An anonymous inner class ___?

A: Has no name — Anonymous means without a name.

Q: What does an anonymous inner class mainly provide?

A: A quick one-time implementation of an interface/abstract class — It is used for short, one-time implementations.

Q: Which statement is TRUE about a local inner class?

A: It is declared inside a method — Local inner classes are declared inside methods.

Q: In modern Java, a one-method interface can be implemented more simply using ___?

A: A lambda expression — Lambdas replace anonymous classes for functional interfaces.

Q: The member inner class can access ___ of the outer class?

A: Even private members — Inner classes can access the outer class's private members.

Chapter 6 — Common Mistakes

Common Mistakes Beginners Make:
  • Trying to create a member inner class with new Inner() directly — a non-static inner class needs an outer object, so the syntax is outer.new Inner().
  • Accessing the outer class's instance variables from a static nested class — a static nested class is tied to the class, not to an object, so non-static members are not directly available.
  • Declaring a local inner class in a method and trying to use it outside the method — a local class is visible only inside the method where it is declared.
  • Forgetting the semicolon ; after an anonymous inner class definition — the anonymous class is an expression, so it must end with ; like a statement.
  • Writing new Greeting() with nothing after it — an interface cannot be instantiated; you must provide the implementation body in braces right after the new.

Chapter 7 — Quick Questions

Q: Which is the wrapper class of int?

A: Integer — Integer is the wrapper class for int.

Q: Autoboxing means ___?

A: Primitive to object automatically — Autoboxing wraps a primitive into its wrapper automatically.

Q: Which method converts "100" into primitive int 100?

A: Integer.parseInt("100") — parseInt returns a primitive int; valueOf returns an Integer object.

Q: Integer a = 100; Integer b = 100; a == b gives ___?

A: true — Values -128..127 are cached, so both point to the same object.

Q: Integer c = 1000; Integer d = 1000; c == d gives ___?

A: false — 1000 is outside the cache, so two different objects are made.

Q: Which keyword converts a primitive to String safely?

A: Integer.toString — toString converts primitives to String; parseXxx does the reverse.

Q: Which is the wrapper class for boolean?

A: Boolean — Boolean (capital B) is the wrapper class.

Q: Why can't ArrayList be used directly?

A: Because int is not a class — Collections store only objects, so we must use Integer instead of int.

Chapter 7 — Common Mistakes

Common Mistakes Beginners Make:
  • Trying to store a primitive int directly in an ArrayList — collections accept only objects, so you must use the wrapper Integer instead.
  • Comparing wrapper objects with == — for values outside the cached range (-128 to 127), Java makes new objects, so == can give false even for equal values; use .equals().
  • Mixing up Integer.parseInt("100") and Integer.valueOf("100") — parseInt returns an int (primitive) while valueOf returns an Integer (object), so using the wrong one causes type errors.
  • Calling intValue() on an Integer that is null — unboxing a null reference throws a NullPointerException at run time.
  • Passing a non-numeric String to parseInt — Integer.parseInt("abc") throws a NumberFormatException, so the input must be checked first.

Chapter 8 — Quick Questions

Q: Which statement must be the first in a file to create a package?

A: package — package statement comes first, then imports, then the class.

Q: Which package is automatically imported into every Java program?

A: java.lang — java.lang is automatically available (String, System, Math).

Q: A private member is accessible in ___?

A: Same class only — private is the most restricted — same class only.

Q: Which modifier makes a member visible in child classes of other packages too?

A: protected — protected allows access to sub classes across packages.

Q: What does `import mypack.*;` do?

A: Imports all classes of mypack — The * (wildcard) imports all public classes of the package.

Q: A top-level class can have which access modifiers?

A: public and default — Top-level classes are public or default (package-private).

Q: The classpath is ___?

A: The location where JVM searches for classes — Classpath lists folders/jars where the JVM looks for compiled classes.

Q: Which tool packages many .class files into a single archive?

A: jar — The jar tool creates Java archives.

Chapter 8 — Common Mistakes

Common Mistakes Beginners Make:
  • Writing the package statement after the import or class declaration — the package statement must be the very first statement in the file, before anything else.
  • Forgetting to compile with javac -d . — without the -d option the compiler does not create the package folder, and the .class file lands in the wrong directory.
  • Declaring a top-level class as private or protected — a top-level class can only be public or default (package-private).
  • Using a class from another package without import or a fully qualified name — the compiler reports 'cannot find symbol' because the class is not visible.
  • Writing package names like example.com or with capital letters — the Java convention is small letters with the domain reversed, for example com.example.

Chapter 9 — Quick Questions

Q: Which statement about String is TRUE?

A: String is immutable — String is an immutable class.

Q: Which class is NOT thread-safe but is the fastest for editing text?

A: StringBuilder — StringBuilder is fastest but not thread-safe.

Q: String a = "Java"; String b = "Java"; a == b returns ___?

A: true — Both literals share the same String pool object, so == is true.

Q: String a = "Java"; String c = new String("Java"); a == c returns ___?

A: false — new String creates a different object, so references differ.

Q: Which method removes spaces from both ends of a String?

A: Both strip() and trim() — Both trim() and the modern strip() remove edge spaces.

Q: How do you convert a String to lowercase?

A: s.toLowerCase() — toLowerCase() converts to lowercase.

Q: What does "Program".substring(3) return?

A: gram — substring(3) returns characters from index 3 onwards.

Q: Which method splits a String into parts based on a delimiter?

A: split() — split(regex) returns a String array.

Q: The default toString() of an object prints ___?

A: Class name @ memory code — By default it prints classname@hashcode; we override it.

Q: StringBuilder is best used when ___?

A: Building text repeatedly in a single thread — Use StringBuilder for repeated single-threaded editing.

Chapter 9 — Common Mistakes

Common Mistakes Beginners Make:
  • Comparing String content with == instead of .equals() — == compares references, so two strings created with new that hold the same text return false.
  • Calling immutable methods like concat(), trim() or toUpperCase() and ignoring the returned value — the original String never changes, so the result is silently lost.
  • Building text with + inside a loop — every concatenation creates a new String object, making the loop slow; use StringBuilder instead.
  • Forgetting that substring(a, b) stops at index b - 1, so "Chocolate".substring(2, 6) gives ocol and not the first six characters.
  • Passing a regex special character like . to split() without escaping — "a.b".split(".") returns an empty array because . matches any character.

Chapter 10 — Quick Questions

Q: Which keyword is used to handle exceptions?

A: catch — catch catches and handles the exception.

Q: What happens if an exception is not handled?

A: Program crashes with an error message — An unhandled exception terminates the program.

Q: Which block ALWAYS executes?

A: finally — finally runs regardless of exception or not.

Q: Checked exceptions must be ___?

A: Handled using try-catch or throws — The compiler forces checked exceptions to be handled.

Q: Which of these is an unchecked exception?

A: ArithmeticException — ArithmeticException extends RuntimeException, so it is unchecked.

Q: What does the throw keyword do?

A: Actually throws an exception — throw raises the exception; throws is only a declaration.

Q: What does the throws keyword do?

A: Declares possible exceptions in the method signature — throws is a warning written in the method declaration.

Q: How do you create a custom exception?

A: Extend Exception or RuntimeException — Custom exceptions extend Exception (checked) or RuntimeException.

Q: try-with-resources automatically ___?

A: Closes the resource — It closes AutoCloseable resources automatically.

Q: An Error (like OutOfMemoryError) should be ___?

A: Fixed at the code level, not caught — Errors are serious system problems; we fix the code, not catch them.

Chapter 10 — Common Mistakes

Common Mistakes Beginners Make:
  • Putting the general catch (Exception e) before specific catches like ArithmeticException — the specific catch becomes unreachable and the code does not compile.
  • Writing an empty catch block to swallow the exception — the program keeps running but the real bug is hidden and never fixed.
  • Forgetting to close a file, stream or connection — the resource stays open and leaks memory; use try-with-resources.
  • Confusing throw with throws — throw raises the exception inside the body, throws only declares it in the method signature.
  • Creating a custom exception class without extending Exception or RuntimeException — it is not an exception and cannot be thrown with throw.

Chapter 11 — Quick Questions

Q: A running program is called ___?

A: A process — A running program is a process; threads run inside it.

Q: Which method starts a thread's execution?

A: start() — start() creates the new thread and then calls run().

Q: Calling run() directly instead of start() ___?

A: Runs it in the same thread — Only start() makes a new thread; run() runs in the current thread.

Q: Which interface should we implement to make a class a thread job?

A: Runnable — Runnable has the single run() method.

Q: The synchronized keyword is used to ___?

A: Allow only one thread in a block at a time — synchronized provides a lock, allowing one thread at a time.

Q: Which method makes the current thread wait for a fixed time?

A: sleep() — sleep(ms) pauses the thread for the given milliseconds.

Q: wait() and notify() must be called from ___?

A: A synchronized block — They need the lock, so they must be inside synchronized code.

Q: When all non-daemon threads finish, daemon threads ___?

A: Are stopped automatically — The JVM exits and daemon threads stop automatically.

Q: Which situation is called deadlock?

A: Two threads wait on each other's locks — Deadlock = circular waiting for each other's locks.

Q: Which class manages a pool of threads in modern Java?

A: ExecutorService — ExecutorService manages a pool of reusable threads.

Chapter 11 — Common Mistakes

Common Mistakes Beginners Make:
  • Calling run() directly instead of start() — the job runs in the current thread and no new thread is ever created.
  • Extending the Thread class when the class already extends another class — Java allows only one parent; implement Runnable instead.
  • Sharing a mutable variable between threads without synchronized — the updates race and some additions get lost, exactly like the balance example.
  • Calling wait() or notify() outside a synchronized block — they need the lock and throw IllegalMonitorStateException.
  • Forgetting shutdown() on an ExecutorService — the pool threads keep running and the program never exits.

Chapter 12 — Quick Questions

Q: Which package contains Java IO classes?

A: java.io — java.io has all stream and file classes.

Q: Which pair is used for reading and writing text files?

A: Reader / Writer — Character streams (Reader/Writer) are for text.

Q: Which class reads a whole line easily?

A: BufferedReader — BufferedReader.readLine() returns each line.

Q: What does FileReader.read() return at the end of the file?

A: -1 — -1 signals end of file.

Q: Which class is the simplest to read numbers from the keyboard?

A: Scanner — Scanner reads nextInt(), nextDouble(), etc. easily.

Q: Which streams are used to copy an image file?

A: Byte streams — Binary files need byte streams to avoid corruption.

Q: What must a class implement to be serialized?

A: Serializable — Serializable is the marker interface for saving objects.

Q: Which keyword stops a field from being saved during serialization?

A: transient — transient fields are skipped during serialization.

Q: Which File class method returns the file size in bytes?

A: length() — File.length() gives the size in bytes.

Q: How do you write to a file at the end instead of overwriting?

A: Use append(true) in FileWriter — new FileWriter(name, true) appends instead of overwriting.

Chapter 12 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting to close a stream after writing — data may not be flushed to the file and resources leak; always close or use try-with-resources.
  • Using a character stream like FileReader to copy a binary file such as an image — the bytes get corrupted; use byte streams instead.
  • Testing read() against 0 instead of -1 for the end of file — read() returns -1 at EOF, so the loop reads forever.
  • Serializing a class that does not implement Serializable — the program throws NotSerializableException.
  • Creating a File object and expecting the file to appear — new File("x.txt") only represents the path; you must call createNewFile() to actually create it.

Chapter 13 — Quick Questions

Q: Which class does a server use to listen for clients?

A: ServerSocket — ServerSocket listens; accept() returns a Socket for the client.

Q: Which class does a client use to connect to a server?

A: Socket — The client creates a Socket with the server's IP and port.

Q: Which protocol is reliable and keeps data in order?

A: TCP — TCP guarantees delivery and order.

Q: Which protocol is used for live video where small loss is acceptable?

A: UDP — UDP is fast and suits live media where tiny losses are fine.

Q: The port number tells us ___?

A: Which service/program on that computer — Port identifies a specific service on a machine.

Q: Which method makes a server wait for a client?

A: accept() — ServerSocket.accept() blocks until a client connects.

Q: What is 'localhost'?

A: This computer itself — localhost refers to your own machine (127.0.0.1).

Q: Which class represents a web address like https://www.google.com?

A: URL — URL parses and works with web addresses.

Chapter 13 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting to start the server before running the client — the client throws ConnectException because nothing is listening on that port yet.
  • Using the same port for two servers at once — the port is already occupied, so the second ServerSocket throws BindException.
  • Forgetting the imports java.net.* and java.io.* — Socket and ServerSocket then show 'cannot find symbol' errors.
  • Calling accept() on the client side — only the server calls accept(); the client simply creates new Socket(ip, port) to connect.
  • Confusing ServerSocket with Socket — the ServerSocket only waits for connections; the actual talking happens through the Socket returned by accept().
  • Not closing the socket and server socket at the end — open ports leak, and the server cannot restart cleanly on the same port.

Chapter 14 — Quick Questions

Q: RMI stands for ___?

A: Remote Method Invocation — RMI = Remote Method Invocation.

Q: Which class is the client-side stand-in for the remote object?

A: Stub — The stub is the local representative the client calls.

Q: Which part receives the request on the server and calls the real method?

A: Skeleton — The skeleton (now automatic) dispatches to the real object.

Q: A remote interface must extend which interface?

A: Remote — The remote interface extends java.rmi.Remote.

Q: What is the RMI Registry?

A: A phonebook that connects names to remote objects — The registry maps service names to remote objects.

Q: Remote methods must declare which exception?

A: RemoteException — RemoteException is the network-related exception.

Q: An RMI server object typically extends which class?

A: UnicastRemoteObject — UnicastRemoteObject makes the object network-callable.

Q: Modern distributed applications mostly use ___ instead of RMI?

A: REST web services with JSON — REST over HTTP with JSON is the modern standard.

Chapter 14 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting to declare throws RemoteException on the interface methods — the compiler refuses because remote calls can fail over the network.
  • Starting the client before the registry and server — the lookup() fails because no object with that name is registered yet.
  • Forgetting to extend UnicastRemoteObject in the implementation class — the object is not network-callable, and exporting it throws RemoteException.
  • Binding the same name twice with bind() — it throws AlreadyBoundException; use rebind() to overwrite a name safely.
  • Calling LocateRegistry.createRegistry() on the client side — creating the registry is the server's job; the client only calls getRegistry().
  • Mismatching the service name in rebind() and lookup() — the client gets NotBoundException because the names must match exactly.

Chapter 15 — Quick Questions

Q: Which collection allows duplicate elements?

A: List — Lists allow duplicates; Sets and Map keys do not.

Q: Which collection never allows duplicates?

A: HashSet — A Set rejects duplicates by design.

Q: Which class sorts a list?

A: Collections — Collections.sort(list) sorts any List.

Q: Which Map implementation gives insertion order?

A: LinkedHashMap — LinkedHashMap keeps insertion order.

Q: Which Map implementation sorts entries by key?

A: TreeMap — TreeMap keeps keys sorted.

Q: HashMap uses which method to decide the bucket of a key?

A: hashCode() — hashCode() decides the bucket; equals() checks equality.

Q: To sort objects by a custom rule, use ___?

A: Comparator — Comparator provides custom sorting rules.

Q: Which collection works like a ticket line (FIFO)?

A: Queue — Queue follows First In First Out.

Q: What happens if you put the same key twice in a HashMap?

A: It updates the old value — The old value is replaced by the new one.

Q: Which of these is a utility class?

A: Collections — Collections is the static utility class; the others are data structures.

Chapter 15 — Common Mistakes

Common Mistakes Beginners Make:
  • Confusing Collection (the interface) with Collections (the utility class) — trying to write new Collections() fails because you cannot instantiate a static utility class.
  • Forgetting the generic type and writing raw new ArrayList() — you get raw-type warnings, extra casting, and the compiler no longer checks what goes in.
  • Changing a collection with its own remove() while looping with a for-each or Iterator — throws ConcurrentModificationException; always remove through the cursor's remove().
  • Using an index on a Set or treating a Map like a list — set.get(0) and map.get(0) do not exist; Sets have no positions and Maps are looked up by key.
  • Overriding equals() without also overriding hashCode() consistently — a HashMap can then store the same logical key twice and lookups fail.
  • Calling add() on a Map — Map has no add(); entries go in with put(key, value).

Chapter 16 — Quick Questions

Q: What is the main benefit of generics?

A: Compile-time type safety — Generics catch type mistakes at compile time.

Q: Which syntax declares a generic class?

A: class Box — The type parameter is written in angle brackets .

Q: What does the diamond operator <> do?

A: Lets the compiler infer the type — new Box<>() lets Java guess the type from the left side.

Q: means ___?

A: T must be Number or its subclass — It bounds T to Number and its children.

Q: Which wildcard accepts a list of any type?

A: ? — A bare ? accepts any type.

Q: A method that only READS from a collection should use which wildcard?

A: ? extends T — Producer (reads) extends — PECS.

Q: What is type erasure?

A: Removing generic types at run time — Generics are erased when the code is compiled.

Q: Which of these is a valid generic object?

A: ArrayList — Generics work with classes, so we use Integer, not int.

Q: Before generics, a mistake like adding a String to a number list was found ___?

A: At run time — It crashed at run time — that was the problem generics solved.

Q: PECS stands for ___?

A: Producer Extends, Consumer Super — Producer Extends (read), Consumer Super (write).

Chapter 16 — Common Mistakes

Common Mistakes Beginners Make:
  • Using a primitive type in generics — ArrayList does not compile; you must use the wrapper class, ArrayList.
  • Forgetting the diamond or type argument on the right side — a raw new ArrayList() disables compile-time checking and needs manual casts everywhere.
  • Putting the type parameter after the return type in a generic method — the must come before the return type, as in static void printAll(T[] items).
  • Testing generics with instanceof — list instanceof List is a compile error because at run time the type has been erased.
  • Confusing ? extends T with ? super T — a method that writes (adds) into a collection needs ? super T; with ? extends T the compiler cannot know the exact type and rejects the add.
  • Using a bare wildcard List and then trying to add an element — a List allows reading but not adding, so list.add("x") does not compile.

Chapter 17 — Quick Questions

Q: Which package contains Swing components?

A: javax.swing — Swing components (JButton, JFrame) live in javax.swing.

Q: Which class creates a window in Swing?

A: JFrame — JFrame is the main window class in Swing.

Q: AWT components are ___?

A: Heavyweight, OS-provided — AWT uses the operating system's own components.

Q: Which layout divides the window into five regions?

A: BorderLayout — BorderLayout: North, South, East, West, Center.

Q: Which method shows the frame?

A: setVisible(true) — setVisible(true) makes the frame appear.

Q: Which listener handles button clicks?

A: ActionListener — ActionListener.actionPerformed runs on button click.

Q: Which component is used for one line of text input?

A: JTextField — JTextField is the single-line input box.

Q: Which Swing component shows a drop-down list?

A: JComboBox — JComboBox is the drop-down; JList shows a boxed list.

Q: The modern replacement of Swing is ___?

A: JavaFX — JavaFX is Oracle's modern desktop GUI toolkit.

Q: To choose exactly ONE option from several, use ___?

A: JRadioButton — Radio buttons allow single selection; check boxes allow many.

Chapter 17 — Common Mistakes

Common Mistakes Beginners Make:
  • Calling setVisible(true) before adding the components — the window opens but looks empty.
  • Forgetting setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) — the program keeps running even after you press the close button.
  • Using setBounds(...) while a layout manager is active — the manager ignores your coordinates and places the components itself.
  • Using setLayout(null) and then forgetting setBounds(...) — the component stays at size zero, so nothing shows up.
  • Forgetting the imports javax.swing.* and java.awt.event.* — the code will not compile.
  • Adding components to the frame *after* setVisible(true) — the window does not refresh and the new component stays invisible.

Chapter 18 — Quick Questions

Q: I18N stands for ___?

A: Internationalization — I - 18 letters - N = Internationalization.

Q: Which class identifies a language and country?

A: Locale — Locale defines language and country.

Q: Resource bundle files end with which extension?

A: .properties — Properties files use the .properties extension.

Q: Which class loads the correct language file?

A: ResourceBundle — ResourceBundle.getBundle picks the right file.

Q: Which method reads a value from a resource bundle?

A: getString() — getString(key) returns the text for that key.

Q: Localization (L10N) means ___?

A: Translating into one specific language — L10N is the actual translation work for a specific locale.

Q: To support a new language, you mostly need ___?

A: A new properties file — Add a properties file — the code stays unchanged.

Q: Which class formats currency for a locale?

A: NumberFormat — NumberFormat.getCurrencyInstance(locale) formats currency.

Chapter 18 — Common Mistakes

Common Mistakes Beginners Make:
  • Misspelling a key — getString("welcom") throws MissingResourceException because the key must match the file exactly.
  • Naming the file wrongly, like Messages_en.Properties — the base name and the .properties extension must be exact, and the file must be on the classpath.
  • Swapping the arguments — ResourceBundle.getBundle(locale, "messages") fails because the base name comes first.
  • Writing new Locale("en_US") — the language code cannot hold an underscore; use new Locale("en", "US").
  • Saving the properties file in a non-UTF-8 encoding — Hindi and Telugu text comes out as garbage (????).
  • Forgetting a default messages.properties file — the program crashes for any language that has no bundle.

Chapter 19 — Quick Questions

Q: Reflection means ___?

A: Inspecting classes at run time — Reflection examines and uses classes while the program runs.

Q: Which object describes a loaded class?

A: Class — Every class has a Class object holding its description.

Q: Which method loads a class by its name?

A: Class.forName() — Class.forName("java.lang.String") loads a class.

Q: Which method calls a method found by reflection?

A: invoke() — Method.invoke(obj, args...) calls the reflected method.

Q: Which method gives access to private fields?

A: setAccessible(true) — setAccessible(true) bypasses access checks.

Q: Which framework uses reflection to find @Test methods?

A: JUnit — JUnit reflects over classes to find @Test methods.

Q: The package for reflection classes is ___?

A: java.lang.reflect — Reflection classes live in java.lang.reflect.

Q: Why is reflection avoided in performance-critical loops?

A: It is slower than normal calls — Reflection is slower, so it is used at startup, not in hot paths.

Chapter 19 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting the full, qualified class name in Class.forName("ArrayList") — you must write "java.util.ArrayList".
  • Calling getMethod() with the wrong parameter types — c.getMethod("add", String.class) throws NoSuchMethodException because add takes an Object.
  • Forgetting that reflective code throws checked exceptions — Class.forName(...) and invoke(...) require throws Exception or try-catch.
  • Reading a private field with get() but passing no object — get(null) works only for static fields; an instance field needs the object itself.
  • Using getMethods() when you want private members — it returns only public ones; use getDeclaredMethods() for private ones.
  • Using reflection in a performance-critical loop — it is much slower than a normal method call and can slow the program badly.

Chapter 20 — Quick Questions

Q: An annotation is ___?

A: Metadata attached to code — Annotations are metadata that tools read.

Q: Which annotation checks that a method correctly overrides a parent method?

A: @Override — @Override makes the compiler check the override.

Q: Which annotation marks code as old and not recommended?

A: @Deprecated — @Deprecated warns users that the code is outdated.

Q: @Retention controls ___?

A: How long the annotation is kept — @Retention decides SOURCE, CLASS or RUNTIME lifetime.

Q: Which annotation value allows reflection to read it?

A: RetentionPolicy.RUNTIME — RUNTIME keeps the annotation visible to reflection.

Q: Custom annotations are declared using which keyword?

A: @interface — @interface declares a custom annotation.

Q: Which Spring annotation marks a web controller?

A: @RestController — @RestController is Spring's web controller annotation.

Q: @Target(ElementType.METHOD) means the annotation ___?

A: Works only on methods — @Target restricts where the annotation can appear.

Chapter 20 — Common Mistakes

Common Mistakes Beginners Make:
  • Putting @Override on a method that does not actually override anything — the compiler gives an error, not a warning.
  • Forgetting @Retention(RetentionPolicy.RUNTIME) on a custom annotation — reflection cannot see it and isAnnotationPresent() always returns false.
  • Using @Target(ElementType.METHOD) and then placing the annotation on a class — the compiler rejects it.
  • Declaring the custom annotation as interface instead of @interface — it becomes an ordinary interface, not an annotation.
  • Writing the member value without parentheses — @MyTest value = 5 must be @MyTest(value = 5).
  • Expecting @SuppressWarnings to fix errors — it only silences warnings, never compile errors.

Chapter 21 — Quick Questions

Q: Which class compiles a regular expression?

A: Pattern — Pattern.compile() compiles the regex; Matcher searches.

Q: Which method moves to the next match?

A: find() — Matcher.find() finds successive matches.

Q: Which pattern matches a single digit?

A: \d — \d matches one digit (0-9).

Q: What does the + quantifier mean?

A: One or more — + means one or more of the previous character.

Q: Which pattern matches an optional character?

A: ? — ? means zero or one (optional).

Q: Which String method checks if the WHOLE string matches?

A: matches() — String.matches() returns true only if the whole string matches.

Q: Which method replaces every match in a String?

A: replaceAll() — replaceAll(regex, replacement) replaces all matches.

Q: In a Java string, how do you write the digit pattern \d?

A: "\\d" — The backslash must be escaped, so we write "\\d".

Q: Which pattern matches any word character?

A: \w — \w matches letters, digits and underscore.

Q: Which symbol matches the start of the line?

A: ^ — ^ anchors to the start; $ anchors to the end.

Chapter 21 — Common Mistakes

Common Mistakes Beginners Make:
  • Writing the digit pattern as "\d" instead of "\\d" in a Java string — the single backslash is swallowed, so the regex engine sees the wrong pattern and the match fails.
  • Using String.matches() to search anywhere in the text — matches() is true only when the whole string matches, so a pattern that finds a match inside a longer string returns false.
  • Confusing * with + — * allows zero matches, so a validation like [0-9]* happily accepts an empty string where at least one digit was expected.
  • Forgetting to escape the dot — . matches any character, so split(".") splits between every character instead of at the full stops.
  • Calling m.find() only once and missing the rest of the matches — you need a loop like while (m.find()) to step through every match in the text.

Chapter 22 — Quick Questions

Q: What does the Garbage Collector do?

A: Frees memory of unused objects — The GC automatically frees memory of unreachable objects.

Q: When is an object eligible for garbage collection?

A: When no reference reaches it — Unreachable objects become garbage.

Q: Which statement marks an object as garbage?

A: obj = null — Setting the reference to null makes the object unreachable.

Q: What does System.gc() do?

A: Requests the GC to run — System.gc() is only a request, not a command.

Q: Which method was removed and replaced by Cleaner?

A: finalize() — finalize() is deprecated/removed since Java 9/18.

Q: Where do Java objects live?

A: Heap — Objects live in the heap memory area.

Q: Which GC is the default since Java 9?

A: G1 GC — G1 (Garbage First) became the default in Java 9.

Q: The idea that most objects die young is called ___?

A: Generational collection — Generational GC assumes most objects die quickly.

Chapter 22 — Common Mistakes

Common Mistakes Beginners Make:
  • Calling System.gc() and expecting memory to be freed instantly — it is only a *request*, the JVM may ignore it, and forcing it too often slows the app.
  • Thinking two objects that point only to each other are never garbage — an unreachable cycle is still collected because nothing outside refers to it.
  • Writing obj.free() or obj.delete() like in C/C++ — Java has no manual memory-free operator; the Garbage Collector does that work automatically.
  • Using finalize() in new code — it has been deprecated since Java 9 and removed in Java 18; use try-with-resources or Cleaner instead.
  • Believing an object stays alive just because a local variable refers to it — when the method returns, the reference dies and the object becomes garbage.

Chapter 23 — Quick Questions

Q: Which subsystem loads .class files into memory?

A: Class Loader — The Class Loader Subsystem loads and prepares classes.

Q: Where do actual objects live?

A: Heap — Objects and arrays live in the heap.

Q: Where do local variables of a method live?

A: Stack — Each thread's stack holds its local variables.

Q: Which part of the JVM speeds up frequently used methods?

A: JIT Compiler — JIT compiles hot methods into fast machine code.

Q: What does the Interpreter do?

A: Runs bytecode instruction by instruction — The interpreter executes bytecode line by line.

Q: The Method Area stores ___?

A: Class definitions and static variables — Method Area holds class metadata and statics.

Q: Who frees memory in the heap?

A: Garbage Collector — The GC automatically frees unused heap objects.

Q: Which statement is TRUE?

A: Primitives and references live in the stack — Stack holds primitives and references; heap holds objects.

Chapter 23 — Common Mistakes

Common Mistakes Beginners Make:
  • Saying objects live in the stack — actual objects live in the heap; the stack holds primitives and references to objects.
  • Thinking every thread has its own heap — the heap and method area are shared by all threads; the stack is the per-thread area.
  • Believing the JIT compiles everything before the program starts — the interpreter begins first and the JIT only compiles the hot methods used again and again.
  • Expecting classes to load the moment the program starts — class loading is lazy, so a class loads only when it is first actually used.
  • Mixing up the Method Area with the Stack — the Method Area holds class definitions and static variables for all threads, while the Stack holds one thread's local variables.

Chapter 24 — Quick Questions

Q: JDBC stands for ___?

A: Java Database Connectivity — JDBC = Java Database Connectivity.

Q: Which method gets a database connection?

A: DriverManager.getConnection(url, u, p) — DriverManager.getConnection() establishes the connection.

Q: Which statement type is best to prevent SQL injection?

A: PreparedStatement — PreparedStatement uses ? placeholders and is injection-safe.

Q: What does executeUpdate() return for an INSERT?

A: Number of rows affected — executeUpdate returns the count of changed rows.

Q: Which method runs a SELECT query?

A: executeQuery() — executeQuery returns a ResultSet for SELECT.

Q: Which method moves to the next row of a ResultSet?

A: next() — rs.next() advances and returns false at the end.

Q: The MySQL default port is ___?

A: 3306 — MySQL listens on port 3306 by default.

Q: In a transaction, which method UNDOES changes on failure?

A: rollback() — rollback() undoes all uncommitted changes.

Q: Which connection method disables auto-commit for transactions?

A: setAutoCommit(false) — setAutoCommit(false) gives manual control.

Q: Which statement is used to call a stored procedure?

A: CallableStatement — CallableStatement calls stored procedures.

Chapter 24 — Common Mistakes

Common Mistakes Beginners Make:
  • Joining user input into an SQL string with + — a value like ' OR '1'='1 can break the query or wipe data (SQL injection); always use PreparedStatement with ? placeholders.
  • Using executeUpdate() for a SELECT (or executeQuery() for an INSERT) — executeQuery returns a ResultSet, while executeUpdate returns the number of rows changed.
  • Reading a column before calling rs.next() — getXxx() works only on the current row, and before the first next() call there is no row to read.
  • Forgetting to close Connection, Statement and ResultSet — database connections are limited resources; use try-with-resources so they close automatically.
  • Calling rollback() without setAutoCommit(false) — with auto-commit on, every statement is saved instantly, so there is nothing left to undo.

Chapter 25 — Quick Questions

Q: Which Java version introduced Lambda expressions?

A: Java 8 — Java 8 (2014) brought lambdas and streams.

Q: A functional interface has exactly ___ abstract method(s).

A: One — Exactly one abstract method — that is what makes it lambda-ready.

Q: Which interface has a method boolean test(T)?

A: Predicate — Predicate.test() returns true or false.

Q: Which interface's method is void accept(T)?

A: Consumer — Consumer.accept() takes a value and returns nothing.

Q: What does the :: symbol do?

A: Method reference shorthand — :: refers to an existing method in a lambda.

Q: Which stream method keeps only matching elements?

A: filter — filter(predicate) keeps only elements where the test is true.

Q: Which stream method converts every element?

A: map — map(function) transforms each element.

Q: What does Optional.of(value) do?

A: Creates a box holding that value — Optional.of wraps a non-null value in a box.

Q: Which method gives a default value when an Optional is empty?

A: orElse() — orElse(default) returns the value or the default.

Q: Which class represents just a date (no time)?

A: LocalDate — LocalDate is date only; LocalDateTime has date and time.

Chapter 25 — Common Mistakes

Common Mistakes Beginners Make:
  • Using a lambda with an interface that has two abstract methods — a lambda only works with a functional interface that has exactly one abstract method.
  • Forgetting to import java.util.function.* or java.util.stream.* — Predicate, Function, Collectors will not compile without the import.
  • Expecting the original list to change after list.stream().filter(...) — streams produce a new result, and without collect(...) the pipeline never creates anything.
  • Calling Optional.get() without checking isPresent() — on an empty Optional it throws NoSuchElementException, the same crash you were trying to avoid.
  • Assuming months start at 0 in java.time like the old Date class — in LocalDate, January is 1, not 0.
  • Trying to break out of a forEach(...) loop — it is a method that takes a lambda, so break and continue are compile errors inside it.

Chapter 26 — Quick Questions

Q: Which tool lets you test Java code interactively?

A: JShell — JShell gives instant answers without files.

Q: JPMS stands for ___?

A: Java Platform Module System — JPMS = Java Platform Module System.

Q: The module descriptor file is called ___?

A: module-info.java — Every module has a module-info.java file.

Q: Which keyword in module-info declares what a module needs?

A: requires — requires lists packages the module needs.

Q: List.of("A", "B") creates ___?

A: An immutable list — List.of creates an immutable (unchangeable) list.

Q: What happens if you try to add to a List.of collection?

A: UnsupportedOperationException — The collection is immutable, so adding throws an exception.

Q: Which Java version allowed private methods in interfaces?

A: Java 9 — Java 9 added private interface methods.

Q: Java 9's try-with-resources allows ___?

A: Using variables declared outside the try — You can use already-declared resource variables.

Chapter 26 — Common Mistakes

Common Mistakes Beginners Make:
  • Calling add() on a List.of(...) collection — these collections are immutable, so every change throws UnsupportedOperationException.
  • Passing more than 10 pairs to Map.of(...) — it accepts at most 10; use Map.ofEntries(...) for larger maps.
  • Forgetting module-info.java when trying to use modules — without the descriptor, the code is treated as an unnamed module and exports/requires have no effect.
  • Reassigning a resource variable that is used in try-with-resources — Java 9 requires the variable to be effectively final, so reassigning it is a compile error.
  • Forgetting that JShell is only for small experiments — code with multiple classes and packages still needs normal files and javac.
  • Writing a private interface method that no default method calls — Java 9 private methods exist to be shared helpers, and an unused one is dead code.

Chapter 27 — Quick Questions

Q: What does var do in Java 10?

A: Lets Java infer the type of a local variable — var infers the type from the initialised value.

Q: Where can var be used?

A: Local variables only — var is restricted to local variables.

Q: Which of these is valid with var?

A: var s = "Hi"; — var must be initialized; null cannot be inferred.

Q: After `var a = 100;`, a is of type ___?

A: int — The literal 100 is an int, so a is int.

Q: List.copyOf(list) creates ___?

A: An immutable copy — copyOf makes an unchangeable copy.

Q: What does Optional.orElseThrow() do when the Optional is empty?

A: Throws NoSuchElementException — It throws NoSuchElementException if no value is present.

Q: Before Java 10, how often were big Java versions released?

A: Every few years — Before 10, versions came years apart; from 10, every six months.

Q: Is var a keyword in Java?

A: No, it is a reserved type name — var is a reserved type name, not a keyword.

Chapter 27 — Common Mistakes

Common Mistakes Beginners Make:
  • Writing var x; without an initial value — Java must infer the type from the right-hand side, so an uninitialised var is a compile error.
  • Using var for a class field or a method parameter — var works only for local variables inside a method.
  • Writing var n = null; — Java cannot guess the type of null, so this line does not compile.
  • Thinking var makes Java dynamically typed — after var a = 100;, a is still an int, and a = "text" fails to compile.
  • Trying to modify a copy made by List.copyOf(...) — the copy is immutable, so add() throws UnsupportedOperationException.
  • Calling orElseThrow() on an empty Optional without handling the exception — the program crashes with NoSuchElementException.

Chapter 28 — Quick Questions

Q: Which version is an LTS (Long-Term Support) version?

A: Java 11 — Java 11 is one of the LTS versions (8, 11, 17, 21).

Q: What does " ".isBlank() return?

A: true — isBlank() is true when the string is empty or only spaces.

Q: "AB".repeat(3) returns ___?

A: ABABAB — repeat(3) prints the string three times: ABABAB.

Q: Which method removes spaces from both ends (modern)?

A: strip() — strip() is the modern Unicode-aware replacement for trim().

Q: Which command compiles and runs a single .java file directly?

A: java Hello.java — Java 11 added the single-file launch: java Hello.java.

Q: In Java 11, var is allowed in ___?

A: Lambda parameters — var can appear in lambda parameters in Java 11.

Q: Which class is the modern way to call web APIs in Java 11?

A: HttpClient — HttpClient (java.net.http) is the modern HTTP client.

Q: Which old modules were removed in Java 11?

A: Java EE modules like CORBA — Java EE modules (CORBA, JAXB, etc.) were removed to lighten the platform.

Chapter 28 — Common Mistakes

Common Mistakes Beginners Make:
  • Using trim() in new code instead of strip() — trim() misses Unicode spaces like tab and non-breaking space, while strip() removes all of them.
  • Trying to run java Hello.java on a program with several files or external libraries — the single-file launch works only for one source file with no dependencies.
  • Expecting " ".isBlank() to return false — a string made of only spaces is blank, so isBlank() correctly returns true.
  • Forgetting that lines() returns a Stream — you cannot print it directly; you must call .forEach(...) or collect it first.
  • Adding var to every lambda parameter without a reason — it is only needed when you want annotations like (@NotNull var s), otherwise plain s is shorter.
  • Calling repeat(n) with a negative count — "AB".repeat(-1) throws IllegalArgumentException.

Chapter 29 — Quick Questions

Q: In the new switch expression, which symbol is used?

A: -> — The arrow -> means 'if matched, produce this value'.

Q: In the new switch, you need ___ to stop fall-through?

A: Nothing (no break needed) — Arrow-style cases do not fall through, so break is not needed.

Q: case 1, 3, 5 -> 31; means ___?

A: Cases 1, 3 and 5 each give 31 — Comma-separated values share the same result.

Q: What does "Hi".indent(4) do?

A: Adds 4 spaces before every line — indent(4) adds four spaces to the start of each line.

Q: transform() is used to ___?

A: Chain operations on a String — transform() applies a function to the String and returns the result.

Q: Collectors.teeing() ___?

A: Runs two collectors at once and merges — teeing runs two collectors in parallel and combines the results.

Q: A preview feature means ___?

A: It is experimental and may change — Previews are for feedback; they may change before becoming final.

Q: CompactNumberFormat shows 3500000 as ___?

A: 3.5M — The short style shows millions as M.

Chapter 29 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting the semicolon ; after a switch expression — because it returns a value, the whole switch (...) { ... }; needs a ; just like any assignment.
  • Writing break inside arrow-style cases — arrow cases never fall through, so break is unnecessary and marks the older, bug-prone style.
  • Thinking indent(4) trims or changes the text — it only adds or removes leading spaces on every line; the characters themselves are untouched.
  • Expecting transform() to work on each character — it applies one function to the whole String and returns the result, like a final step in a chain.
  • Expecting Collectors.teeing() to sort or filter the stream — it runs exactly two collectors at once and needs a merge function to combine the two results.

Chapter 30 — Quick Questions

Q: Text blocks are written using ___?

A: Triple double quotes — A text block starts and ends with three double quotes.

Q: Text blocks are most useful for ___?

A: Multi-line text like SQL and HTML — They make long multi-line text clean.

Q: In a switch block style, which keyword returns a value?

A: yield — yield gives a value back from inside a switch block.

Q: yield is different from return because ___?

A: yield only leaves the switch block, not the method — yield leaves the switch expression; return would exit the whole method.

Q: formatted() works like ___?

A: String.format() — formatted() is String.format() attached to the string.

Q: Text blocks became FINAL in which version?

A: Java 15 — Text blocks were finalized in Java 15.

Q: Switch expressions became FINAL in which version?

A: Java 14 — Switch expressions were finalized in Java 14.

Q: A text block's common leading spaces are ___?

A: Removed automatically — Java strips the shared indentation automatically.

Chapter 30 — Common Mistakes

Common Mistakes Beginners Make:
  • Forgetting the closing triple quotes """ of a text block — where you place the closing delimiter decides the final newline and the indentation of the last line, so a stray space changes the output.
  • Using return inside a block-style switch case instead of yield — return exits the whole method, while yield just hands a value back to the switch expression.
  • Thinking a text block keeps every space you typed — Java removes the indentation common to all lines, so code indentation does not leak into the output.
  • Trying to use text blocks in Java 12 or earlier — text blocks were first previewed in Java 13 and need --enable-preview until they became final in Java 15.
  • Expecting formatted() to change the original text block — like String.format(), it returns a new String with the placeholders filled in, and the text block itself stays unchanged.

Chapter 31 — Quick Questions

Q: Switch expressions became a permanent feature in ___?

A: Java 14 — Java 14 finalized switch expressions.

Q: A record automatically provides ___?

A: Constructor, accessors, toString, equals, hashCode — Records give all the boilerplate automatically.

Q: Which feature combines instanceof check and cast?

A: Pattern matching for instanceof — Pattern matching creates the typed variable in one step.

Q: In Java 14+, a NullPointerException message now shows ___?

A: Exactly where the null was and which call failed — Helpful NPE messages point to the exact null cause.

Q: How do you access a record's field?

A: rollNo() — Records use accessor methods named like the field: rollNo().

Q: Which version made Records FINAL?

A: Java 16 — Records were finalized in Java 16.

Q: Text blocks became FINAL in ___?

A: Java 15 — Text blocks were finalized in Java 15.

Q: Which Java version introduced Virtual Threads (preview)?

A: Java 19 — Virtual threads were previewed in Java 19 and finalized in Java 21 (LTS).

Chapter 31 — Common Mistakes

Common Mistakes Beginners Make:
  • Writing getRollNo() for a record field — record accessors are named after the field itself (rollNo()), not with a get prefix.
  • Trying to use records without --enable-preview in Java 14 (or below Java 14) — records were a preview feature until they became final in Java 16.
  • Adding mutable fields to a record — record components are implicitly final, so records are meant for immutable data carriers, not for objects that change after creation.
  • Casting again after a pattern-matching instanceof — when obj instanceof String s succeeds, s is already a String inside the block and the extra cast is unnecessary.
  • Expecting the helpful NullPointerException message by default in Java 14 — you had to opt in with -XX:+ShowCodeDetailsInExceptionMessages; it became the default only in Java 15.
  • Forgetting that text blocks were still a preview in Java 14 — they needed --enable-preview until they became final in Java 15.

Chapter 32 — Quick Questions

Q: Which is the LATEST Long-Term Support (LTS) version?

A: Java 21 — Java 21 (Sep 2023) is the latest LTS; Java 17 and 11 are older LTS.

Q: Records became a FINAL feature in which version?

A: Java 16 — Records were finalized in Java 16.

Q: Sealed classes became FINAL in which version?

A: Java 17 — Sealed classes were finalized in Java 17 (LTS).

Q: Which feature lets servers handle millions of lightweight tasks?

A: Virtual threads — Virtual threads (Java 21) are extremely lightweight.

Q: Which method starts a virtual thread?

A: Thread.startVirtualThread(r) — Thread.startVirtualThread(Runnable) starts one.

Q: A sealed class ___?

A: Can be extended only by the listed classes — Sealed classes name their permitted subclasses.

Q: Which expression matches on TYPE in the new switch?

A: Pattern matching for switch — Pattern matching for switch matches types and values.

Q: Java 21's sequenced collections add methods ___?

A: getFirst() and getLast() — Sequenced collections give getFirst()/getLast().

Chapter 32 — Common Mistakes

Common Mistakes Beginners Make:
  • Trying to use records, sealed classes, or virtual threads on Java 8 or 11 — records need Java 16+, sealed classes need Java 17+, and virtual threads need Java 21+.
  • Extending a sealed class that is not listed in permits — the compiler rejects the subclass with a compile error, because the family of classes is deliberately closed.
  • Handling virtual threads like heavy platform threads — you still use the same synchronized and wait/notify ideas from Chapter 11; virtual threads just make creating many threads cheap.
  • Forgetting a default case in a pattern-matching switch — when a switch matches on types, you still need to say what happens for any value that matches nothing.
  • Using Stream.toList() and then trying to add or remove elements — toList() returns an unmodifiable list, unlike Collectors.toList().
  • Building production code on preview features like string templates — previews can change or even be removed before they become final.
📝 Key Takeaways
  • Each Q&A comes straight from the chapter material
  • Common mistakes are the exact errors beginners make
  • Practise the MCQs, then try the full quiz page