0% found this document useful (0 votes)
3 views50 pages

Java Interview Questions

The document provides a comprehensive overview of Java programming, covering fundamental concepts such as Java's definition, key features, JVM, JDK, data types, operators, control statements, OOP principles, and more. It includes explanations of various Java constructs like class loaders, typecasting, encapsulation, inheritance, and polymorphism, along with examples for clarity. Additionally, it outlines the advantages of packages, access specifiers, and operator precedence, making it a valuable resource for Java interview preparation.

Uploaded by

V.M.Hariharan
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)
3 views50 pages

Java Interview Questions

The document provides a comprehensive overview of Java programming, covering fundamental concepts such as Java's definition, key features, JVM, JDK, data types, operators, control statements, OOP principles, and more. It includes explanations of various Java constructs like class loaders, typecasting, encapsulation, inheritance, and polymorphism, along with examples for clarity. Additionally, it outlines the advantages of packages, access specifiers, and operator precedence, making it a valuable resource for Java interview preparation.

Uploaded by

V.M.Hariharan
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/ 50

JAVA INTERVIEW QUESTIONS

1. What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now


owned by Oracle) and released in 1995. It is designed to be platform-independent using the "Write
Once, Run Anywhere" (WORA) principle, which means Java code can run on any device that has a Java
Virtual Machine (JVM).

2. What are the key features of java?

• Object-Oriented – Follows OOP principles (Encapsulation, Inheritance, Polymorphism,


Abstraction) for modular and reusable code.
• Platform-Independent – Java uses "Write Once, Run Anywhere" (WORA) with the help of JVM.
• Simple & Secure – No pointers, automatic memory management, and security features like
Bytecode Verification and Security Manager.
• Robust – Strong memory management, Garbage Collection, and Exception Handling prevent
crashes.
• Multi-threaded – Supports parallel execution for better performance.
• High Performance – Uses JIT (Just-In-Time) Compiler for faster execution.
• Distributed – Supports RMI (Remote Method Invocation) and networking capabilities.
• Dynamic & Portable – Java dynamically loads classes at runtime and runs on any system with a
JVM.

3.Define JVM?
JVM is the abbreviation for Java Virtual Machine. It is a virtual machine that provides a runtime
environment to write code. JVM is a part of JRE (Java Runtime Environment) and is used to convert the
bytecode into machine-level language. This machine is responsible for allocating memory.

4.Name the memory areas that are allocated by JVM ?

JVM allocates memory into five key areas for efficient execution:

1. Class Area (Method Area) – Stores class-level metadata, including static variables and method
information.

2. Heap – Stores objects and instance variables. It is managed by Garbage Collection (GC).

3. Stack – Stores method call frames, including local variables and return values. Each thread has
its own stack.

4. Native Method Stack – Handles native (non-Java) method calls, such as C/C++ via JNI.

5. PC Register – Stores the current instruction address of the executing method.


5.Explain the class loader in JVM?

The ClassLoader loads Java class files into memory when a program runs. It follows a hierarchical
delegation model, meaning each class loader delegates the loading task to its parent first.

Types of Class Loaders

1. Bootstrap ClassLoader – Loads core Java classes (java.lang.*, java.util.*). It is written in native
code.

2. Extension ClassLoader (Platform ClassLoader in Java 9+) – Loads classes from lib/ext/ or Java
module system.

3. Application ClassLoader (System ClassLoader) – Loads user-defined classes from the


classpath (bin/, lib/).

Key Point: If a class is not found in any parent class loader, the child class loader attempts to load it.

6.What is JDK?
Java Development Kit is one of the three prominent technology packages used in Java programming. JDK
is used as a standalone component to run the Java programs by JVM and JRE. This kit is used to
implement Java platform specifications, including class libraries and compiler.

7.What are the different types of variables in Java?


There are mainly three different types of variables available in Java, and they are
1.Static Variables
2.Local Variables
3.Instance Variables

