KEMBAR78
Java Interview Questions | PDF | Java Virtual Machine | Method (Computer Programming)
0% found this document useful (0 votes)
17 views33 pages

Java Interview Questions

The document is a comprehensive guide on Java interview questions covering fundamentals, architecture, language basics, syntax, data types, and type conversion. It includes key concepts such as Java's platform independence, the role of JDK, JRE, and JVM, as well as explanations of various programming constructs and best practices. Additionally, it addresses advanced topics like type promotion, casting, and memory management in Java.

Uploaded by

mukeshchevula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views33 pages

Java Interview Questions

The document is a comprehensive guide on Java interview questions covering fundamentals, architecture, language basics, syntax, data types, and type conversion. It includes key concepts such as Java's platform independence, the role of JDK, JRE, and JVM, as well as explanations of various programming constructs and best practices. Additionally, it addresses advanced topics like type promotion, casting, and memory management in Java.

Uploaded by

mukeshchevula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Java Interview Questions

Java Fundamentals & Architecture

1. What is Java and what are its main features? Answer: Java is a high-level, object-
oriented programming language. Main features include:

• Platform independence (Write Once, Run Anywhere - WORA)


• Object-oriented programming
• Automatic memory management (Garbage Collection)
• Strong type checking
• Multithreading support
• Security features
2. Explain the concept "Write Once, Run Anywhere" (WORA). Answer: WORA
means Java source code compiled into bytecode can run on any platform with a JVM
installed, without recompilation. This is achieved through:

• Source code (.java) → Compiler (javac) → Bytecode (.class) → JVM → Machine


Code
3. What is the difference between JDK, JRE, and JVM? Answer:

• JDK (Java Development Kit): Complete development environment including


JRE + development tools (javac, jar, etc.)
• JRE (Java Runtime Environment): Execution environment including JVM +
core libraries
• JVM (Java Virtual Machine): Runtime engine that executes bytecode and
converts it to machine code
4. How does Java achieve platform independence? Answer: Through bytecode and
JVM:

1. Java compiler converts source code to platform-independent bytecode


2. JVM (platform-speci c) interprets/compiles bytecode to machine code
3. Same bytecode runs on any platform with appropriate JVM
5. What is bytecode in Java? Answer: Bytecode is platform-independent intermediate
code generated by Java compiler from source code. It's stored in .class les and
executed by JVM.

6. What happens when you compile a Java program? Answer:

1. javac compiler reads .java source les


2. Performs syntax checking and validation
3. Generates .class les containing bytecode
4. Bytecode is platform-independent and ready for JVM execution
7. What is the role of the Java compiler (javac)? Answer: The Java compiler:

• Converts human-readable Java source code to bytecode


• Performs syntax and semantic checking
• Generates .class les
• Detects compile-time errors
8. Explain the Java execution process step by step. Answer:

1. Write Java source code (.java les)


2. Compile using javac (creates .class les with bytecode)
3. Class Loader loads classes into JVM memory
4. Bytecode Veri er checks code safety
5. Execution Engine interprets/compiles bytecode to machine code
6. Program executes and produces output
9. What is the main method in Java and why is it important? Answer: The main
method is the entry point of Java applications:

public static void main(String[] args)

• public: Accessible from anywhere


fi
fi
fi
fi
fi
fi
fi
fi
• static: Can be called without creating object
• void: Doesn't return anything
• String[] args: Command-line arguments
10. What are the basic components of a Java program? Answer:

• Package declaration (optional)


• Import statements (optional)
• Class declaration (required)
• Main method (for executable programs)
• Other methods and variables
11. What is Just-In-Time (JIT) compilation and how does it improve
performance? Answer: JIT compilation optimizes frequently executed bytecode:

• Initially interprets bytecode line by line


• Identi es "hot spots" (frequently used code)
• Compiles hot spots to native machine code
• Caches compiled code for reuse
• Results in faster execution for repeated operations
12. Explain the different components of JVM architecture. Answer:

• Class Loader: Loads .class les into memory


