Java Interview Questions
1. Difference between JDK, JRE, JVM
JDK (Java Development Kit): Complete environment for Java development, including:
- Development tools (compiler, debugger, documentation tools)
- JRE
- Core classes and APIs
JRE (Java Runtime Environment): Minimum environment needed to execute Java
applications:
- JVM
- Core classes and supporting files
JVM (Java Virtual Machine): Abstract computing machine providing runtime environment:
- Executes Java bytecode
- Handles memory management
- Provides platform independence
Real-life analogy: JDK is like a complete restaurant setup, JRE is like the dining area, JVM is
like the kitchen.
2. Explain public static void main ()
public: Accessible from anywhere
static: Can be called without creating class instance
void: Returns nothing
main: Entry point method name
(String[] args): Command line arguments
Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println('Hello World!');
}
}
3. Why Java is Platform Independent?
Java code is compiled to bytecode (.class files)
Bytecode runs on JVM, not directly on hardware
JVM is available for different platforms
"Write Once, Run Anywhere" (WORA)
4. Is Java Pure Object-Oriented?
No, Java is not purely object-oriented because:
- Has primitive data types (int, float, etc.)
- Allows static methods and variables
- Doesn't support multiple inheritance (through classes)
5. Difference between heap memory and stack memory.
Stack:
- Stores method calls and local variables
- Memory allocated/deallocated automatically
- LIFO (Last In First Out)
- Faster access
- Thread-safe
Heap:
- Stores objects and JRE classes
- Memory managed by garbage collector
- Slower access
- Shared across threads
Example:
public void example() {
int age = 25; // Stack
Person person = new Person(); // Reference in stack, object in heap
}
6. Difference between equals method and==
== compares reference/memory address
equals() compares content
Example:
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)
7. Why No Pointers in Java
- Security: Prevents memory access errors
- Simplicity: Reduces complexity
- JVM handles memory management
- Garbage collection automated
8. JIT (Just-In-Time) Compiler
- Part of JRE
- Compiles bytecode to native machine code at runtime
- Improves performance
- Only compiles frequently used code
- Adaptive optimization
9. Local vs Instance Variables
Instance Variables:
- Declared inside class but outside methods
- Created when object is instantiated
- Have default values if not initialized
- Can use access modifiers
- Exist throughout object lifecycle
Local Variables:
- Declared inside methods
- Must be initialized before use
- No default values
- Cannot use access modifiers
- Exist only within method scope
Example:
public class Student {
int rollNo; // Instance variable
public void study() {
int studyHours = 5; // Local variable
System.out.println('Studying for ' + studyHours + ' hours');
}
}
10. Constants in Java
Constants are unchangeable values declared using 'final' keyword
Types:
1. Static constants (class level)
2. Instance constants (object level)
3. Local constants (method level)
4. Interface constants (public, static, final)
Example:
public class Constants {
// Static constant
public static final double PI = 3.14159;
// Instance constant
final String STUDENT_ID;
public void method() {
// Local constant
final int MAX_ATTEMPTS = 3;
}
}
11. Can we declare class, methods, and variables as constants?
- Class: Yes, using 'final'
- Methods: Yes, using 'final'
- Variables: Yes, using 'final'
Example:
final class FinalClass {
final int NUMBER = 100;
final void display() {
System.out.println(NUMBER);
}
}
12. Difference between break and continue
Break:
- Terminates entire loop
Continue:
- Skips current iteration
Example:
// Break
for(int i = 1; i <= 10; i++) {
if(i % 2 == 0) {
break;
}
}
// Continue
for(int i = 1; i <= 10; i++) {
if(i % 2 == 0) {
continue;
}
}
13. Define a Class Loader System.
- Part of JRE that loads class files
Types:
1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader
14. Method Overloading and Method Overriding
Method Overloading (Compile-time Polymorphism):
Same method name, different parameters
Can occur in same class
Based on parameter number, type, or order
Return type can be different
Access modifier can be different
Method Overriding (Runtime Polymorphism):
Same method name, same parameters
Occurs in inherited classes
Based on inheritance relationship
Return type must be same or covariant
Access modifier cannot be more restrictive
Example:
class Animal {
// Overloaded methods
void makeSound() {
System.out.println("Some sound");
}
void makeSound(String sound) {
System.out.println(sound);
}
}
class Dog extends Animal {
// Overridden method
@Override
void makeSound() {
System.out.println("Woof");
}
}
15. Difference between c++ and java.
Key Differences:
Memory Management:
Java: Automatic (Garbage Collection)
C++: Manual (delete/free)
Multiple Inheritance:
Java: Only through interfaces
C++: Supports multiple class inheritance
Platform Independence:
Java: Write Once Run Anywhere (WORA)
C++: Code needs recompilation for different platforms
Pointers:
Java: No direct pointer support
C++: Full pointer support
Operator Overloading:
Java: Not supported
C++: Supported
16. Difference between final, finally and finalize.
final:
Keyword to create constants
Can be applied to classes, methods, variables
Prevents inheritance, overriding, modification
finally:
Block used with try-catch
Always executes (except System.exit())
Used for cleanup operations
finalize():
Method called by garbage collector
Before object destruction
Not guaranteed to be called
public class FinalExample {
final int value = 10; // constant
public void example() {
try {
// some code
} catch(Exception e) {
// handle exception
} finally {
// cleanup code
}
}
@Override
protected void finalize() {
// cleanup before garbage collection
}
}
17. Explain type casting in java.
Two Types:
Implicit (Widening):
Automatic conversion
Smaller to larger data type
No data loss
Example: byte → short → int → long
Explicit (Narrowing):
Manual conversion
Larger to smaller data type
Possible data loss
Requires cast operator
// Implicit casting
int num = 10;
long bigNum = num; // automatic
// Explicit casting
double pi = 3.14;
int iPi = (int)pi; // manual casting
18. Default value of local variable and static variable.
Static Variables:
int: 0
byte: 0
short: 0
long: 0L
float: 0.0f
double: 0.0d
boolean: false
char: '\u0000'
Object: null
Local Variables:
No default values
Must be initialized before use
public class DefaultValues {
static int staticNum; // 0
static boolean staticBool; // false
void method() {
int localNum; // Error if used without initialization
localNum = 10; // Must initialize
}
}
19. Define data types.
Two Categories:
Primitive Data Types:
1. byte (8 bits)
2. short (16 bits)
3. int (32 bits)
4. long (64 bits)
5. float (32 bits)
6. double (64 bits)
7. char (16 bits)
8. boolean (1 bit)
Reference Data Types:
1. Classes
2. Interfaces
3. Arrays
4. Enums
20. Define Exception handling in java.
Mechanism to handle runtime errors
Hierarchy: Throwable → Error/Exception
Types:
1. Checked Exceptions (Compile-time)
2. Unchecked Exceptions (Runtime)
3. Errors
Components:
try: Contains code that might throw exception
catch: Handles exceptions
finally: Cleanup code
throw: Throws explicit exception
throws: Declares exceptions
Example:
public class ExceptionExample {
public void divide(int a, int b) {
try {
int result = a / b;
System.out.println(result);
} catch(ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Operation complete");
}
}
}
21. What are the default data types in java?
Primary default data types:
Numeric:
Integer types: byte, short, int (default for whole numbers), long
Floating types: float, double (default for decimal numbers)
Character: char
Boolean: boolean
Reference type: null
public class DefaultTypes {
void example() {
int number = 10; // Default integer literal
double decimal = 10.5; // Default decimal literal
char character = 'A'; // Character literal
boolean flag = true; // Boolean literal
String text = null; // Default object reference
}
}
22. In char data type it takes two bites but c++ it takes one byte. Why?
Java uses Unicode (16 bits) for characters
Supports international characters
Can represent 65,536 different characters
Platform independent
C++ uses ASCII (8 bits) by default
Limited to 256 characters
Mainly English characters
Platform dependent
char englishChar = 'A'; // Works in both Java and C++
char chineseChar = '中'; // Works in Java, might not work in C++
23. Can we overload the main method in Java?
Yes, the main method can be overloaded, but:
JVM only recognizes public static void main(String[] args)
Other overloaded versions won't serve as entry points
Can be called from the main entry point
public class MainOverload {
// Entry point
public static void main(String[] args) {
main("Hello");
main("Hello", "World");
}
// Overloaded main methods
public static void main(String arg1) {
System.out.println(arg1);
}
public static void main(String arg1, String arg2) {
System.out.println(arg1 + " " + arg2);
}
}
24. Can we overwrite?
Yes, main method can be overridden, but:
It doesn't affect program execution
JVM always calls the main method of the class specified to run
Not practically useful
class Parent {
public static void main(String[] args) {
System.out.println("Parent's main");
}
}
class Child extends Parent {
public static void main(String[] args) {
System.out.println("Child's main");
}
}
25. Can we type cast.
Yes, Java supports two types of type casting:
Primitive Type Casting:
o Widening (Implicit)
o Narrowing (Explicit)
Reference Type Casting:
o Upcasting (Child to Parent)
o Downcasting (Parent to Child)
Example:
// Primitive casting
int x = 10;
long y = x; // Widening
int z = (int)y; // Narrowing
// Reference casting
class Animal {}
class Dog extends Animal {}
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog)animal; // Downcasting
26. Difference between assignment and initialization.
Initialization:
Providing first value when declaring variable
Happens at creation time
Can only happen once
Can use initialization blocks
Assignment:
Giving new value to existing variable
Can happen multiple times
Happens after declaration
Uses assignment operator (=)
public class InitVsAssign {
int initialized = 10; // Initialization
int assigned;
void method() {
assigned = 20; // Assignment
assigned = 30; // Another assignment
}
}
27. What is the Unicode system?
International encoding standard
Represents characters from all languages
Uses 16 bits in Java
Supports:
o Multiple languages
o Special characters
o Symbols and emojis
Example:
public class UnicodeExample {
char english = 'A'; // \u0041
char chinese = '中'; // \u4E2D
char copyright = '©'; // \u00A9
String emoji = "\uD83D\uDE00"; //
}
28. Use of the main method?
Entry point of Java program
Called by JVM to start execution
Must have specific signature
Can accept command-line arguments
Static to avoid object creation
Required signature:
public static void main(String[] args)
29. Can we execute a java program without the main method?
29. No, but with exceptions:
Static blocks execute during class loading
Can use static initialization
Not considered proper program execution
JVM requires main method as entry point
public class NoMain {
static {
System.out.println("Static block executes");
System.exit(0); // Terminates JVM
}
}
30. What is byte code?
Intermediate code (.class files)
Generated by Java compiler
Platform independent
Executed by JVM
Contains instructions for JVM
Stored in .class files
Verified by JVM before execution
Java Source (.java) → Compiler → Bytecode (.class) → JVM → Machine Code
31. How many types of loops in java?
Java supports 4 types of loops:
for loop:
Used when number of iterations known
Has initialization, condition, increment/decrement
while loop:
Used when iterations depend on condition
Condition checked before execution
do-while loop:
Similar to while but executes at least once
Condition checked after execution
Enhanced for loop (for-each):
Used for collections and arrays
Simpler syntax for iteration
Example:
public class LoopTypes {
void examples() {
// for loop
for(int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop
int j = 0;
while(j < 5) {
System.out.println(j++);
}
// do-while loop
int k = 0;
do {
System.out.println(k++);
} while(k < 5);
// for-each loop
int[] numbers = {1, 2, 3, 4, 5};
for(int num : numbers) {
System.out.println(num);
}
}
}
32. How many access modifiers in java?
Java has 4 access modifiers:
1. public:
Accessible everywhere
Least restrictive
2. protected:
Accessible in:
Same package
Subclasses (even in different packages)
3. default (no modifier):
Accessible only in same package
Package-private
4. private:
Accessible only within same class
Most restrictive
Example:
public class AccessModifiers {
public int publicVar; // Accessible everywhere
protected int protectedVar;// Accessible in package and subclasses
int defaultVar; // Accessible in package
private int privateVar; // Accessible only in this class
public void publicMethod() {}
protected void protectedMethod() {}
void defaultMethod() {}
private void privateMethod() {}
33. Is it possible to declare an array as a final?
Yes, but with important considerations:
Final array means reference can't change
Array elements can still be modified
Size remains constant
New array can't be assigned to reference
Example:
public class FinalArray {
void example() {
// Final array declaration
final int[] numbers = {1, 2, 3};
// Valid: Modifying elements
numbers[0] = 10;
// Invalid: Can't assign new array
// numbers = new int[]{4, 5, 6}; // Compilation error
// To make elements immutable, need to:
// 1. Use Collections.unmodifiableList for List
// 2. Create defensive copies
// 3. Use deep cloning for complex objects
}
}
34. What is a jagged array?
Array of arrays with different lengths
Each sub-array can have different size
Common in:
o Matrix operations
o Dynamic data structures
o Memory optimization
Also called ragged array
Example:
public class JaggedArrayExample {
void createJaggedArray() {
// Declaration
int[][] jaggedArray = new int[3][];
// Initialize sub-arrays with different lengths
jaggedArray[0] = new int[3]; // First row has 3 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[2]; // Third row has 2 columns
// Another way to initialize
int[][] jagged = {
{1, 2, 3},
{4, 5, 6, 7, 8},
{9, 10}
};
// Accessing elements
System.out.println(jagged[0][1]); // Prints 2
// Printing jagged array
for(int i = 0; i < jagged.length; i++) {
for(int j = 0; j < jagged[i].length; j++) {
System.out.print(jagged[i][j] + " ");
}
System.out.println();
}
}
}
Java Interview Questions with Detailed
Answers
1. Why Java is not 100% Object Oriented?
Java is not 100% object-oriented because:
1. Primitive data types (int, byte, short, long, etc.)
- Not objects
- Don't inherit from Object class
- Have wrapper classes (Integer, Byte, etc.)
2. Static members
- Can be accessed without object creation
- Violates object-oriented principle
3. No multiple inheritance through classes
- Only supports through interfaces
- True OOP should support full inheritance
4. Methods and variables can exist outside classes (in default package)
Example:
public class NonOOP {
int primitive = 10; // Primitive, not object
static int staticMember = 20; // Can use without object
// Wrapper class (object-oriented alternative)
Integer wrapper = Integer.valueOf(10);
}
2. Why Pointers are not used in Java?
Pointers are not used in Java for:
1. Security:
- Prevents direct memory access
- Eliminates memory corruption
- Prevents buffer overflows
2. Simplicity:
- Reduces complexity
- Fewer bugs
- Easier to learn
3. Platform Independence:
- Memory handling varies across platforms
- JVM manages memory internally
- References used instead of pointers
4. Garbage Collection:
- Automatic memory management
- No manual deallocation needed
- Prevents memory leaks
3. JIT (Just-In-Time) Compiler in Java
JIT Compiler:
- Part of JVM
- Converts bytecode to native machine code at runtime
- Improves performance
Process:
1. Java code → Bytecode (by javac)
2. Bytecode → Native code (by JIT)
3. Native code executed directly by CPU
Benefits:
- Faster execution
- Optimizes frequently used code
- Platform-specific optimization
- Adaptive optimization
4. Why String is Immutable in Java
Strings are immutable for:
1. Security:
- String pool safety
- Network security
2. Performance:
- String pool caching
- Hash code caching
- Better memory utilization
3. Synchronization:
- Thread safe
- No synchronization needed
Example:
String s1 = "Hello";
String s2 = "Hello"; // Uses same object from string pool
s1 = s1 + " World"; // Creates new string, original unchanged
5. Marker Interface?
- Interface with no methods
- Used to signal something to JVM
- Provides runtime type information
Examples:
1. Serializable
2. Cloneable
3. Remote
// Example of marker interface
public interface MyMarker {}
public class MyClass implements MyMarker {
// Class is now "marked"
}
6. Can you Override Private or Static Methods?
Private Methods:
- Cannot be overridden
- Not visible in child class
- Can have method with same name (hiding)
Static Methods:
- Cannot be overridden
- Can be hidden by child class
- Bound to class, not instance
Example:
class Parent {
private void privateMethod() {}
static void staticMethod() {}
}
class Child extends Parent {
// Not override, just new method
private void privateMethod() {}
// Method hiding, not overriding
static void staticMethod() {}
}
7. Does Finally Always Execute?
Finally block always executes except:
1. System.exit() is called
2. JVM crashes/dies
3. Infinite loop in try/catch
4. Fatal error in finally itself
Example:
try {
// code that might throw exception
System.exit(0); // Finally won't execute
} catch(Exception e) {
// handle exception
} finally {
// This block usually always executes
}
8. Object Class Methods
Key methods:
1. toString() - String representation
2. equals() - Compare objects
3. hashCode() - Hash code value
4. clone() - Create copy
5. finalize() - Cleanup
6. getClass() - Runtime class info
7. notify(), notifyAll(), wait() - Threading
9. Making Class Immutable
Steps:
1. Declare class as final
2. Make fields private final
3. No setter methods
4. Deep copy in constructor
5. Deep copy in getter methods
Example:
public final class ImmutableClass {
private final String name;
private final Date birthDate;
public ImmutableClass(String name, Date birthDate) {
this.name = name;
this.birthDate = new Date(birthDate.getTime()); // Deep copy
}
public String getName() {
return name;
}
public Date getBirthDate() {
return new Date(birthDate.getTime()); // Deep copy
}
}
10. Singleton Class
- Only one instance can exist
- Global point of access
- Private constructor
- Static instance
Example:
public class Singleton {
// Private static instance
private static Singleton instance;
// Private constructor
private Singleton() {}
// Public static access method
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Thread-safe version:
public class ThreadSafeSingleton {
private static volatile ThreadSafeSingleton instance;
private ThreadSafeSingleton() {}
public static ThreadSafeSingleton getInstance() {
if(instance == null) {
synchronized(ThreadSafeSingleton.class) {
if(instance == null) {
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
}