8.What is Typecasting?
Typecasting in Java is done explicitly by the programmer; this is done to convert one data type into
another data type.
Widening (automatically) - conversion of a smaller data type to a larger data type size.
byte -> short -> char -> int -> long -> float -> double
Narrowing (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

9.What is Type Conversion?


Type conversion can be defined as converting one data type to another data type automatically by the
compiler.There are two types of type conversions, and they are:

1. Implicit type conversion


2.Explicit type conversion.

10.What are primitive data types?

Primitive data types in Java are the major constituents of data manipulation. These are the most
basic data types that are available in Java. The primitive data types include int, char, byte, float,
double, long, short, and boolean.

11.What are non-primitive data types?


Non-primitive data types are reference types that do not store actual values but store references to
memory locations where the data is kept. Unlike primitive types, they can have methods and properties.

Key Differences from Primitive Types:

• Stored in Heap Memory (not Stack).

• Can have methods and properties.

• Can be null, unlike primitives.

12.Write the syntax for object declaration in Java?

The new keyword is used to create an object.


ClassName objectName = new ClassName();

Example:

class Car {

String model = "Tesla";

public class Main {

public static void main(String[] args) {

Car myCar = new Car(); // Object declaration and creation

System.out.println(myCar.model); // Output: Tesla

Explanation:

1. ClassName → The name of the class (e.g., Car).


2. objectName → The reference variable storing the object (e.g., myCar).

3. new → Allocates memory for the object.

4. Constructor → Calls the class constructor to initialize the object.

13.Is there any default value for local variables?

No, local variables are not initialized by any default values.

14.How many types of operators are available in Java?


Java provides eight types of operators to perform different operations:

1. Arithmetic Operators – +, -, *, /, % (Used for mathematical operations).

2. Assignment Operators – =, +=, -=, *=, /=, %= (Used to assign values).

3. Logical Operators – &&, ||, ! (Used for boolean logic).

4. Relational (Comparison) Operators – ==, !=, >, <, >=, <= (Used to compare values).

5. Bitwise Operators – &, |, ^, ~, <<, >> (Operate at the bit level).

6. Unary Operators – +, -, ++, --, ! (Work on a single operand).

7. Ternary Operator – condition ? trueValue : falseValue; (Shortens if-else).

8. Shift Operators – <<, >>, >>> (Shifts bits left or right).

15.What is operator precedence in Java?


Operator precedence in Java defines the rules that determine the order in which operators are
evaluated in an expression. Operators with higher precedence are executed before those with lower
precedence. If multiple operators have the same precedence, the associativity rule (left-to-right or
right-to-left) determines the execution order.

16.What are the different logical operators in Java?

Operator Description

This operator can be used with


logical expressions, boolean type
Logical NOT variables, and relational variables,
The Logical NOT operator is denoted
by the symbol “!”
These logical operators operate only
Logical OR on boolean variable types and the
symbol for this operator is “||”

We can combine many relational


operations using this operator and
Logical AND the output will be of boolean type.
The “&&” is the symbol for logical
AND

17.What is the role of the unary operator in Java?

A unary operator in Java is an operator that operates on a single operand. It is mainly used for:

• Incrementing (++) or decrementing (--) values

• Negating an expression (-)

• Inverting a boolean value (!)

18.Define left shift and right shift operators in Java?

Left shift (<<) and right shift (>>, >>>) are bitwise shift operators in Java that shift the bits of a
number left or right.

1. Left Shift (<<)

• Moves bits toward the left by a specified number of positions.

• Zeros (0s) are added to the rightmost places.

• Each shift multiplies the number by 2.

2. Right Shift (>>)

• Moves bits toward the right by a specified number of positions.

• Copies the leftmost bit (sign bit) for negative numbers (Sign extension).

• Each shift divides the number by 2.

19.What is a ternary operator?

The Ternary operator (?:) In Java is a conditional operator used as a shorthand for if-else statements. It
evaluates an expression and returns one of two values based on whether the condition is true or
falsevariable= (expression) ? variable = (condition) ? value_if_true : value_if_false;
int a = 10, b = 20;

int min = (a < b) ? a : b; // If a < b is true, min = a; otherwise, min = b

System.out.println("Minimum: " + min); // Output: Minimum: 10

20.What are Java keywords? Java


keywords are also called “Reserved keywords” that act as a key to a code. Keywords in Java are
predefined that cannot be used as an object name or variable. There are many keywords in Java, and
some of them are: 1.abstract
2.default
3.new

21.What are various access specifiers present in Java?


There are four access specifiers present in Java, and they are:
1.Public: The methods, classes, and variables that are defined as the public can be accessed by any class
or method.

2.Private: The methods or classes which are declared as private can be accessible within the same class
only.

3.Protected: The variables, methods, and classes which are defined as private can be accessed within
the same class of the same package or by the subclass of the same class.

4.Default: By default, all the classes, variables, and methods are of default scope. The default is
accessible within the package only.

22.What are the advantages of packages in Java?:

1.Name clashes are avoided using packages


2.Packages enable easier access control
3.Packages provide an effective and easier way to locate the related classes.

23.List out the control statements in Java?

Control statements in Java regulate the flow of execution in a program. They are categorized into
three types:

1. Selection Statements (Decision-Making Statements)

Used to execute code based on conditions.

• if statement

• if-else statement

• switch statement
Example:

int num = 10;

if (num > 0) {

System.out.println("Positive number");

} else {

System.out.println("Negative number");

2. Iterative (Looping) Statements

Used to execute a block of code multiple times.

• for loop

• while loop

• do-while loop

Example:

for (int i = 1; i <= 5; i++) {

System.out.println(i);

3. Jump Statements

Used to control the flow by jumping to another part of the program.

• break (Exits a loop or switch case)

• continue (Skips the current iteration)

• return (Exits from a method and returns a value)

Example:

for (int i = 1; i <= 5; i++) {

if (i == 3) {

continue; // Skips iteration when i == 3


}

System.out.println(i);

Key Points:

✔ Selection statements → Choose between multiple paths.


✔ Looping statements → Repeat execution.
✔ Jump statements → Control execution flow.

24.What is the difference between a while loop and a do-while loop?


The key difference between while and do-while loops is when the condition is checked:

Loop Type Condition Checking Execution Guarantee

Condition is checked before entering the May not execute if the condition is false
while loop
loop. initially.

do-while Condition is checked after executing the Executes at least once, even if the condition
loop loop body. is false.

While Loop Example:

int i = 5;

while (i < 5) { // Condition is false initially, so this won't execute.

System.out.println("Hello");

Do While Loop Example:

int i = 5;

do {

System.out.println("Hello");

} while (i < 5); // Condition is false, but executes once.

25.What are the comments in Java?


Java comments are statements that are not executed by the interpreter and compiler. These are used to
provide information about the class, variables, methods, and any statements. Comments are mainly used
to hide program code for a specific time.
1.Documentation comment
2.Multi-line comment
3.Single-line comment

26.Describe in brief OOPs concepts?


OOPs is an abbreviation for Object-Oriented Programming Language which entirely deals with an
object. The main aim of OOPs is to implement real-world entities such as objects, classes, inheritance,
polymorphism, and so on. Simula is considered the first object-oriented programming language. The
most popular programming languages are Java, Python, PHP, C++, and many others.
The following are the OOPs concepts that are included in Java:
1.Class
2.Object
3.Abstraction
4.Encapsulation
5.Inheritance
6.Polymorphism

27.What is Abstraction in Java?


Abstraction is the process of hiding the internal implementation details and showing only the
essential functionality to the user. It helps in reducing complexity and improving code maintainability.

Ways to Achieve Abstraction in Java:

1. Using Abstract Classes (abstract keyword) → Can have both abstract and concrete methods.

2. Using Interfaces → Provides complete abstraction (before Java 8).

Example: Using an Abstract Class

abstract class Vehicle {

abstract void start(); // Abstract method (no implementation)

class Car extends Vehicle {

void start() {

System.out.println("Car starts with a key");

}
}

public class Main {

public static void main(String[] args) {

Vehicle myCar = new Car();

myCar.start(); // Output: Car starts with a key

Real-World Example of Abstraction:

• ATM Machine – You just insert your card and withdraw money (functionality exposed), but the
internal process (validations, transactions) is hidden.

28.Define encapsulation?

Encapsulation is the process of binding data (variables) and code (methods) together into a single
unit to prevent direct access from outside the class. It helps in data hiding and security.

Example of Encapsulation in Java:

class Student {

private String name; // Private data member

// Getter method

public String getName() {

return name;

// Setter method

public void setName(String name) {

this.name = name;

}
}

public class Main {

public static void main(String[] args) {

Student s = new Student();

s.setName("John"); // Setting value

System.out.println(s.getName()); // Getting value (Output: John)

Real-World Example:

• Capsule (Medicine): Just like a capsule hides the medicine inside, encapsulation hides data
inside the class and only exposes controlled access.

29.What is Inheritance in Java?

Inheritance is a mechanism where a child class (subclass) acquires the properties and behaviors of a
parent class (superclass). It promotes code reusability and helps in achieving runtime polymorphism.

Types of Inheritance in Java:

1. Single Inheritance – One class inherits from another.

2. Multilevel Inheritance – A class inherits from a derived class.

3. Hierarchical Inheritance – Multiple classes inherit from a single parent.

4. Multiple Inheritance (via Interfaces) – A class implements multiple interfaces.

Java does not support multiple inheritance with classes to avoid ambiguity.

Example of Inheritance in Java:

class Animal {

void makeSound() {

System.out.println("Animal makes a sound");


}

class Dog extends Animal { // Dog inherits Animal

void bark() {

System.out.println("Dog barks");

public class Main {

public static void main(String[] args) {

Dog d = new Dog();

d.makeSound(); // Inherited method

d.bark(); // Child class method

Real-World Example:

• Father-Son Relationship – A child inherits genetic traits from parents.

30.What is Polymorphism in Java?

Polymorphism in Java allows a single task to be performed in multiple ways. It enables method
behavior to change based on the object that invokes it. Polymorphism improves code flexibility and
reusability.

Types of Polymorphism in Java:

1. Compile-Time Polymorphism (Method Overloading)

o Multiple methods with the same name but different parameters.


o Decided at compile time.

Example:

class MathUtils {

int add(int a, int b) {

return a + b;

double add(double a, double b) {

return a + b;

2. Runtime Polymorphism (Method Overriding)

o A child class provides a specific implementation of a method from the parent class.

o Decided at runtime using dynamic method dispatch.

Example:

class Animal

void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

void sound() { // Overriding the parent method

System.out.println("Dog barks");

}
Real-World Example:

• A person behaves differently in different situations (a student in class, a player on the field).

31.What are the advantages of OOPs?

1.OOPs provides data hiding


2.OOPs makes development and maintenance easier when compared to a procedural programming
language. 3.OOPs has the ability to stimulate real-world entities more effectively.

32.What are the rules we need to follow to declare a class?

1.It should start with an uppercase letter.


2.The class name must be a noun such as Thread, Class, Java, and so on.

33.Define Constructor in Java?

A constructor is a special method used to initialize objects in Java. It is called automatically when an
object is created using the new keyword. The constructor has the same name as the class and does not
have a return type.

Types of Constructors in Java:

1. Default Constructor (No Arguments)

o Automatically provided if no constructor is defined.

o Initializes objects with default values.

class Car {

Car() { // Default constructor

System.out.println("Car object created");

2. Parameterized Constructor

o Accepts arguments to initialize object properties.

class Car {

String model;

Car(String m) { // Parameterized constructor


model = m;

3. Copy Constructor (Not Built-in, Manually Defined)

o Creates a new object by copying values from another object.

class Car {

String model;

Car(Car c) { // Copy constructor

this.model = c.model;

Example of Constructor Usage:

class Car {

String model;

// Constructor

Car(String m) {

model = m;

public static void main(String[] args) {

Car myCar = new Car("Tesla");

System.out.println("Car Model: " + myCar.model);

Output:

Car Model: Tesla


Real-World Example:

• When you buy a phone, it comes pre-configured with some settings. Similarly, a constructor
initializes an object when it is created.

34.What all the rules must be followed while creating a constructor in Java?

Same Name as Class – The constructor must have the same name as the class.

No Return Type – A constructor does not have an explicit return type, not even void.

Cannot Have Certain Modifiers – A constructor cannot be synchronized, abstract, final, or


static because:

o abstract → A constructor must be called, but abstract classes cannot be instantiated.

o final → Constructors cannot be inherited, so final has no meaning.

o static → A constructor is tied to an object, while static belongs to the class.

o synchronized → No need, as each object has its own constructor.

Example of Constructor Rules in Java:

class Car {

String model;

// Constructor with the same name as class

Car(String m) {

model = m;

public static void main(String[] args) {

Car myCar = new Car("Tesla"); // No return type, called automatically

System.out.println("Car Model: " + myCar.model);

}
Output:

Car Model: Tesla

35.What are the different types of constructors available in Java?


1.Default constructor,2.Parameterized constructor

1.Default constructor: It is also called a no-argument constructor and it is mainly used to initialize the
instance variable with the default value. Moreover, it is also used to perform some useful tasks on object
creation. This default constructor is implicitly invoked by the compiler if there is no constructor for a
particular class.

2.Parameterized constructor: A parameterized constructor is one type of constructor which is mainly


used to initialize the instance variables with the given values. In simple words, the constructor that
accepts arguments is called a parameterized constructor.

36.What is the use of a copy constructor in Java?


There is no copy constructor in Java, we can copy the values from one object to another same as that of
a copy constructor in C++. In Java, there are many ways to copy the values of one object to another and
they are:

1.By using Clone() of object class


2.By using constructor
3.By assigning the value of one object to another

37.Define the method in Java?

A method in Java is a block of code that performs a specific task and can be executed by calling its
name. It helps in code reusability, modularity, and readability.

returnType methodName(parameters) {

// Method body

return value; // (if returnType is not void)

class Calculator {

// Method to add two numbers

int add(int a, int b) {

return a + b;
}

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println(calc.add(5, 10)); // Output: 15

38.Difference between constructor and method?

The difference between constructor and method are as follows:

Constructor Method

The constructor should have the The method name is not the
same name as the class name same as that of the class name

The method must have a return


A constructor has no return type
type

It can be invoked implicitly It can be invoked explicitly

39.What is the role of static keywords in Java?

The static keyword in Java is used for memory management. It allows members to be shared across all
objects of a class, instead of each object having its own copy. The static keyword can be applied to
variables, methods, blocks, and nested classes.

40.Define this keyword in Java?

The this keyword in Java refers to the current object of the class. It is used to differentiate between
instance variables and local variables, call constructors, return the current instance, and pass the object
as an argument.

Uses of this Keyword:

1. Refers to Instance Variables (Avoids Name Conflict)

class Student {
String name;

Student(String name) {

this.name = name; // Refers to the instance variable

2. Calls Another Constructor in the Same Class (this())

class Demo {

Demo() { System.out.println("Default constructor"); }

Demo(int x) {

this(); // Calls the default constructor

System.out.println("Parameterized constructor: " + x);

3. Returns the Current Class Instance

class Test {

Test getInstance() {

return this; // Returns current object

4. Passes the Current Object as an Argument

class A {

void show(A obj) {

System.out.println("Method called");

void display() {
show(this); // Passing current object

41.Why we use inheritance in Java?


1.For code reusability 2.For method overriding

42.Write the syntax for inheritance in Java?


The syntax for inheritance in Java is as follows:

class Superclass extends subclass{

//code }

43.What are Java packages?

A package in Java is a collection of related classes and interfaces that are grouped together. It helps in
organizing code, avoiding name conflicts, and promoting reusability. Packages can be imported into
different classes for easy access.

Types of Packages in Java:

1. Built-in Packages – Predefined Java packages (e.g., java.util, java.io).

2. User-defined Packages – Custom packages created by developers.

44.What are the different ways to overload a method? 1.By


changing the data type , 2.By changing the number of arguments

45.What is method overriding in Java?


Method Overriding in Java occurs when a subclass provides a specific implementation of a method
that is already defined in its superclass. The method in the subclass must have the same name, return
type, and parameters as the method in the superclass.

45.What is method overloading in Java?

Method Overloading in Java allows multiple methods in the same class to have the same name but
with different parameters (different number, type, or order of parameters). It enables compile-time
polymorphism.

46.What is the usage of method overriding in Java?


Method overriding is used to achieve run-time polymorphism and also it is used to provide a specific
implementation for a method that is already given by its subclass.

47.What is the difference between aggregation and composition?


Aggregation and Composition are both types of Association in Java, used to define relationships
between classes. The key difference lies in the strength of the relationship:

Feature Aggregation (Weak Relationship) Composition (Strong Relationship)

One class has-a relationship with another, but they One class owns another class, and
Definition
can exist independently. they cannot exist separately.

Objects can exist independently even if the Dependent objects cannot exist
Dependency
relationship is removed. without the parent object.

The contained object can survive even after the The contained object is deleted when
Lifespan
container is deleted. the container is deleted.

A Department has multiple Employees, but an A Human has a Heart, and a Heart
Example
Employee can exist without a Department. cannot exist without a Human.

Example of Aggregation (Weak Relationship)

class Department {

String name;

Department(String name) { this.name = name; }

class Employee {

String empName;

Department dept; // Aggregation (Employee has-a Department)

Employee(String empName, Department dept) {

this.empName = empName;

this.dept = dept;

Example of Composition (Strong Relationship)


class Heart {

void beat() {

System.out.println("Heart is beating...");

class Human {

private Heart heart; // Composition (Human has-a Heart)

Human() { this.heart = new Heart(); } // Heart exists only inside Human

48.Explain JDK, JRE and JVM?

JDK vs JRE vs JVM

JDK JRE JVM

It stands for
It stands for
Java
Java Runtime It stands for Java Virtual Machine.
Development
Environment.
Kit.

It is the tool
JRE refers to a
necessary to
runtime
compile, It is an abstract machine. It is a specification
environment in
document that provides a run-time environment in
which Java
and package which Java bytecode can be executed.
bytecode can
Java
be executed.
programs.

It contains It’s an
JVM follows three notations:
JRE + implementation
Specification, Implementation, and Runtime
development of the JVM
which Instance.
tools.
physically
exists.

49.Why Java is platform independent? Java is


platform-independent because its compiled bytecode can run on any system, regardless of the
operating system. Instead of compiling directly into machine code, Java programs are compiled into an
intermediate form called bytecode, which is executed by the Java Virtual Machine (JVM).

50.Why Java is not 100% Object-oriented?


Java is not 100% Object-oriented because it makes use of eight primitive data types such as
boolean, byte, char, int, float, double, long, short which are not objects.

51.What are wrapper classes in Java?


Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type
has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data
type into an object of that class. Refer to the below image which displays different primitive type,
wrapper class and constructor argument.

53.What is singleton class in Java and how can we make a class singleton?

A Singleton class is a class that allows only one instance to be created at a time within a single JVM.
It is used when a single shared resource (e.g., database connection, logging system) is needed
throughout the application.

How to Create a Singleton Class in Java?

A class can be made singleton by:

1. Making the constructor private (prevents object creation from outside).

2. Providing a static method to return the single instance.

3. Using a static variable to store the single instance.

Example of a Singleton Class:

class Singleton {

private static Singleton instance; // Single instance

private Singleton() { } // Private constructor


public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

return instance;

public class Main {

public static void main(String[] args) {

Singleton obj1 = Singleton.getInstance();

Singleton obj2 = Singleton.getInstance();

System.out.println(obj1 == obj2); // Output: true (Same instance)

54.What is the difference between Array list and vector in Java?

ArrayList Vector

Array List is not synchronized. Vector is synchronized.

Array List is fast as it’s non-


Vector is slow as it is thread safe.
synchronized.

If an element is inserted into the Array


Vector defaults to doubling size of its array.
List, it increases its Array size by 50%.

Array List does not define the


Vector defines the increment size.
increment size.

Array List can only use Iterator for Vector can use both Enumeration and
traversing an Array List. Iterator for traversing.

55.How is the creation of a String using new() different from that of a literal?
When we create a string using new(), a new object is created. Whereas, if we create a string using the
string literal syntax, it may return an already existing object with the same name.

Key Differences:

Feature String Literal new Keyword

Memory Storage Stored in String Pool Stored in Heap Memory

Duplicate Objects Reuses existing objects Always creates a new object

Performance Faster (uses cached values) Slower (allocates new memory)

When to Use?

✔ Use string literals for better memory efficiency.


✔ Use new when you explicitly need a separate object

56.Why pointers are not used in Java?

Java does not support pointers because they are unsafe and increase complexity. Instead, Java uses
references to handle memory indirectly, making the language more secure and simple.

Reasons Why Java Avoids Pointers:

1. Security & Memory Safety → Pointers allow direct memory manipulation, which can lead to
security vulnerabilities and memory corruption.

2. Simplicity & Readability → Java focuses on ease of use, and pointers make code more complex.

3. Garbage Collection → The JVM handles memory allocation and deallocation automatically,
eliminating the need for manual pointer management.

4. Avoiding Dangling & Wild Pointers → Pointers can reference invalid memory locations, leading
to crashes and unpredictable behavior.

57.What is JIT compiler in Java?


JIT (Just-In-Time) Compiler in Java is a performance optimization feature that converts bytecode into
native machine code at runtime. This speeds up execution since the compiled code is executed directly
by the CPU instead of being interpreted line by line.

How JIT Works:

1. Java code is first compiled into bytecode (.class file).

2. The JVM interprets bytecode, but frequently used methods are compiled into native machine
code by the JIT compiler.

3. The compiled machine code is cached, improving performance for future executions.

58.Why is synchronization necessary? Explain with the help of a relevant example.


Synchronization in Java is a mechanism that ensures only one thread can access a shared resource at
a time. It prevents race conditions and memory inconsistency errors when multiple threads access the
same variable or object.

59.What are access modifiers in Java? In


Java, access modifiers are special keywords which are used to restrict the access of a class, constructor,
data member and method in another class. Java supports four types of access modifiers:

Access modifiers in Java are special keywords that control the visibility of classes, methods, and
variables in other classes or packages. Java supports four types of access modifiers:

Types of Access Modifiers in Java:

1. private (Most Restrictive)

• Members declared private are only accessible within the same class.

• Not accessible in subclasses or other classes.

class A {

private int data = 10;

private void show() { System.out.println(data); }

2. Default (No Keyword)

• Members without an access modifier are accessible within the same package but not outside.

class A {

int data = 10; // Default access


}

3. protected (Limited to Package & Subclasses)

• Members are accessible within the same package and in subclasses (even in different
packages).

class A {

protected int data = 10;

4. public (Least Restrictive)

• Members declared public are accessible everywhere.

class A {

public int data = 10;

Key Points:

✔ private → Only within the same class.


✔ Default (no modifier) → Within the same package.
✔ protected → Same package + Subclasses in different packages.
✔ public → Accessible everywhere.

60.What is an object in Java and how is it created?


An object in Java is a real-world entity that has:

1. State → Represents data (variables) (e.g., color, name, age).

2. Behavior → Represents methods (functions) (e.g., run, jump, drive).

3. Identity → A unique reference in memory.

How to Create an Object in Java?

An object is created using the new keyword:

ClassName obj = new ClassName();

Example:

class Car {
String model = "Tesla"; // State

void drive() { // Behavior

System.out.println(model + " is driving.");

public static void main(String[] args) {

Car myCar = new Car(); // Object creation

myCar.drive(); // Output: Tesla is driving.

62.Differentiate between the constructors and methods in Java?

Methods Constructors

1. Used to represent the behavior of an


1. Used to initialize the state of an object
object

2. Must have a return type 2. Do not have any return type

3. Needs to be invoked explicitly 3. Is invoked implicitly

4. No default method is provided by the 4. A default constructor is provided by the compiler if


compiler the class has none

5. Method name may or may not be same 5. Constructor name must always be the same as the
as class name class name

63.What is final keyword in Java?

The final keyword in Java is a non-access modifier used to restrict modification of variables,
methods, and classes.

1. final Variable → Its value cannot be changed after initialization.

2. final Method → Cannot be overridden by subclasses.


3. final Class → Cannot be inherited by other classes.

64.What is a Map in Java?

A Map in Java is an interface from the java.util package that stores key-value pairs, where:
✔ Keys are unique (No duplicates allowed).
✔ Each key maps to at most one value (One-to-one mapping).
✔ It is not part of the Collection interface but is still part of the Java Collection Framework.

Common Implementations of Map:

1. HashMap → Stores elements in random order, allows null keys.

2. LinkedHashMap → Maintains insertion order.

3. TreeMap → Stores elements in sorted order (based on keys).

4. Hashtable → Synchronized version of HashMap (thread-safe).

65. What is collection class in Java? List down its methods and interfaces.

The Java Collection Framework (JCF) is a predefined architecture for storing, processing, and
manipulating a group of objects efficiently. It provides various classes and interfaces to handle data
structures like lists, sets, queues, and maps.

Key Features of Collections in Java:

✔ Supports dynamic resizing (unlike arrays).


✔ Provides built-in methods for sorting, searching, insertion, and deletion.
✔ Improves performance by using optimized data structures.

66.What is the usage of this keyword in Java?


1.It is used to refer to the current class instance variable.
2.This is also used to invoke the current class constructor

3.It is used to invoke the current class method


4.It can be passed as an argument in the method call and in the constructor call

67.Can this keyword be used to refer to the current class instance variable?
Yes, this keyword is used to refer to the current class instance variable and it is also used to initiate or
invoke the current class constructor.

68.Which class is the superclass for all the classes in Java?


An object class is a superclass for all the classes in Java.
69. What is Java String Pool?

The Java String Pool is a special memory area inside the Heap, where string literals are stored. It helps
optimize memory usage by reusing existing string objects instead of creating new ones.

70. What will happen if we declare don’t declare the main as static?

We can declare the main method without using static and without getting any errors. But, the main
method will not be treated as the entry point to the application or the program.

71. What is the difference between an instance variable and a class variable in Java?

In Java, instance variables and class variables differ in scope, memory allocation, and access.

Feature Instance Variable Class Variable (Static Variable)

Declared with the static keyword inside a


Declaration Inside a class but outside methods
class

Stored in Method Area (single copy for all


Memory Stored in Heap memory (inside objects)
objects)

Instance- Belongs to an object (each object has its Shared among all objects (one copy for the
Based? own copy) entire class)

Access Accessed via object reference Accessed via class name or object reference

Example int age; (without static) static int count;

72. What is the difference between System.out, System.err, and System.in?

System.out – It is a PrintStream that is used for writing characters or can be said it can output the data
we want to write on the Command Line Interface console/terminal.

System.err – It is used to display error messages.

System.in – It is an InputStream used to read input from the terminal Window.

73. How many ways you can take input from the console?

There are two methods to take input from the console in Java mentioned below:

1. Using Command line argument


2. Using Buffered Reader Class

3. Using Console Class

4. Using Scanner Class

72. Difference in the use of print, println, and printf.


print, println, and printf all are used for printing the elements but print prints all the elements
and the cursor remains in the same line. println shifts the cursor to next line. And with printf
we can use format identifiers too.

73. What is dot operator?

The Dot operator in Java is used to access the instance variables and methods of class objects. It is
also used to access classes and sub-packages from the package.

73. What are the differences between String and StringBuffer?

String StringBuffer

Store of a sequence of characters. Provides functionality to work with the strings.

It is mutable (can be modified and other string


It is immutable.
operations could be performed on them.)

No thread operations in a string. It is thread-safe (two threads can’t call the


methods of StringBuffer simultaneously)

74. What are the differences between StringBuffer and StringBuilder?

StringBuffer StringBuilder

StringBuffer provides functionality to work with StringBuilder is a class used to build a mutable
the strings. string.
StringBuffer StringBuilder

It is thread-safe (two threads can’t call the It is not thread-safe (two threads can call the
methods of StringBuffer simultaneously) methods concurrently)

Being non-synchronized, implementation is


Comparatively slow as it is synchronized.
faster

75. Can we execute a program without main() method?

No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not
possible to execute a Java class without the main method..

76. What is marker or tagged interface?

An interface which has no member is known as a marker or tagged interface, for example,
Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM
so that JVM may perform some useful operation.

77. What do you understand by the jagged array?

A jagged array in Java is a two-dimensional (2D) array with variable column sizes. Unlike a normal
2D array where each row has the same number of columns, rows in a jagged array can have
different lengths.

78.What are the advantages and disadvantages of arrays in Java?

Arrays in Java are used to store multiple elements of the same type in a single structure. They have
both advantages and limitations.

✅ Advantages:

1. Fast Access (O(1)) – Elements can be accessed quickly using an index.

2. Memory Efficient – Uses contiguous memory allocation for better performance.

3. Easy Traversal – Can be iterated using loops.

4. Better Performance – Faster than ArrayList for fixed-size data.

❌ Disadvantages:
1. Fixed Size – Cannot grow dynamically after declaration.

2. Memory Wastage – If allocated too large, unused memory is wasted.

3. Insertion/Deletion Overhead (O(n)) – Requires shifting elements.

4. Homogeneous Data – Stores only one data type.

79. What is the difference between an object-oriented programming language and an object-
based programming language?

Object-Oriented Programming Language Object-Based Programming Language

Object-oriented programming language covers The scope of object-based programming is


larger concepts like inheritance, polymorphism, limited to the usage of objects and
abstraction, etc. encapsulation.

It supports all the built-in objects It doesn’t support all the built-in objects

Examples: Java, C#, etc. Examples: Java script, visual basics, etc.

80.What is an interface in Java?

An interface in Java is a blueprint of a class that contains only abstract methods (before Java 8) and
static or default methods (from Java 8 onward). It is used for achieving abstraction and multiple
inheritance in Java.

Example:

interface Animal {

void makeSound(); // Abstract method (No body)

class Dog implements Animal {


public void makeSound() { // Must override the method

System.out.println("Dog barks");

public class Main {

public static void main(String[] args) {

Animal obj = new Dog();

obj.makeSound(); // Output: Dog barks

81.Can a class be private in Java?

A top-level class cannot be private in Java because it must be accessible by the JVM. However, a
nested (inner) class can be private.

82. Give some features of the Interface.

• The interface can help to achieve total abstraction.

• Allows us to use multiple inheritances in Java.

• Any class can implement multiple interfaces even when one class can extend only one class.

• It is also used to achieve loose coupling.

83.What are the differences between abstract class and interface?

Abstract Class Interface Class

Both abstract and non-abstract methods may be


The interface contains only abstract methods.
found in an abstract class.

The interface class does not support Final


Abstract Class supports Final methods.
methods.
Abstract Class Interface Class

Multiple inheritance is not supported by the Multiple inheritances is supported by Interface


Abstract class. Class.

Abstract Keyword is used to declare Abstract Interface Keyword is used to declare the
class. interface class.

extend keyword is used to extend an Abstract implements keyword is used to implement the
Class. interface.

Abstract Class has members like protected,


All class members are public by default.
private, etc.

84. Difference between an Error and an Exception.

Errors Exceptions

Recover from exceptions by either using a try-


Recovering from Errors is not possible.
catch block or throwing exceptions back to the
caller.

It includes both checked as well as unchecked


Errors are all unchecked types in Java.
types that occur.

Errors are mostly caused by the environment in The program is mostly responsible for causing
which the program is running. exceptions.

Errors can occur at compile time as well as run All exceptions occur at runtime but checked
time. Compile Time: Syntax Error, Run Time: exceptions are known to the compiler while
Logical Error. unchecked are not.

They are defined in java.lang.Error package. They are defined in java.lang.Exception package
Errors Exceptions

Examples: Checked Exceptions: SQLException,


Examples: java.lang.StackOverflowError, IOException Unchecked Exceptions:
java.lang.OutOfMemoryError ArrayIndexOutOfBoundException,
NullPointerException, ArithmeticException.

85.What is Exception Handling in Java?

Exception handling in Java is a mechanism to handle runtime errors and ensure the program does not
crash unexpectedly. It is done using try, catch, finally, throw, and throws keywords.

86.What is the difference between Checked and Unchecked Exceptions?

• Checked Exceptions → Checked at compile time (e.g., IOException, SQLException).

• Unchecked Exceptions → Occur at runtime and are subclasses of RuntimeException (e.g.,


NullPointerException, ArithmeticException).

87.What is the difference between throw and throws?

• throw → Used inside a method to explicitly throw an exception.

• throws → Declares exceptions that a method might throw but does not handle them itself.

Example:

void divide(int a, int b) throws ArithmeticException {

if (b == 0) {

throw new ArithmeticException("Cannot divide by zero");

88.Can we have multiple catch blocks for a single try block?

Yes, multiple catch blocks can be used to handle different exception types.

Example:

try {
int result = 10 / 0;

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

} catch (Exception e) {

System.out.println("Some other exception occurred");

89.What happens if an exception is not caught?

If an exception is not caught, it propagates through the call stack. If no method handles it, the JVM
terminates the program and prints the exception stack trace.

90.What is finally block, and when is it executed?

The finally block is always executed after try and catch, regardless of whether an exception occurs. It is
used for cleanup tasks like closing files or releasing resources.

Example:

try {

System.out.println(10 / 0);

} catch (ArithmeticException e) {

System.out.println("Exception caught");

} finally {

System.out.println("Finally block executed");

91.Can we write only a try block without catch or finally?

No, a try block must be followed by either a catch or a finally block.

92.Can a finally block contain a return statement?

Yes, but using return in finally is not recommended because it overrides any previous return statement
in try or catch.

Example:
public int testMethod() {

try {

return 10;

} finally {

return 20; // This will override the return from try

Output → 20

93.Can a constructor throw an exception?

Yes, a constructor can throw an exception using the throws keyword.

Example:

class Test {

Test() throws Exception {

throw new Exception("Constructor Exception");

94.Can we handle multiple exceptions in a single catch block?

Yes, Java 7 introduced multi-catch, allowing multiple exceptions to be handled in a single catch block
using |.

Example:

try {

int num = Integer.parseInt("abc"); // NumberFormatException

} catch (NumberFormatException | NullPointerException e) {

System.out.println("Exception caught: " + e);

95.What is the difference between final, finally, and finalize()?


• final → Used for constants, methods (prevents overriding), and classes (prevents inheritance).

• finally → A block that always executes, used for cleanup.

• finalize() → A method called by the garbage collector before an object is destroyed.

96.Can we throw an exception manually in Java?

Yes, we can manually throw an exception using the throw keyword.

Example:

throw new IllegalArgumentException("Invalid input");

97.Can a catch block have multiple exceptions of different types?

No, a single catch block can only catch one exception type at a time, unless using multi-catch (|).

98. What happens if an exception occurs in a catch block?

If an exception occurs inside a catch block, it will not be handled by the same catch block and will
propagate up the call stack. To avoid this, use nested try-catch inside the catch block.

Example:

try {

int result = 10 / 0;

} catch (ArithmeticException e) {

try {

int[] arr = new int[5];

System.out.println(arr[10]); // New exception inside catch block

} catch (ArrayIndexOutOfBoundsException ex) {

System.out.println("Exception inside catch block: " + ex);

99. Can we have multiple finally blocks in Java?

No, only one finally block is allowed per try block. However, multiple try-catch-finally blocks can be
nested.
Example:

try {

System.out.println(10 / 2);

} finally {

System.out.println("Finally block executed");

100. Can we catch an exception that is not thrown?

No, Java does not allow catching an exception that is never thrown in the try block. This will result in a
compilation error.

Example:

try {

System.out.println("No exception here");

} catch (IOException e) { // Compilation error (IOException is never thrown)

System.out.println(e);

101. Can we inherit an exception class in Java?

Yes, custom exceptions can be created by extending Exception (checked exception) or


RuntimeException (unchecked exception).

Example:

class MyException extends Exception {

MyException(String message) {

super(message);

102. What is exception propagation in Java?


Exception propagation occurs when an exception is not caught in the current method and is passed to
the calling method. This continues until it is caught or reaches the JVM, which then terminates the
program.

Example:

void method1() {

method2(); // Exception propagates to method1

void method2() {

int result = 10 / 0; // Exception occurs here

103. Can we use try without catch or finally?

No, a try block must be followed by either a catch or a finally block.

104. What is the difference between Exception and Error in Java?

• Exception → Can be handled in code using try-catch (e.g., IOException, NullPointerException).

• Error → Represents serious issues that cannot be recovered (e.g., OutOfMemoryError,


StackOverflowError).

105. Can we rethrow an exception in Java?

Yes, an exception can be caught and then rethrown using the throw keyword.

Example:

try {

throw new NullPointerException("Exception occurred");

} catch (NullPointerException e) {

System.out.println("Caught exception: " + e);

throw e; // Rethrowing exception

}
106. Final vs Finally vs Finalize in Java

Feature final finally finalize()

Type Keyword (Modifier) Block Method

Ensures cleanup after Used by Garbage Collector before


Purpose Restricts modification
try-catch object destruction

Used with variables, Used in exception Used for resource cleanup before
Usage
methods, and classes handling GC

Can be final methods cannot be Not related to Can be overridden from Object
Overridden? overridden overriding class

Execution
At compile-time At runtime Before garbage collection
Timing

107. What is a thread in Java?

A thread is a lightweight subprocess that allows multiple tasks to run concurrently within a program.
Java provides built-in support for multithreading, which enables better CPU utilization and
responsiveness.

108. How can we create a thread in Java?

In Java, a thread can be created in two ways:

1. By extending the Thread class

class MyThread extends Thread {

public void run() {

System.out.println("Thread is running...");

public static void main(String[] args) {

MyThread t1 = new MyThread();

t1.start(); // Starts the thread


}

2. By implementing the Runnable interface (Preferred method)

class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread is running...");

public static void main(String[] args) {

Thread t1 = new Thread(new MyRunnable());

t1.start(); // Starts the thread

✔ Using Runnable is preferred because it allows extending other classes.

109. What is the difference between start() and run() in threads?

• start() → Creates a new thread and calls the run() method.

• run() → Runs like a normal method in the main thread (no new thread is created).

Example:

class Test extends Thread {

public void run() {

System.out.println("Thread running...");

}
public class Main {

public static void main(String[] args) {

Test t = new Test();

t.run(); // Runs in the main thread (wrong way)

t.start(); // Runs in a new thread (correct way)

110. What are the different states of a thread in Java?

A thread in Java has five states:

1. New → Created but not started (Thread t = new Thread();).

2. Runnable → Ready to run but waiting for CPU.

3. Blocked → Waiting for a resource (e.g., waiting for lock).

4. Waiting/Timed Waiting → Waiting indefinitely (wait()) or for a fixed time (sleep()).

5. Terminated → Execution is complete (run() method exits).

111. What is the difference between a process and a thread?

Feature Process Thread

A lightweight subprocess within a


Definition A program in execution
program

Memory Usage Takes more memory Takes less memory

Communication Uses Inter-Process Communication (IPC) Shares memory within the process

Context
Slower Faster
Switching

Example Multiple tabs in Chrome


Running chrome.exe and notepad.exe
Feature Process Thread

separately

112. What is the purpose of the sleep() method in Java?

The sleep() method is used to pause a thread for a specific time without terminating it.

Example:

class Test extends Thread {

public void run() {

for (int i = 1; i <= 5; i++) {

try {

Thread.sleep(1000); // Pauses for 1 second

} catch (InterruptedException e) {

System.out.println(e);

System.out.println(i);

✔ Used for delays, animations, or polling mechanisms.

113. What is thread priority in Java?

Java allows setting priority levels for threads using:

• MIN_PRIORITY (1)

• NORM_PRIORITY (5, default)

• MAX_PRIORITY (10)
Example:

Thread t1 = new Thread();

t1.setPriority(Thread.MAX_PRIORITY);

✔ Higher priority increases chances of getting CPU time but does not guarantee execution order.

114. What is join() in Java threads?

The join() method makes the main thread wait until the called thread finishes execution.

Example:

class Test extends Thread {

public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(i);

public static void main(String[] args) {

Test t = new Test();

t.start();

try {

t.join(); // Main thread waits for t to finish

} catch (InterruptedException e) {

System.out.println(e);

System.out.println("Main thread resumes");

}
}

115. What is a daemon thread in Java?

A daemon thread is a background thread that runs continuously and automatically stops when all user
threads finish.

Example:

class MyThread extends Thread {

public void run() {

System.out.println("Daemon thread running...");

public static void main(String[] args) {

MyThread t = new MyThread();

t.setDaemon(true); // Setting thread as daemon

t.start();

✔ Used for garbage collection, monitoring, logging, etc.

116. What is thread synchronization in Java?

Thread synchronization ensures that only one thread accesses a critical section at a time, preventing
race conditions.

Example:

class Counter {

private int count = 0;


public synchronized void increment() { // Synchronized method

count++;

✔ synchronized ensures thread safety when accessing shared resources.

117. What is a deadlock in Java threads?

A deadlock occurs when two or more threads are waiting for each other to release a resource,
resulting in infinite waiting.

Example:

class Test {

static final Object lock1 = new Object();

static final Object lock2 = new Object();

public static void main(String[] args) {

Thread t1 = new Thread(() -> {

synchronized (lock1) {

synchronized (lock2) { // Nested lock (Possible deadlock)

System.out.println("Thread 1 running");

});

Thread t2 = new Thread(() -> {

synchronized (lock2) {

synchronized (lock1) { // Nested lock (Possible deadlock)


System.out.println("Thread 2 running");

});

t1.start();

t2.start();

✔ Avoid using nested locks, and use tryLock() from ReentrantLock to prevent deadlocks.

118. What is volatile in Java threads?

The volatile keyword ensures visibility of changes to a variable across multiple threads.

Example:

class Test {

private volatile boolean running = true;

public void stop() {

running = false; // Ensures visibility across threads

✔ Prevents thread caching issues by forcing updates to the main memory.

119. What is the difference between synchronized and Lock in Java?

Feature synchronized Lock (ReentrantLock)


Feature synchronized Lock (ReentrantLock)

Type Keyword Class

Flexibility Less flexible More flexible

Try-Lock Feature No Yes (tryLock())

Fairness Setting No Yes (new ReentrantLock(true))

Example using Lock:

Lock lock = new ReentrantLock();

lock.lock();

try {

// Critical section

} finally {

lock.unlock();

✔ Lock provides better control over synchronization.

You might also like