• Memory Areas: Stack (method calls), Heap (objects), Method Area (class data)
• Execution Engine: Interpreter, JIT Compiler, Garbage Collector
• PC Register: Tracks currently executing instruction
• Native Method Stack: For native method calls
13. What is the difference between compile-time and runtime in Java? Answer:

• Compile-time: Source code converted to bytecode, syntax errors detected


• Runtime: Bytecode executed by JVM, logic errors and exceptions occur
14. How does garbage collection work in Java? Answer: Automatic memory
management process:
fi
fi
1. Detection: Find objects with no references
2. Marking: Mark unreachable objects
3. Sweeping: Remove marked objects from memory
4. Compaction: Reorganize memory to reduce fragmentation
15. What is the class loading process in Java? Answer:

1. Loading: Read .class le from storage


2. Linking:
◦ Veri cation: Check bytecode validity
◦ Preparation: Allocate memory for static variables
◦ Resolution: Replace symbolic references with direct references
3. Initialization: Execute static blocks and initialize static variables
16. Explain the concept of static variables and their memory
allocation. Answer: Static variables:

• Belong to class, not individual objects


• Shared among all objects of the class
• Memory allocated once when class is loaded
• Independent of object creation
• Stored in Method Area of memory
17. What are the advantages and disadvantages of Java's platform
independence? Answer: Advantages:

• Cross-platform compatibility
• Reduced development cost
• Wider market reach
Disadvantages:

• Additional JVM layer (slight performance overhead)


• JVM dependency for target platforms
• Memory overhead compared to native applications
fi
fi
18. How does JVM handle memory management differently for primitives and
objects? Answer:

• Primitives: Stored in stack memory (for local variables) or method area (for
static)
• Objects: Stored in heap memory, stack contains references
• Garbage Collection: Only applies to heap memory (objects)
• Access Speed: Stack access is faster than heap access
19. What is the difference between interpretation and compilation in JVM
context? Answer:

• Interpretation: Bytecode executed line by line (slower startup, consistent


performance)
• JIT Compilation: Frequently used bytecode compiled to machine code (faster
execution after warmup)
• Modern JVMs: Use both - interpret initially, compile hot spots
20. Explain how Java handles security at the bytecode level. Answer:

• Bytecode Veri cation: Checks code safety before execution


• Sandbox Model: Restricts operations based on code origin
• Class Loader Security: Controls which classes can be loaded
• Security Manager: Enforces security policies at runtime

Language Basics & Syntax

21. What are the naming conventions in Java? Answer:

• Classes: PascalCase (e.g., StudentRecord)


• Variables/Methods: camelCase (e.g., studentName, calculateTotal())
• Constants: UPPER_CASE (e.g., MAX_SIZE)
• Packages: lowercase (e.g., com.company.project)
fi
22. What are keywords in Java? Give examples. Answer: Reserved words with
special meaning. Examples:

• Access modi ers: public, private, protected


• Class-related: class, interface, extends, implements
• Method-related: static, void, return
• Control ow: if, else, for, while, switch
23. What is the difference between public, private, and protected? Answer:

• public: Accessible from anywhere


• private: Accessible only within the same class
• protected: Accessible within package and subclasses
24. Why is the main method static in Java? Answer: Because JVM needs to call
main method before creating any objects. Static methods belong to class and can be
called without object instantiation.

25. What is the purpose of the void keyword? Answer: void indicates that a
method doesn't return any value. Methods with void return type execute statements but
don't provide a return value to the caller.

26. How do you take input from user in Java? Answer: Using Scanner class:

Scanner input = new Scanner(System.in);


int number = input.nextInt();
String text = input.nextLine();

27. What are the different ways to output data in Java? Answer:

• System.out.println(): Print with newline


• System.out.print(): Print without newline
• System.out.printf(): Formatted output
fl
fi
28. What is the difference
between System.out.print() and System.out.println()? Answer:

• print(): Outputs text on same line


• println(): Outputs text and moves cursor to next line
29. What are literals in Java? Answer: Literals are actual values assigned to
variables:

• Integer: 25, 100


