Java Notes
40+ Core Java interview questions with detailed answers covering JVM, data types, strings, wrapper classes, memory management, and Java fundamentals.
1. What is Java and why is it platform independent?
Answer: Java is a high-level, object-oriented programming language. It achieves platform independence through the JVM (Java Virtual Machine). Java source code is compiled into bytecode (.class file), which runs on any platform that has a JVM installed.
Source.java → javac → Source.class (bytecode) → JVM → Machine CodeThe JVM acts as an abstraction layer between Java bytecode and the underlying operating system.
3. Explain JVM memory areas.
| Heap | Objects, arrays (GC here) |
|---|---|
| Stack | Method frames, locals |
| Method Area | Class metadata, static |
| PC Register | Current instruction |
| Native Stack | Native method calls |
- Heap: Shared among all threads; stores all objects
- Stack: Per-thread; stores method frames, local variables, references
- Method Area: Class-level data, static variables, constant pool
4. What are the differences between == and .equals()?
| Feature | == | .equals() |
|---|---|---|
| Compares | Reference (memory address) | Content/Value |
| For primitives | Compares values | Cannot be used |
| For objects | Checks same object | Checks logical equality |
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
String s3 = "hello";
String s4 = "hello";
System.out.println(s3 == s4); // true (String pool)false (different objects) true (same content) true (String pool)
5. What is the String Pool?
The String Pool (String Intern Pool) is a special memory area in the heap where Java stores string literals. When you create a string literal, Java checks the pool first:
String a = "Java"; // Goes to pool
String b = "Java"; // Reuses from pool
String c = new String("Java"); // Creates new object in heap
System.out.println(a == b); // true (same pool reference)
System.out.println(a == c); // false (pool vs heap)
System.out.println(a == c.intern()); // true (intern returns pool ref)true (same pool reference) false (pool vs heap) true (intern returns pool ref)
6. Why is String immutable in Java?
- Security: Strings used in network connections, class loading, etc.
- String Pool: Immutability enables safe sharing in pool
- Thread Safety: Immutable objects are inherently thread-safe
- Hashcode Caching: Hash can be cached since string won't change
- Class Loading: Class names are strings; mutation would be a security risk
7. Difference between String, StringBuilder, and StringBuffer?
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes (immutable) | No | Yes (synchronized) |
| Performance | Slow for concatenation | Fastest | Slower than StringBuilder |
| Use when | Value won't change | Single-threaded modification | Multi-threaded modification |
// String — creates new object each time
String s = "Hello";
s = s + " World"; // Original "Hello" is now garbage
// StringBuilder — modifies same object
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Same object modified8. What is autoboxing and unboxing?
Autoboxing: Automatic conversion from primitive to wrapper class. Unboxing: Automatic conversion from wrapper to primitive.
// Autoboxing
int num = 10;
Integer obj = num; // int → Integer (autoboxing)
// Unboxing
Integer obj2 = Integer.valueOf(20);
int num2 = obj2; // Integer → int (unboxing)
// Trap!
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true (cached range: -128 to 127)
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false (beyond cache range)true (cached range: -128 to 127) false (beyond cache range)
9. What is the difference between final, finally, and finalize?
| Keyword | Type | Purpose |
|---|---|---|
final | Modifier | Variable (constant), method (no override), class (no inherit) |
finally | Block | Always executes after try-catch (cleanup) |
finalize | Method | Called by GC before object destruction (deprecated) |
final int MAX = 100; // Cannot reassign
final class Utility {} // Cannot extend
final void display() {} // Cannot override
try { ... }
catch (Exception e) { ... }
finally { connection.close(); } // Always runs10. What is the difference between throw and throws?
| Feature | throw | throws |
|---|---|---|
| Purpose | Actually throws exception | Declares possible exception |
| Location | Inside method body | In method signature |
| Count | One exception at a time | Multiple comma-separated |
// throw — creates and throws exception
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
// throws — declares that method might throw
public void readFile(String path) throws IOException, FileNotFoundException {
// code that may throw these exceptions
}11. Explain checked vs unchecked exceptions.
| Feature | Checked | Unchecked |
|---|---|---|
| Checked at | Compile time | Runtime |
| Must handle | Yes (try-catch or throws) | No |
| Extends | Exception | RuntimeException |
| Examples | IOException, SQLException | NullPointerException, ArrayIndexOutOfBounds |
12. What is the difference between abstract class and interface?
| Feature | Abstract Class | Interface (Java 8+) |
|---|---|---|
| Methods | Abstract + concrete | Abstract + default + static |
| Variables | Any type | Only public static final |
| Constructor | Yes | No |
| Inheritance | Single | Multiple |
| Access modifiers | All | Public only (methods) |
| Use when | IS-A relationship | CAN-DO capability |
13. What is method overloading vs overriding?
| Feature | Overloading | Overriding |
|---|---|---|
| Class | Same class | Parent-child classes |
| Method name | Same | Same |
| Parameters | Different | Same |
| Return type | Can differ | Same or covariant |
| Access modifier | Can differ | Same or wider |
| Static methods | Can be overloaded | Cannot be overridden |
| Binding | Compile-time (static) | Runtime (dynamic) |
14. What is the static keyword?
Class loaded
Static members belong to the class, not to any instance.
15. Explain pass-by-value in Java.
Java is always pass-by-value. However:
- For primitives: the value is copied
- For objects: the reference (memory address) is copied (not the object)
void modify(int x, StringBuilder sb) {
x = 100; // Changes local copy only
sb.append(" World"); // Modifies original object (same reference)
sb = new StringBuilder("New"); // Changes local reference only
}
int num = 5;
StringBuilder text = new StringBuilder("Hello");
modify(num, text);
System.out.println(num); // 5 (unchanged)
System.out.println(text); // "Hello World" (modified via reference)5 (unchanged) "Hello World" (modified via reference)
16. What is garbage collection?
GC automatically reclaims memory from unreachable objects. You cannot force GC, only request it:
System.gc(); // Request (not guaranteed)
Runtime.getRuntime().gc(); // Same thingGC Algorithms: Serial GC, Parallel GC, G1 GC, ZGC
An object becomes eligible for GC when no live reference points to it.
17. What are access modifiers?
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
18. What is a ClassLoader?
ClassLoader loads classes into JVM memory. Three built-in class loaders:
- Bootstrap ClassLoader — Loads core Java classes (java.lang.*)
- Extension ClassLoader — Loads extension classes (javax.*)
- Application ClassLoader — Loads your application classes
They follow delegation hierarchy — child delegates to parent first.
19. What is a marker interface?
A marker interface has NO methods. It "marks" a class for special treatment:
public interface Serializable {} // Marks class as serializable
public interface Cloneable {} // Marks class as cloneableThe JVM/framework checks instanceof to determine behavior.
20. What is the difference between Array and ArrayList?
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type | Primitives + Objects | Objects only |
| Generics | No | Yes |
| Performance | Faster (no overhead) | Slightly slower |
| Methods | .length | .size(), add(), remove() |
| Multi-dimensional | Yes | Not directly |
21. What is type casting in Java?
// Widening (implicit) — smaller to larger
int i = 100;
long l = i; // int → long (automatic)
double d = l; // long → double (automatic)
// Narrowing (explicit) — larger to smaller
double x = 9.78;
int y = (int) x; // double → int (manual cast, loses .78)
// Object casting
Animal animal = new Dog(); // Upcasting (automatic)
Dog dog = (Dog) animal; // Downcasting (explicit, needs instanceof check)22. Explain the this keyword.
public class Student {
private String name;
public Student(String name) {
this.name = name; // Distinguish field from parameter
}
public Student() {
this("Unknown"); // Call another constructor
}
public Student getThis() {
return this; // Return current object
}
}23. What is the super keyword?
class Parent {
int x = 10;
Parent(int x) { this.x = x; }
void display() { System.out.println("Parent"); }
}
class Child extends Parent {
int x = 20;
Child() {
super(100); // Call parent constructor (must be first line)
}
void display() {
super.display(); // Call parent method
System.out.println("Child x=" + this.x + ", Parent x=" + super.x);
}
}24. What happens if main() method is missing?
Since Java 7+, the program won't run and throws: Error: Main method not found in class.
Before Java 7, you could use a static block to execute code without main(), but the JVM would still throw an error after the static block ran.
25. Can we override static methods?
No. Static methods belong to the class, not the instance. You can hide a static method in a subclass, but it's not true overriding:
class Parent {
static void greet() { System.out.println("Parent"); }
}
class Child extends Parent {
static void greet() { System.out.println("Child"); } // Method hiding
}
Parent p = new Child();
p.greet(); // "Parent" — resolved at compile time, not runtime26. What is a singleton class?
A class that allows only ONE instance to be created:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {} // Private constructor
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}27. What is the difference between Comparable and Comparator?
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T o1, T o2) |
| Modifies class | Yes (implements) | No (separate class) |
| Sorting | Natural order (one way) | Custom order (multiple ways) |
28. What is an enum in Java?
public enum Day {
MONDAY("Start of work week"),
TUESDAY("Second day"),
WEDNESDAY("Mid week"),
THURSDAY("Almost Friday"),
FRIDAY("TGIF"),
SATURDAY("Weekend!"),
SUNDAY("Rest day");
private final String description;
Day(String description) {
this.description = description;
}
public String getDescription() { return description; }
}Enums are type-safe constants with methods and fields.
29. What is a transient variable?
transient prevents a field from being serialized:
public class User implements Serializable {
private String username;
private transient String password; // NOT saved during serialization
}30. What is the volatile keyword?
volatile ensures a variable is always read from main memory, not from CPU cache:
private volatile boolean running = true; // Visible to all threads immediatelyIt provides visibility but NOT atomicity. For atomic operations, use AtomicInteger, etc.
31. What is the difference between Iterator and ListIterator?
| Feature | Iterator | ListIterator |
|---|---|---|
| Direction | Forward only | Forward + Backward |
| Collections | Any Collection | Only List |
| Methods | hasNext(), next(), remove() | + hasPrevious(), previous(), add(), set() |
| Index | No | nextIndex(), previousIndex() |
32. Can a constructor be private?
Yes. Used in:
- Singleton pattern
- Utility classes (all static methods)
- Factory method pattern
- Builder pattern
33. What is covariant return type?
A subclass can override a method and return a subtype of the parent's return type:
class Animal { Animal create() { return new Animal(); } }
class Dog extends Animal { Dog create() { return new Dog(); } } // Covariant34. What is the difference between Error and Exception?
| Feature | Error | Exception |
|---|---|---|
| Recovery | Usually not recoverable | Can be handled |
| Cause | JVM/System issues | Application logic issues |
| Examples | OutOfMemoryError, StackOverflowError | IOException, NullPointerException |
| Handling | Should NOT catch | Should catch and handle |
35. What are varargs?
public int sum(int... numbers) { // Variable number of arguments
int total = 0;
for (int n : numbers) total += n;
return total;
}
sum(1, 2); // Works
sum(1, 2, 3, 4); // Works
sum(); // Works (empty array)Rules: Only one vararg per method, must be the last parameter.
36-40. Quick Fire Questions
36. Can we have multiple public classes in one file? No. Only one public class per file, and its name must match the filename.
37. What is the default value of local variables? Local variables have NO default value — must be initialized before use.
38. Can abstract class have constructor? Yes. Called when subclass is instantiated.
39. What is the Object class? Root of all Java classes. Every class implicitly extends java.lang.Object. Methods: toString(), equals(), hashCode(), clone(), getClass(), finalize(), wait(), notify().
40. What is diamond problem? How does Java solve it? When a class inherits from two classes with same method. Java doesn't allow multiple class inheritance. With interfaces (Java 8+ default methods), the class must explicitly override the conflicting method.
Summary
In this chapter, we learned about Core Java Interview Questions in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Core Java Interview Questions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, interview, questions, core
Related Java Master Course Topics