Java Core Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does the JVM do?
Correct answer: Runs compiled bytecode on a specific platform
javac compiles .java files into .class bytecode. The JVM loads and runs that bytecode, interpreting it and compiling hot parts with the JIT.
2. What's the difference between the JDK and the JRE?
Correct answer: The JDK adds development tools like javac to what is needed to run Java
The JRE was just what you needed to run programs. The JDK includes it plus the compiler, debugger and other tools. Modern Java ships the JDK only.
3. Which of these is a primitive type in Java?
Correct answer:
intJava has eight primitives: byte, short, int, long, float, double, char, boolean. Integer is a wrapper class, String is a class.
4. What is the default value of an
intfield in a class?Correct answer: 0
Fields get defaults: 0 for numbers, false for boolean, null for references. Local variables have no default and must be assigned before use.
5. What does this code print?
String a = new String("hi"); String b = new String("hi"); System.out.println(a == b); System.out.println(a.equals(b));Correct answer: false, then true
== compares references: two
newobjects are different. equals compares content. Always use equals for strings in tests and code.6. Why are Java strings called immutable?
Correct answer: A String object's content can't change after creation
Methods like toUpperCase return a new string. The variable can point to another string, but the object itself never changes.
7. Why use
StringBuilderwhen building a string in a loop?Correct answer: It changes one buffer instead of creating a new string each time
s += x in a loop creates many temporary strings. StringBuilder appends to one buffer and builds the result once.
8. What are the four main principles of OOP?
Correct answer: Encapsulation, inheritance, polymorphism and abstraction
Encapsulation hides state, inheritance reuses behavior, polymorphism lets one call work with many types, abstraction focuses on what, not how.
9. What is encapsulation?
Correct answer: Hiding fields and exposing behavior through methods
Private fields with getters and methods that keep the object valid. Callers can't put it into a broken state directly.
10. What does the
privatemodifier mean for a field?Correct answer: It is visible only inside its own class
private is class-only. No modifier means package-private, protected adds subclasses, public is everywhere.
11. What is a constructor?
Correct answer: A special method that initializes a new object
A constructor has the class name and no return type. If you write none, the compiler adds a default no-argument one.
12. What does
staticmean on a field?Correct answer: It belongs to the class and is shared by all instances
A static counter is the same for all objects. Constants are usually
static final.13. What does
finalmean on a variable?Correct answer: It can be assigned only once
A final reference can't point to another object, but the object itself may still change, e.g. a final List can get new elements.
14. What is method overloading?
Correct answer: Several methods with the same name but different parameters
The compiler picks the overload by argument types at compile time. Overriding is chosen at runtime by the object's class.
15. What is method overriding?
Correct answer: A subclass providing its own version of a parent's method
Mark it with @Override so the compiler checks that the method really exists in the parent.
16. What does the
@Overrideannotation give you?Correct answer: A compile error if nothing is actually overridden
A typo in the name or a wrong parameter type would otherwise create a new method silently.
17. Can a Java class extend two classes?
Correct answer: No: one class, but any number of interfaces
Single inheritance of classes avoids ambiguity. Interfaces give multiple types and, since Java 8, default methods.
18. What is an abstract class?
Correct answer: A class you can't instantiate, with abstract methods
Subclasses must implement the abstract methods. Unlike an interface, it can hold state and constructors.
19. What is an interface in Java?
Correct answer: A type that declares methods a class promises to implement
Classes implement interfaces. Code depends on the interface, so implementations can be swapped, e.g. List and ArrayList.
20. What is polymorphism in this code?
List<String> list = new ArrayList<>(); list.add("a");Correct answer: A List variable holds an ArrayList, and the ArrayList's add runs
The variable type is the interface; the actual method comes from the object's class at runtime. You can switch to LinkedList without changing callers.
21. What is the difference between
ArrayListandLinkedListforget(i)?Correct answer: ArrayList is O(1), LinkedList is O(n)
ArrayList is backed by an array with direct index access. LinkedList walks nodes. In practice ArrayList is almost always the better default.
22. Which collection keeps only unique elements?
Correct answer:
SetA Set rejects duplicates by equals/hashCode. HashSet has no order, LinkedHashSet keeps insertion order, TreeSet sorts.
23. What does a
Mapstore?Correct answer: Key-value pairs with unique keys
put with an existing key replaces the value. HashMap has no order, LinkedHashMap keeps insertion order, TreeMap sorts keys.
24. What happens here?
List<Integer> nums = List.of(1, 2, 3); nums.add(4);Correct answer: An UnsupportedOperationException is thrown
List.of returns an immutable list. Use new ArrayList<>(List.of(...)) when you need to change it.
25. What do generics like
List<String>give you?Correct answer: Type checks at compile time and no casts when reading
The compiler stops you from adding an Integer to List<String>. At runtime the type info is erased.
26. Why can't you write
List<int>?Correct answer: Generics take only reference types: use
List<Integer>Primitives aren't objects. Autoboxing converts int to Integer when you add it.
27. What is autoboxing?
Correct answer: Automatic conversion between primitives and wrappers
int to Integer and back happens implicitly. Unboxing a null Integer throws NullPointerException.
28. What does this Integer comparison print?
Integer a = 127, b = 127; Integer c = 128, d = 128; System.out.println(a == b); System.out.println(c == d);Correct answer: true, then false
Integer caches -128..127, so small values share objects. Larger ones are new objects, and == compares references. Use equals.
29. What is the difference between checked and unchecked exceptions?
Correct answer: Checked must be caught or declared; unchecked extend RuntimeException
IOException is checked: the compiler forces handling. NullPointerException and IllegalArgumentException are unchecked.
30. When does the
finallyblock run?Correct answer: After try or catch, whether an exception happened or not
It's for cleanup. It doesn't run only if the JVM stops, e.g. System.exit.
31. What does try-with-resources do?
try (var reader = Files.newBufferedReader(path)) { return reader.readLine(); }Correct answer: Closes the resource automatically, even if an exception is thrown
Any AutoCloseable declared in the header is closed at the end. It's safer than a manual finally with close().
32. What causes a
NullPointerException?Correct answer: Calling a method on a reference that is null
Division by zero gives ArithmeticException, a bad index gives ArrayIndexOutOfBoundsException. Modern JVMs say which variable was null.
33. What is
Optionalfor?Correct answer: To show that a method may return no value
Callers must handle the empty case explicitly, e.g. orElse or ifPresent. It's meant for return values, not fields.
34. What's the contract between
equalsandhashCode?Correct answer: Equal objects must have the same hash code
If you override equals, override hashCode too, or HashMap and HashSet won't find your objects.
35. What does
toString()return by default?Correct answer: The class name,
@and a hex hash codeOverride it to get readable logs and test failure messages. Records generate a useful one automatically.
36. What does a lambda expression replace?
list.forEach(s -> System.out.println(s));Correct answer: An anonymous class implementing a functional interface
Lambdas implement functional interfaces like Consumer or Function in a short form.
37. What is a functional interface?
Correct answer: An interface with exactly one abstract method
Runnable, Comparator and Function are examples. @FunctionalInterface makes the compiler check it.
38. What does this stream return?
List.of(1, 2, 3, 4).stream() .filter(n -> n % 2 == 0) .map(n -> n * 10) .toList();Correct answer: [20, 40]
filter keeps even numbers, map multiplies them. toList collects the result into an unmodifiable list.
39. When does a stream pipeline actually run?
Correct answer: Only when a terminal operation like
toListorcountis calledIntermediate operations are lazy. Without a terminal operation nothing happens, a common surprise in tests.
40. What does
vardo invar list = new ArrayList<String>();?Correct answer: The compiler infers the type, here
ArrayList<String>var is only for local variables, and the type is fixed at compile time.
41. What is a
recordin Java?record User(String name, int age) {}Correct answer: A compact class for immutable data with generated methods
Records cut boilerplate for data carriers. Fields are final, and accessors are name() and age().
42. What is the difference between
==andequalsfor objects?Correct answer: == compares references; equals compares content
Object's default equals is ==. Classes like String, Integer and records override it to compare values.
43. What does
thisrefer to inside an instance method?Correct answer: The current object
It is used to tell fields from parameters with the same name, e.g. this.name = name.
44. What does
superlet you do?Correct answer: Call the parent's constructor or methods
super() must be the first line of a constructor. super.method() calls the parent's version of an overridden method.
45. What is the
mainmethod signature that starts a classic Java program?Correct answer:
public static void main(String[] args)The JVM looks for this method in the class you run. Newer Java versions allow simpler launch forms, but this one always works.
46. What is a package in Java?
Correct answer: A namespace that groups related classes
Packages avoid name clashes and control access: package-private members are visible only inside their package.
47. What does
importdo?Correct answer: Lets you use a class by its short name in the file
It's a compile-time shortcut. Dependencies themselves come from the classpath, usually via Maven or Gradle.
48. What are Maven and Gradle used for?
Correct answer: Building, managing dependencies and running tests
They download libraries, compile, run tests (
mvn test,gradle test) and package the app.49. What does
mvn testdo?Correct answer: Runs the build lifecycle up to the test phase
Maven phases run in order: validate, compile, test, package and so on. Each phase includes all the earlier ones.
50. Which annotation marks a test method in JUnit 5?
Correct answer:
@TestJUnit 5 uses org.junit.jupiter.api.Test. Lifecycle hooks are @BeforeEach, @AfterEach, @BeforeAll and @AfterAll.
51. What does
@BeforeEachin JUnit 5 do?Correct answer: Runs before every test method in the class
Use it to create fresh test data so tests don't depend on each other. @BeforeAll runs once and must be static by default.
52. What does
assertEquals(expected, actual)check?Correct answer: That the two values are equal using equals
Put the expected value first: failure messages show 'expected X but was Y'. assertSame checks references.
53. Why do many QA teams use AssertJ assertions?
assertThat(user.getName()).isEqualTo("Ann");Correct answer: They read like sentences and fail with clear messages
Fluent assertions chain checks on strings, lists and objects. They work with JUnit and TestNG.
54. What is TestNG?
Correct answer: A Java test framework with groups and data providers
TestNG is common in Selenium projects: testng.xml defines suites, groups and parallel runs.
55. What does
@DataProviderin TestNG give you?Correct answer: One test method runs with several sets of data
Data-driven tests avoid copying the same method. JUnit 5 has @ParameterizedTest for the same goal.
56. What is a mock object, e.g. from Mockito?
Correct answer: A fake dependency that records how it was called
Mocks isolate the class under test: you stub returns with when(...).thenReturn(...) and check calls with verify.
57. What does this loop print?
for (int i = 0; i < 3; i++) { System.out.print(i); }Correct answer: 012
i starts at 0 and the loop stops when i < 3 is false, so 0, 1 and 2 are printed.
58. What does integer division
7 / 2give in Java?Correct answer: 3
Dividing two ints drops the fraction. Use 7 / 2.0 or cast to double for 3.5.
59. What happens when an
intoverflows?int x = Integer.MAX_VALUE; x = x + 1;Correct answer: It wraps around to a large negative number
int arithmetic wraps silently. Math.addExact throws on overflow. Boundary tests should include MAX_VALUE.
60. What is the index of the first element of an array?
Correct answer: 0
Arrays are zero-based; the last index is length - 1. arr[arr.length] throws ArrayIndexOutOfBoundsException.
61. What is the difference between
length,length()andsize()?Correct answer: Array field, String method, Collection method
arr.length, str.length(), list.size(). A frequent compile error for people coming from other languages.
62. What does the garbage collector do?
Correct answer: Frees memory of objects that are no longer reachable
You don't free memory by hand. Resources like files still need closing, ideally with try-with-resources.
63. Can there be a memory leak in Java despite garbage collection?
Correct answer: Yes, if objects stay referenced, e.g. in a static map
The GC frees only unreachable objects. A cache that only grows keeps everything alive.
64. What does
switchwith arrows do here?String size = switch (n) { case 1, 2 -> "small"; default -> "big"; };Correct answer: Returns a value, with no fall-through
Switch expressions return values and don't fall through, so no break is needed.
65. What are text blocks (
""") used for?Correct answer: Multi-line string literals, handy for JSON or SQL in tests
Text blocks keep line breaks and remove common indentation. Great for request bodies in API tests.
66. What is an enum?
Correct answer: A type with a fixed set of named constants
enum Status { NEW, PAID, SHIPPED }. Enums can have fields and methods and work well in switch.
67. What is a thread?
Correct answer: An independent path of execution in a program
Threads share the process's memory, which is why shared data needs care.
68. What problem can two threads incrementing the same counter cause?
Correct answer: Lost updates, because ++ is not atomic
count++ reads, adds and writes. Use AtomicInteger, synchronized or a lock.
69. What does
synchronizedon a method do?Correct answer: Lets only one thread run it on the same object at a time
It takes the object's lock. It also makes changes visible to the next thread that takes the lock.
70. How do you compare two strings ignoring case?
Correct answer:
a.equalsIgnoreCase(b)== compares references. compareTo returns an order, not 1 for equal. equalsIgnoreCase compares content without case.
71. What does
Comparabledefine?Correct answer: The natural order of a class through
compareToCollections.sort and TreeSet use it. A Comparator defines another order without changing the class.
72. What does this code print after calling concat?
String s = "QA"; s.concat("!"); System.out.println(s);Correct answer: QA
concat returns a new string; the result is thrown away. Assign it: s = s.concat("!").
73. What is the classpath?
Correct answer: Where the JVM looks for classes and jar files
Missing jars on the classpath cause ClassNotFoundException or NoClassDefFoundError at runtime.
74. What is JIT compilation?
Correct answer: Compiling frequently used bytecode to native code at runtime
Hot methods get optimized while the program runs. That's why Java code is often slower in the first seconds.
75. What does
Arrays.asList(...)return when you calladdon it?List<String> list = Arrays.asList("a", "b"); list.add("c");Correct answer: UnsupportedOperationException: the list has a fixed size
Arrays.asList wraps the array: you can set elements but not add or remove. Copy it into a new ArrayList to change its size.