• Float: 99.99f
• Character: 'A'
• String: "Hello"
• Boolean: true, false
30. What are identi ers in Java and what are the rules for naming
them? Answer: Identi ers are names for variables, methods, classes. Rules:

• Must start with letter, underscore, or dollar sign


• Cannot start with digits
• Cannot be Java keywords
• Case sensitive
31. What is case sensitivity in Java? Answer: Java distinguishes between uppercase
and lowercase letters:

• variable and Variable are different


• main and Main are different
• String and string are different
32. How do you write comments in Java? Answer:

// Single line comment


/* Multi-line comment */
fi
fi
/** Documentation comment */

33. What is the difference between = and == operators? Answer:

• =: Assignment operator (assigns value)


• ==: Comparison operator (compares values)
34. What are escape sequences in Java? Answer: Special characters using
backslash:

• \n: Newline
• \t: Tab
• \": Double quote
• \\: Backslash
35. What is Unicode support in Java? Answer: Java supports Unicode character
encoding, allowing international characters in strings and even identi ers.
Example: String hindi = "नम ";

36. What happens if you don't write the main method in a Java
program? Answer: The program will compile successfully but
throw NoSuchMethodError at runtime when JVM tries to nd the main method as
entry point.

37. Can you have multiple classes in a single Java le? Answer: Yes, but only one
can be public and the le must be named after the public class. Non-public classes can
exist in the same le.

38. What is the difference between Java keywords and reserved


words? Answer: Java keywords are currently used by the language
(like class, public), while reserved words are kept for future use (like goto, const).
fi
fi
स्ते
fi
fi
fi
39. How does Java handle large numbers in literals? Answer: Use underscores for
readability:

int million = 1_000_000;


long billion = 1_000_000_000L;

40. What are the rules for package naming in Java? Answer:

• Use lowercase letters


• Reverse domain name convention (e.g., com.company.project)
• Separate words with dots
• Avoid Java keywords
Hard Level (41-45)

41. Explain the concept of lexical scoping in Java. Answer: Variables are accessible
based on where they are declared in the code structure. Inner blocks can access outer
variables, but not vice versa.

42. What happens during the compilation phase regarding identi ers and
keywords? Answer: Compiler checks that identi ers follow naming rules, don't con ict
with keywords, and are properly declared before use. Symbol table is created for
identi er management.

43. How does Java handle identi er collision in different scopes? Answer: Inner
scope variables can shadow outer scope variables with the same name. The innermost
declaration takes precedence within its scope.

44. What is the difference between reserved words and contextual keywords in
Java? Answer: Reserved words are always keywords, while contextual keywords
(like module, requires) have special meaning only in speci c contexts.
fi
fi
fi
fi
fi
fl
45. Explain the compilation unit concept in Java. Answer: A compilation unit is a
single .java le containing package declaration, imports, and type declarations. It's the
basic unit processed by the Java compiler.

Data Types & Type Conversion

46. What are the primitive data types in Java? Answer: 8 primitive types:

• Numeric: byte, short, int, long, float, double


• Character: char
• Boolean: boolean
47. What is the size and range of int data type? Answer:

• Size: 4 bytes (32 bits)


• Range: -2,147,483,648 to 2,147,483,647 (-2³¹ to 2³¹-1)
48. What is the difference between float and double? Answer:

• float: 4 bytes, single precision, suf x 'f' required


• double: 8 bytes, double precision, default for decimals
49. When would you use byte instead of int? Answer: Use byte when:

• Memory is limited
• Working with small numbers (-128 to 127)
• Processing large arrays of small values
50. What is the difference between char and String? Answer:

• char: Single character, primitive type, 2 bytes


• String: Sequence of characters, object type, variable size
51. What are the default values of primitive data types? Answer:
fi
fi
• Numeric types: 0 (byte, short, int, long, oat, double)
• boolean: false
• char: '\u0000' (null character)
52. How do you declare and initialize variables in Java? Answer:

int age; // Declaration


age = 25; // Initialization
int marks = 95; // Declaration + initialization

53. What is type conversion in Java? Answer: Process of converting one data type
to another. Two types:

• Implicit (Automatic): Smaller to larger type


