Java Interview Q&A
Java Interview Q&A
Real-life analogy: JDK is like a complete restaurant setup, JRE is like the dining area, JVM is
like the kitchen.
// Static constant
public static final double PI = 3.14159;
// Instance constant
final String STUDENT_ID;
// 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;
}
}
Example:
class Animal {
// Overloaded methods
void makeSound() {
System.out.println("Some sound");
}
Multiple Inheritance:
Platform Independence:
Pointers:
Operator Overloading:
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
@Override
protected void finalize() {
// cleanup before garbage collection
}
}
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
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
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)
1. Classes
2. Interfaces
3. Arrays
4. Enums
Types:
Components:
Example:
22. In char data type it takes two bites but c++ it takes one byte. Why?
Java uses Unicode (16 bits) for characters
o Widening (Implicit)
o Narrowing (Explicit)
Example:
// Primitive casting
int x = 10;
long y = x; // Widening
int z = (int)y; // Narrowing
// Reference casting
class Animal {}
class Dog extends Animal {}
Initialization:
Providing first value when declaring variable
Happens at creation time
Can only happen once
Can use initialization blocks
Assignment:
void method() {
assigned = 20; // Assignment
assigned = 30; // Another assignment
}
}
Example:
Required signature:
for loop:
while loop:
do-while loop:
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);
}
}
}
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:
Example:
Common in:
o Matrix operations
o Dynamic data structures
o Memory optimization
// Accessing elements
System.out.println(jagged[0][1]); // Prints 2
2. Static members
- Can be accessed without object creation
- Violates object-oriented principle
4. Methods and variables can exist outside classes (in default package)
Example:
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
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
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?
Examples:
1. Serializable
2. Cloneable
3. Remote
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() {}
}
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
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:
Example:
// Private constructor
private Singleton() {}
Thread-safe version:
private ThreadSafeSingleton() {}