• Explicit (Casting): Larger to smaller type
54. What is automatic type promotion? Answer: Java automatically converts smaller
data types to larger compatible types during operations to prevent data loss.

55. Give examples of valid automatic type conversions. Answer:

byte short int long float double


char int long float double

Medium Level (56-60)

56. What is type casting and when is it needed? Answer: Explicit conversion of
larger data type to smaller. Needed when:

• Converting double to int


• Converting long to int
• Data loss is acceptable
57. What happens when you cast a larger value to a smaller data
type? Answer: Data truncation occurs:








fl

double price = 99.99;
int rupees = (int) price; // Result: 99 (decimal lost)

58. Explain type promotion in expressions with examples. Answer: In expressions,


smaller types promoted to larger:

byte a = 10, b = 20;


int result = a + b; // byte + byte int + int

59. What is the difference between implicit and explicit type conversion? Answer:

• Implicit: Automatic, safe, no data loss (int to long)


• Explicit: Manual casting, potential data loss (double to int)
60. How does Java handle over ow in type casting? Answer: Values wrap around
using modulo operation:

int large = 300;


byte small = (byte) large; // Result: 44 (300 % 256)

Hard Level (61-65)

61. What are the rules for type promotion in complex expressions? Answer:

1. byte, short, char → promoted to int


2. If one operand is long → entire expression becomes long
3. If one operand is oat → entire expression becomes oat
4. If one operand is double → entire expression becomes double
62. Explain the concept of widening and narrowing conversions. Answer:

• Widening: Converting smaller to larger type (safe, automatic)


fl
fl

fl
• Narrowing: Converting larger to smaller type (requires casting, potential data
loss)
63. How does Java handle precision loss in oating-point
operations? Answer: Floating-point numbers have limited precision. Operations may
result in rounding errors. Use BigDecimal for exact decimal calculations.

64. What is the difference between signed and unsigned data types in
Java? Answer: Java doesn't have unsigned primitive types (except char). All integer
types are signed, meaning they can represent both positive and negative values.

65. How does autoboxing and unboxing relate to primitive types? Answer:

• Autoboxing: Automatic conversion of primitive to wrapper object


• Unboxing: Automatic conversion of wrapper object to primitive
Integer obj = 10; // Autoboxing
int primitive = obj; // Unboxing

Control Statements & Loops

66. What are control statements in Java? Answer: Statements that control the ow
of execution:

• Decision-making: if, if-else, switch


• Looping: for, while, do-while
• Branching: break, continue, return
67. Write the syntax of if-else statement. Answer:

if (condition) {
// statements
fl
fl
} else {
// statements
}

68. What is the difference between if-else and switch statements? Answer:

• if-else: Works with any boolean condition, more exible


• switch: Works with speci c values, faster for multiple xed comparisons
69. When should you use a for loop vs a while loop? Answer:

• for loop: When you know the exact number of iterations


• while loop: When the number of iterations is unknown
70. What is an in nite loop and how do you create one? Answer: Loop that never
terminates:

while(true) {
// statements
}
for(;;) {
// statements
}

71. What is the purpose of break and continue statements? Answer:

• break: Exits the loop completely


• continue: Skips current iteration, continues with next
72. Write a program to print numbers 1 to 10 using different loops. Answer:

// For loop
for(int i = 1; i <= 10; i++) {
fi
fi
fl
fi
System.out.println(i);
}

// While loop
int i = 1;
while(i <= 10) {
System.out.println(i);
i++;
}

73. What is the difference between while and do-while loops? Answer:

• while: Condition checked before execution (may not execute at all)


• do-while: Condition checked after execution (executes at least once)
74. How do you exit from nested loops? Answer: Use labeled break:

outer: for(int i = 0; i < 3; i++) {


for(int j = 0; j < 3; j++) {
if(condition) break outer;
}
}

75. What happens if you don't include a break statement in switch


cases? Answer: Fall-through occurs - execution continues to next case until break is
encountered or switch ends.

76. Explain the enhanced for loop (for-each) in Java. Answer: Simpli ed syntax for
iterating over arrays/collections:

int[] numbers = {1, 2, 3, 4, 5};


fi
for(int num : numbers) {
System.out.println(num);
}

77. What are the advantages and disadvantages of different loop types? Answer:

• for: Clear initialization/increment, good for counters


• while: Flexible condition checking, good for unknown iterations
• do-while: Guarantees at least one execution
78. How do you implement multiple conditions in control
statements? Answer: Using logical operators:

if(age >= 18 && age <= 65) { } // AND


if(grade == 'A' || grade == 'B') { } // OR
if(!(score < 60)) { } // NOT

79. What is short-circuit evaluation in Java? Answer: In logical operations, if the


result can be determined from the rst operand, the second operand is not evaluated:

• false && anything → false (second condition not checked)


• true || anything → true (second condition not checked)
80. Explain the ternary operator and its usage. Answer: Shorthand for if-else:

result = (condition) ? value1 : value2;


// Example:
String result = (age >= 18) ? "Adult" : "Minor";

Functions/Methods
fi
81. What is a method in Java? Answer: A block of code that performs a speci c task
and can be called when needed. Methods provide code reusability and better
organization.

82. What is the difference between a function and a method? Answer: In Java,
"method" is the correct term because functions are always associated with classes. The
terms are often used interchangeably in other languages.

83. Write the syntax of a method in Java. Answer:

access_modifier static/non-static return_type


method_name(parameters) {
// method body
return value; // if not void
}

84. What are the components of a method signature? Answer: Method signature
consists of:

• Method name
• Parameter list (number, types, and order) Note: Return type is NOT part of the
signature
85. What is the purpose of the return statement? Answer:

• Returns a value to the method caller


• Terminates method execution immediately
• Must match the declared return type
86. What happens if you don't write a return statement in a non-void
method? Answer: Compilation error occurs. Every non-void method must have a
return statement that can be reached.
fi
87. Can a method have multiple return statements? Answer: Yes, but only one will
execute per method call:

public static int absolute(int n) {


if(n >= 0) return n;
return -n;
}

88. What is the difference between parameters and arguments? Answer:

• Parameters: Variables in method de nition


• Arguments: Actual values passed when calling method
89. Write a method to calculate the area of a rectangle. Answer:

public static double calculateArea(double length, double width)


{
return length * width;
}

90. What is a void method and when do you use it? Answer: Method that doesn't
return a value. Used when you want to perform an action without producing a result:

public static void printMessage() {


System.out.println("Hello World");
}

91. How do you call a method in Java? Answer:

// For static methods


methodName(arguments);
fi
ClassName.methodName(arguments);

// For instance methods (need object)


objectName.methodName(arguments);

92. What is method overloading? Answer: Having multiple methods with the same
name but different parameters (number, type, or order).

93. Give an example of method overloading. Answer:

public static int add(int a, int b) { return a + b; }


public static double add(double a, double b) { return a + b; }
public static int add(int a, int b, int c) { return a + b + c; }

94. What are the rules for method overloading? Answer:

• Different number of parameters, OR


• Different types of parameters, OR
• Different order of parameters
• Return type alone cannot differentiate overloaded methods
95. What is variable arguments (varargs) in Java? Answer: Allows methods to
accept variable number of arguments:

public static int sum(int... numbers) {


int total = 0;
for(int num : numbers) {
total += num;
}
return total;
}
96. Explain pass by value in Java with examples. Answer: Java always passes
copies of values:

public static void changeValue(int x) {


x = 100; // Changes only the copy
}
public static void main(String[] args) {
int num = 50;
changeValue(num);
System.out.println(num); // Still 50
}

97. What is method scope and how does it work? Answer: Variables declared inside
a method are only accessible within that method. Each method has its own separate
scope.

98. Explain block scope in Java. Answer: Variables declared inside {} blocks are
only accessible within those blocks:

if(true) {
int x = 10; // Block scope
}
// x is not accessible here

99. What is variable shadowing? Answer: When an inner scope variable has the
same name as an outer scope variable, hiding the outer one:

int x = 10; // Outer scope


if(true) {
int x = 20; // Shadows outer x
System.out.println(x); // Prints 20
}
System.out.println(x); // Prints 10

100. What are the restrictions on varargs? Answer:

• Only one varargs parameter per method


• Must be the last parameter
• Treated as array internally
101. How does method call stack work in Java? Answer: Each method call creates
a new stack frame containing:

• Local variables
• Parameters
• Return address Frames are removed when methods complete (LIFO order).
102. What is method recursion and how does it work in memory? Answer: Method
calling itself. Each recursive call creates a new stack frame. Base case prevents in nite
recursion and stack over ow.

103. Explain the difference between method signature and method


declaration. Answer:

• Signature: Method name + parameter list


• Declaration: Complete method de nition including access modi ers, return type,
and body
104. How does Java determine which overloaded method to
call? Answer: Compiler uses method resolution based on:

1. Exact parameter type match


2. Primitive type promotion
fl
fi
fi
fi
3. Autoboxing/unboxing
4. Varargs (if no other match)
105. What happens to local variables when a method nishes
execution? Answer: Local variables are destroyed when method's stack frame is
removed. Memory is automatically reclaimed.

Memory Management & JVM

106. What is stack memory in Java? Answer: Memory area that stores:

• Method calls and local variables


• Reference variables (pointers to objects)
• Method parameters
• Follows LIFO (Last In, First Out) structure
107. What is heap memory in Java? Answer: Memory area where:

• Objects and instance variables are stored


• Shared among all threads
• Garbage collection occurs
• Dynamic memory allocation
108. What is the difference between stack and heap memory? Answer:

Stack Heap
Fast access Slower access
Limited size Flexible size
Method calls Objects
Automatic cleanup Garbage collection
Thread-speci c Shared
fi
fi
109. What is garbage collection? Answer: Automatic process that:

• Identi es objects with no references


• Removes unused objects from memory
• Prevents memory leaks
• Reclaims memory for reuse
110. When does an object become eligible for garbage collection? Answer: When
there are no more references pointing to it:

String str = "Hello";


str = null; // "Hello" object becomes eligible for GC

111. What is a memory leak in Java? Answer: When objects are no longer needed
but still have references, preventing garbage collection. Less common in Java due to
automatic GC.

112. What is the purpose of static variables in memory


management? Answer: Static variables:

• Allocated once when class is loaded


• Shared among all instances
• Stored in method area (not heap)
• Exist for entire program duration
113. How are primitive variables stored in memory? Answer:

• Local primitives: Stored in stack


• Instance primitives: Stored in heap (as part of object)
• Static primitives: Stored in method area
114. What happens to object references when passed to methods? Answer: Copy
of reference is passed (not the object itself). Both original and copy point to same object
in heap.
fi
115. Explain the concept of object lifecycle in Java. Answer:

1. Creation: Object instantiated in heap


2. Usage: Referenced and used by application
3. Unreachable: No more references to object
4. Garbage Collection: Object removed from memory
116. What are the different areas of JVM memory? Answer:

• Heap: Objects and instance variables


• Stack: Method calls and local variables
• Method Area: Class metadata, static variables
• PC Register: Current instruction pointer
• Native Method Stack: Native method calls
117. How does garbage collection affect application performance? Answer:

• Positive: Prevents memory leaks, automatic memory management


• Negative: GC pauses can cause temporary performance drops
• Mitigation: Modern GCs minimize pause times
118. What is the difference between young generation and old generation in
heap? Answer:

• Young Generation: New objects, frequent GC, short-lived objects


• Old Generation: Long-lived objects, less frequent GC
• Promotion: Objects surviving multiple GC cycles move to old generation
119. Explain reference types in Java memory management. Answer:

• Strong Reference: Normal references, prevent GC


• Weak Reference: Allow GC even when referenced
• Soft Reference: GC only when memory is low
• Phantom Reference: For cleanup actions
120. How does method area differ from heap memory? Answer:
• Method Area: Class metadata, static variables, method bytecode
• Heap: Instance objects and variables
• Sharing: Method area shared across all threads
• GC: Method area has different GC behavior
121. What are the different garbage collection algorithms? Answer:

• Serial GC: Single-threaded, suitable for small applications


• Parallel GC: Multi-threaded, good for throughput
• G1 GC: Low-latency, good for large heaps
• ZGC/Shenandoah: Ultra-low latency collectors
122. How can you tune JVM memory settings? Answer:

• -Xms: Initial heap size


• -Xmx: Maximum heap size
• -Xss: Stack size per thread
• -XX:NewRatio: Ratio of old/young generation
123. What is memory fragmentation and how does Java handle it? Answer:

• Problem: Free memory scattered in small chunks


• Solution: GC compaction moves objects together
• Result: Contiguous free memory blocks
124. Explain the concept of memory barriers in Java. Answer: Memory barriers
ensure proper ordering of memory operations across threads, important for volatile
variables and synchronization.

125. How does escape analysis optimize memory allocation? Answer: JVM
analyzes if objects can be allocated on stack instead of heap when they don't "escape"
method scope, improving performance.
Object-Oriented Programming Concepts

126. What is Object-Oriented Programming (OOP)? Answer: Programming


paradigm based on objects and classes, featuring:

• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
127. What is a class in Java? Answer: A blueprint or template for creating objects.
De nes attributes (variables) and behaviors (methods) that objects will have.

128. What is an object in Java? Answer: An instance of a class. A real-world entity


that has state (attributes) and behavior (methods).

129. What is the difference between a class and an object? Answer:

• Class: Template/blueprint (like building plan)


• Object: Instance of class (like actual building)
• Relationship: One class can create multiple objects
130. What is encapsulation? Answer: Bundling data (variables) and methods that
operate on that data within a single unit (class), and controlling access using access
modi ers.

131. What is inheritance in Java? Answer: Mechanism where one class (child)
acquires properties and methods of another class (parent). Promotes code reusability.

132. What is polymorphism? Answer: Ability of objects to take multiple forms. Same
method can behave differently in different classes (method overriding).
fi
fi
133. What is abstraction? Answer: Hiding implementation details and showing only
essential features to the user. Achieved through abstract classes and interfaces.

134. What is a constructor? Answer: Special method called when an object is


created. Used to initialize object state. Has same name as class and no return type.

135. What is method overriding? Answer: Rede ning a parent class method in child
class with same signature but different implementation.

136. What is the difference between method overloading and method


overriding? Answer:

Overloading Overriding
Same class Different classes (inheritance)
Different parameters Same signature
Compile-time Runtime
Static polymorphism Dynamic polymorphism

137. What is the super keyword used for? Answer:

• Access parent class methods: super.methodName()


• Access parent class variables: super.variableName
• Call parent class constructor: super()
138. What is the this keyword used for? Answer:

• Refer to current object instance


• Call other constructors: this()
• Resolve naming con icts between parameters and instance variables
fl
fi
139. What is an interface in Java? Answer: Contract that de nes what methods a
class must implement. Contains abstract methods (before Java 8) and can have default/
static methods (Java 8+).

140. What is an abstract class? Answer: Class that cannot be instantiated and may
contain abstract methods. Used as base class for other classes to extend.

String Manipulation

141. What is a String in Java? Answer: Immutable sequence of characters. String


objects are stored in heap memory and cannot be changed after creation.

142. What does "immutable" mean for Strings? Answer: Once created, String
content cannot be modi ed. Any operation that appears to change a String actually
creates a new String object.

143. What is the difference between String, StringBuilder, and


StringBuffer? Answer:

• String: Immutable, thread-safe


• StringBuilder: Mutable, not thread-safe, faster
• StringBuffer: Mutable, thread-safe, slower than StringBuilder
144. How do you compare Strings in Java? Answer:

• Use .equals() for content comparison


• Use == for reference comparison (usually not what you want)
• Use .compareTo() for lexicographic comparison
145. What is String pooling? Answer: JVM optimization where identical String literals
share the same memory location in String pool (part of heap).
fi
fi
146. What is the difference between String s = "Hello" and String s
= new String("Hello")? Answer:

• "Hello": Creates/reuses String in string pool


• new String("Hello"): Always creates new object in heap
147. Why should you use StringBuilder for multiple String
concatenations? Answer: String concatenation with + creates new objects each time.
StringBuilder modi es internal buffer, avoiding object creation overhead.

148. What are some commonly used String methods? Answer:

• length(): String length


• charAt(index): Character at index
• substring(start, end): Extract portion
• indexOf(char): Find character position
• toLowerCase(), toUpperCase(): Case conversion
149. How does String concatenation work internally? Answer: Compiler
converts + operations to StringBuilder operations for ef ciency. Multiple concatenations
use StringBuilder.append() internally.

150. What is the performance difference between String and


StringBuilder? Answer:

• String concatenation: O(n²) time complexity for n operations


• StringBuilder: O(n) time complexity, much more ef cient for multiple operations

Exception Handling

151. What is an exception in Java? Answer: Abnormal event that occurs during
program execution and disrupts normal ow. Examples: division by zero, le not found.
fi
fl
fi
fi
fi
152. What is the difference between checked and unchecked
exceptions? Answer:

• Checked: Must be handled or declared (IOException, SQLException)


• Unchecked: Runtime exceptions, handling optional (NullPointerException,
ArrayIndexOutOfBoundsException)
153. What is the try-catch block? Answer: Mechanism to handle exceptions:

try {
// risky code
} catch (ExceptionType e) {
// handle exception
}

154. What is the purpose of the nally block? Answer: Code that always executes,
whether exception occurs or not. Used for cleanup (closing les, connections).

155. What is the difference between throw and throws? Answer:

• throw: Used to explicitly throw an exception


• throws: Used in method signature to declare exceptions method might throw
156. What is exception propagation? Answer: When a method doesn't handle an
exception, it's passed up to the calling method. Continues until handled or reaches main
method.

157. Can you have multiple catch blocks? Answer: Yes, to handle different
exception types:

try {
// code
} catch (IOException e) {
fi
fi
// handle IO exception
} catch (SQLException e) {
// handle SQL exception
}

158. What is a custom exception? Answer: User-de ned exception class extending
Exception or RuntimeException:

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

159. What happens if an exception occurs in a nally block? Answer: The


exception in nally block suppresses any exception from try block. Original exception is
lost unless properly handled.

160. What is try-with-resources? Answer: Automatic resource management


introduced in Java 7:

try (FileReader file = new FileReader("file.txt")) {


// use file
} // automatically closed

Advanced Java Concepts


fi
fi
fi
161. What is multithreading in Java? Answer: Executing multiple threads
concurrently within a single program. Allows parallel execution and better resource
utilization.

162. What is the Collections Framework? Answer: Set of classes and interfaces for
storing and manipulating groups of objects. Includes List, Set, Map interfaces and their
implementations.

163. What is the difference between ArrayList and LinkedList? Answer:

• ArrayList: Dynamic array, fast random access, slower insertion/deletion


• LinkedList: Doubly linked list, slower access, faster insertion/deletion
164. What is a HashMap? Answer: Key-value pair storage using hash table. Provides
O(1) average time complexity for get/put operations.

165. What is the difference between HashMap and TreeMap? Answer:

• HashMap: Hash table based, O(1) operations, no ordering


• TreeMap: Red-black tree based, O(log n) operations, sorted by keys
166. What is generics in Java? Answer: Type parameterization that provides compile-
time type safety:

List<String> list = new ArrayList<String>();

167. What is re ection in Java? Answer: Ability to inspect and manipulate classes,
methods, and elds at runtime. Used by frameworks for dynamic behavior.

168. What is serialization? Answer: Converting object state into byte stream for
storage or transmission. Object must implement Serializable interface.

169. What is the difference between synchronized and volatile? Answer:

• synchronized: Provides mutual exclusion and memory consistency


fi
fl
• volatile: Ensures visibility of changes across threads, no mutual exclusion
170. What are lambda expressions? Answer: Anonymous functions introduced in
Java 8 for functional programming:

list.forEach(item -> System.out.println(item));

You might also like