What is java
Java is a high-level, object-oriented, and platform-independent programming language used
to develop various types of applications such as web applications, desktop applications,
mobile apps.
High level--->easy for human to read & write(Simply human understanding language like
English)
Object Oriented---->it is a programming language that organize code into objects and classes
Objects represents real world entities such as car,student,pen.
Platform independent---->write ones and run anywhere
(write java program on window same program can run linux or mac,os without change the
code)
Java's interpreted feature means that Java code is not directly converted into machine code
by a compiler. Instead, first, it compiled into bytecode, then executed by the JVM through
an interpreter. It allows Java to be platform-independent, meaning the same bytecode can
run on any system with a JVM.
Why java platform independent
First java compiled into byte code this byte code can run any platform that has the java
virtual machine(JVM)
Java Program Example
Create a file named [Link]:
Step1: Compile the Program
On any OS (Windows/Linux/Mac), run:
javac [Link]
This will generate:
[Link] ← Bytecode file
Step 2: Run the Bytecode
Now execute:
java Hello
How It Works on Any Platform
Because JVM converts the same bytecode into machine code specific to the running OS.
Memory Management in Java
Memory Management in Java is handled by the JVM (Java Virtual Machine).
It ensures efficient allocation and automatic removal of unused objects with the help of
Garbage Collection
When a Java program runs, memory is divided into two main parts:
✅ 1️ Heap Memory
Stores objects and instance variables
Managed automatically by Garbage Collector
✅ 2️ Stack Memory
Stores method calls, local variables, references
Memory is freed as soon as method ends
JVM,JRE,JDK
Jvm:
JVM (Java Virtual Machine) that provides a runtime environment in which Java bytecode can
be executed. It is called a virtual machine because it doesn't physically exist.
(It converts bytecode into machine code based on the OS)
The JVM performs the following main tasks:
Executes Java programs
Makes Java platform independent
Provides memory management and Garbage Collection
JVM is platform dependent (different for Windows/Linux/Mac)
Classloader: Classloader in Java is a subsystem of the Java Runtime Environment (JRE) that
dynamically loads Java classes into the Java Virtual Machine.
JRE
Java Runtime Environment is a set of software tools that are used for developing Java
applications. It is used to provide the runtime environment. It contains a set of libraries +
other files that the JVM uses at runtime.
JRE is the environment required to run Java applications.
It includes:
✔ JVM
✔ Set of libraries
✔ Runtime components
JDK
JDK is a software development kit required to develop and compile Java applications.
It includes everything needed for Java development
✔ JVM (Java Virtual Machine)
✔ JRE (Java Runtime Environment)
✔ Development tools like:
javac → Java compiler
Debugger
Java documentation tools
Packaging and monitoring tools
Short Interview Answer
JDK is a complete package that includes JRE, JVM, and development tools used to write,
compile, and debug Java programs.
Java Hello World Program
✅ Explanation of Java Program Structure
1️ class
The class keyword is used to declare a class in Java.
A class is a blueprint for creating objects.
2️ public
public is an access modifier.
It makes the class or method accessible from anywhere in the program.
3️ static
static is a keyword that allows a method or variable to belong to the class rather
than objects.
We can access static members without creating an object, memory is
allocated once when class is loading
Saves Memory: Instead of each object having its own copy of a
variable, static variables are shared across all objects of the class. This
saves memory because only one copy exists.
The main() method is static so JVM can call it without creating an object, saving
memory.
4️ void
void is the return type of a method.
It means the method does not return any value.
5️ main() method
It is the starting point of a Java program.
JVM looks for the main() method to begin program execution.
6️ String[] args / String args[]
Used to receive command-line arguments.
String[] args
✅ JVM stores each input as a String
✅ args is an array, so you can pass multiple values
Command line arguments allow users to pass values to the main() method when running a
program from the command line. These values are stored in the String[] args array.
7️ [Link]()
Used to print output on the console.
Why is the main() method public in Java?
The main() method is the entry point of a Java [Link] JVM must be able to access and
execute it from outside the [Link] main() is not public, JVM cannot access it, and the
program will not run.
✅ Interview One-Liner Answer
The main() method is public because JVM needs to access it from outside the class. If it were
private, protected, or default, the JVM wouldn’t be able to execute it and the program
would fail to start.
✅ Why is the main() method static in Java?
The main() method is the entry point of a Java [Link] must be called by the JVM before
any object is created. To call a method inside a class, normally we need an object
But when program execution begins:
No objects of the class exist
JVM needs a way to start execution without creating an object
✅ So the main() method is declared static
Because static methods can be called directly using class name
The main() method is static so the JVM can call it directly without creating an object,
ensuring the program starts properly and saving memory.
Java Variables
1️ Local Variable
A variable declared inside the body of the method is called local variable
2) Instance Variable
A variable declared inside the class but outside the body of the method
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
Data Types in Java
1. Primitive Data Types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-Primitive Data Types: The non-primitive data types include Classes, Interfaces,
String, and Arrays.
Typecasting in Java
Typecasting in Java is the process of converting one data type into another.
Java allows you to convert both primitive types and objects (class types).
Two types
o Widening Type Casting------lower to larger
o Narrowing Type Casting--------larger to lower
Widening Type Casting
Converts from smaller to larger data type, Done automatically
by the compiler
byte → short → int → long → float → double
Explicit Typecasting (Narrowing Conversion)
Converts from larger to smaller data type, Done by the
programmer
Syntax-------------- datatype variable = (datatype) value;
Wrapper classes
Wrapper classes used to convert primitive datatype to object.
many Java frameworks and collections, such as ArrayList or HashMap, are designed to
work with objects and cannot directly store primitive types.
wrapper class:
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
char -> Character
boolean -> Boolean
Autoboxing and Unboxing:
Java provides automatic conversion between primitive types and their corresponding
wrapper classes:
Autoboxing: Automatic conversion of a primitive type to its
corresponding wrapper class object (e.g., int to Integer).
Unboxing: Automatic conversion of a wrapper class object to its
corresponding primitive type (e.g., Integer to int).
OOPs Concepts in Java
What is oops?
OOPS (Object-Oriented Programming System) is a programming approach that organizes
software into objects, which represent real-world entities.
Each object contains data (attributes) and behavior (methods) that operate on the data.
OOPS improves software modularity, reusability, scalability, and security.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Class
A class is a blueprint/template for creating objects.
It contains properties (variables) and behaviors (methods) of an object.
Real-time exp:
Think of a Car blueprint. It describes wheels, engine, and features but is not a car itself.
From this blueprint, we can create multiple cars.
This class does not occupy memory until we create an object.
Object
An object is an instance of a class (created from a class).
It represents a real-world entity. Object = Data (properties) + Actions (methods)
Real-time use:
From the Car blueprint (class), you create a BMW car object or Tesla car object.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Simple Definition for Interviews
An object is a real-time entity created from a class that has state (variables) and behavior
(methods).
Created using new keyword Car a=new Car();
Methods in Java
Constructor
A constructor is a special method used to initialize objects in Java. It is executed
automatically when an object is created.
Constructor name must be the same as its class [Link] have not return type
At the time of calling constructor, memory for the object is allocated in the memory.
If there is no constructor available in the class. In such case, Java compiler provides a default
constructor by default.
A constructor initializes values to instance variables of a class when an object is created.
Inheritance in Java
Inheritance is when one class (child/subclass) derives properties and behaviors (variables +
methods) from another class (parent/superclass).
Use of inheritance is code Reusability,method overriding
Real time example: sun derive the properties of father
Single Inheritance
Multilevel Inheritance
Grandfather → passes assets → Father → passes assets → Son
Hierarchical Inheritance
One Parent → Multiple Children
Hybrid Inheritance
Combination of two or more inheritance types
Multiple Inheritance
One child class inherits from multiple parent classes.
Jvm confuse which method I call show method in father or method in
mother that’s why java not support multiple inheritance
But… Java supports Multiple Inheritance using Interfaces
Interface topic lo chuddam just chill
--------------------------------------------------------------------------------------------------
Encapsulation
Encapsulation means wrapping data (variables) and methods (functions) together into a
single unit (class)
Encapsulation is the process of wrapping data (variables) and methods (functions) into a
single unit (class) and protecting the data using access modifiers.
📌 Simply → Data hiding + Data protection
Main purpose is protect the data it is achived by Making variables private Providing public
getters and setters to access them safely
Protect the data and control how it is accessed or modified.
How Encapsulation Works
✅ Use private access modifiers to hide data
✅ Use public getters and setters to access or update data safely
🔹 Real-Time Example (Bank Account)
Imagine your bank account balance.
The balance should not be directly modified by anyone.
It should only change when you deposit or withdraw through proper methods.
ATM Machine → You can’t directly access bank’s database. You can only
deposit/withdraw through the provided interface.
Car → You can’t directly control fuel injection or engine internals; you only use
accelerator/brake.
Mobile Phone → You can’t directly access the hardware; you interact via apps and
settings.
Polymorphism
Polymorphism = Poly (many) + Morph (forms) → One thing, many forms.
It means the same method can perform different behaviors depending on the context
(object or parameters).
Same method, different behaviors based on object or situation.
Why Do We Use Polymorphism?
Flexibility------same method work diffrently with diffrenrt objects
Reusability → Same method name, different behaviors.
Compile-time Polymorphism (Method Overloading)
Definition: Same method name, but different parameter list (number or type of
arguments).
at the time of complilation the compiler decide which method I
call based on parameters so it is called compile time
ploymorphism
Real-Time Examples of Polymorphism
1)Whatup send() method method used for text,photo,video
2)draw() in a Drawing Application
Method → draw()
If object is Circle → draw circle
If object is Rectangle → draw rectangle
If object is Square → draw square
Same method, different shapes
Runtime Polymorphism (Method Overriding)
Definition: Child class provides its own implementation of a method
already defined in parent class.
A method of the child class overrides a method of the parent class,
and the method call is decided at runtime (execution time).
✔ Uses Method Overriding
✔ Achieved through inheritance
✔ JVM decides which method to run based on object type (not reference type)
super Keyword in Java
The super keyword in Java is used to refer to the parent (super) class
members — variables, methods, or constructors.
--
final keyword in Java
When a variable is declared as final, it is known as a final variable. Its value
cannot be changed once initialized. It behaves like a constant.
A method declared as final is known as a final method. Subclasses cannot
override the final method.
A method declared as final is known as a final method. Subclasses cannot
override the final method.
Abstraction
Abstraction means showing only essential information to the user and hiding the internal
implementation details.
Just like:
When you use a mobile phone, you press buttons but don't know the internal
circuits.
While sending an SMS, we just type the message and click send. The internal
processing of message delivery is hidden from us.
Abstraction helps us focus on what an object does rather than how it does it.
java achieves abstraction mainly by:
1. Abstract Classes
2. Interfaces
Abstract Class in Java
An abstract class is a partially implemented class that cannot be instantiated(you can't create
an object from it). It acts as a blueprint for its subclasses to provide implementation for
abstract methods.
Must be declared with the abstract keyword
Can have abstract and non-abstract methods
Cannot create an object of abstract class
Can have constructors, static methods
Abstraction Explained with Real-Time Example
🔹 Real-Time Example: ATM Machine
When we use an ATM:
We insert card
We enter PIN
We withdraw money
We do not know:
How bank validates PIN internally
How account balance is fetched
How cash is dispensed from internal mechanisms
How the transaction is updated in banking servers
👉 These internal operations are hidden from the user.
✅ We only interact with the necessary functions, not the hidden processing.
This is abstraction — hiding implementation, showing only functionality.
Here:
User just calls withdrawMoney().
But inside, ATM performs many hidden tasks like:
✅ Authentication
✅ Account verification
✅ Transaction processing
✅ Cash dispensing
But the user only sees the final output.
Why 100% Abstraction is NOT achieved with Abstract Class in Java?
Because an abstract class can contain:
✔ Abstract methods (without implementation)
✔ Concrete (normal) methods with implementation
✔ Variables (including non-final fields)
✔ Constructors
✔ Static methods
Since some implementation can exist inside an abstract class, it does not provide 100%
abstraction.
✅ Only interfaces guarantee 100% abstraction (before Java 8) because they contain only
abstract methods and no implementation details.
Simple Interview Answer
100% abstraction is not possible in abstract classes because they can contain fully
implemented methods, constructors, and variables. Since some details are visible, abstraction
is only partial (0–100%).
Q: Then why do we use abstract classes?
✔ When we want to share common code between subclasses
✔ When partial abstraction is enough
✔ When we need constructors, state (variables), and non-abstract methods
Interface in Java
An interface is like a blueprint (contract) of a class. It can only have method declarations (no
implementation) and constants (public static final variables by default). A class implements
an interface and gives the actual implementation of those methods.
✅ Methods — public & abstract by default
✅ Variables — public static final (constants) by default
✅ Supports 100% abstraction (before Java 8)
“What to do” is written in the interface, and “How to do” is written in the implementing
classes.
🔹 Why Use Interfaces?
To achieve 100% abstraction (hide implementation, show only behavior).
To achieve multiple inheritance (a class can implement many interfaces).
Real-Time Example
Think of an Electrical Socket (interface)
It defines 3 pins that must be there (contract).
Any device like Fan, TV, Charger can plug in if they implement those 3 pins.
So:
Socket = interface
Fan, TV, Charger = classes implementing interface
They all work differently, but you can use them interchangeably with the same socket → This
is the power of interfaces.
Multiple Interface in Java
If a class inherits from two parent classes having the same method name, Java gets confused:
Which parent's method should the child use?
Parent A’s? or Parent B’s?
Interfaces Solve This Problem
If two interfaces have the same method, child class must override and provide its own
implementation — so no confusion ✅
Diffrence between extend and implements
String
string is an object that represents a sequence of characters. The [Link] class is used
to create a string object. Immutable: once created, its value cannot change.
There are two ways to create String object:
1. By string literal
2. By new keyword
3.
String Literal
1. Java String literal is created by using double quotes String s="welcome";
String s1 = "Gopi";
String s2 = "Gopi";
The first time "Gopi" appears, Java puts it in a special memory area called the String
Constant Pool (a part of the heap).
When the second "Gopi" appears, Java doesn’t create a new object — it just reuses
the existing one from the pool.
So, s1 and s2 point to the same string object in memory.
By new keyword
String s3 = new String("Gopi");
Then Java forces creation of a new object, even though "Gopi" already exists in the pool.
What happens step by step:
1. "Gopi" — this literal goes into the String Constant Pool (SCP).
o If it’s already there, JVM will reuse it.
o If not, it will add it to the pool.
2. The new String("Gopi") part tells Java to create a new string object in the normal
heap memory — outside the pool.
3. The variable s will point to this new heap object, not the one in the pool.
String is immutable so there are two classes create mutable stringsssssss
StringBuffer
StringBuffer is a mutable sequence of characters in [Link].
Synchronized — thread-safe for concurrent use by multiple threads.
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link]([Link]()); // "Hello World"
StringBuilder
StringBuilder is like StringBuffer (mutable sequence of characters) but not synchronized.
StringBuilder sb = new StringBuilder();
[Link]("Hi").append(" there");
[Link]([Link]()); // "Hi there"
Why StringBuffer is slow compared to StringBuilder?
Because all the methods are synchronized meaning only one thread can access the object at a
time → increases safety, decreases speed.
StringBuilder has no synchronization, so it is faster.
Java String comparision
1) By Using equals() Method
It compares the string by actual content of the string not the reference address
[Link](s3) is equal bcz the content is same Sachin,Sachin
2) By Using == Operator
== operator compares references(address) rather than value
S1==s2 true bcz they are point to same reference but s1==s3 false bcz s3 string
created using new it created new object so it reference to different address
3) String compare by compareTo() Method
Strings are compared Lexicographically means dictionary order — or alphabetical order.
Suppose s1 and s2 are two String objects. If:
[Link](str2)
o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.
What is the String Constant Pool (SCP)?
It’s a special memory area inside the heap where Java stores unique string literals to save
memory.
If the same literal already exists, it reuses the existing object.
How are Strings stored in memory?
Strings are stored in heap memory, and literals are stored in the String Constant Pool (SCP),
which is part of the heap.
Can we use == to compare String contents?
No, == compares references (addresses).
Use .equals() to compare the actual content.
Exception Handling in Java
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Types of Java Exceptions
1. Checked Exception
2. Unchecked Exception
3. Error
1. Checked Exception
Checked exceptions are the exceptions that are checked at compile-time
Checked exceptions are those errors or problems that the compiler knows
might happen, so it forces you to handle them before you run the program.
In short:
“Checked exceptions are those that the compiler checks — you must handle
them before running the program.”
Common examples:
IOException-----thrown when an input/output operation fails, such as
when reading from or writing to a file.
SQLException-------It is thrown when an error occurs while accessing a
database.
FileNotFoundException
ClassNotFoundException------ClassNotFoundException happens when
your Java program tries to load a class that doesn’t exist
2. Unchecked Exceptions (Runtime Exceptions)
Unchecked exceptions, also known as runtime exceptions, are not checked at
compile-time it occus at runtime. These exceptions usually occur due to
programming errors, such as logic errors or incorrect assumptions in the code.
✅ Why Are They Called “Unchecked”?
Because the compiler does not check whether you have handled them with try-catch
or throws. You can choose to handle them, but it’s optional.
try-catch block in Java
The try-catch block is used to handle exceptions — that is, unexpected errors that occur
during program execution.
try block:
Contains the code that might throw an exception.
If an exception occurs, control immediately jumps to the matching catch block.
catch block:
Used to handle (catch) the specific type of exception.
You can have multiple catch blocks to handle different exception types separately.
try-catch-finally
finally block is used to execute code whether an exception occurs or not
It’s mainly used for resource cleanup (like closing files, database, etc.)
throw Keyword
throw is used to manually (explicitly) throw an exception from your code.
a built-in exception (like ArithmeticException, NullPointerException, etc.)
or
your own custom exception.
Syntax------ throw new ExceptionType("error message");
throws Keyword
throws is used in the method declaration to tell the compiler that the method
might throw an exception.
It doesn’t throw the exception itself —
it only declares it (a warning to whoever calls the method: “Be ready to handle
this exception”).
Create custom exception in java
Difference between throw vs throws
Can we have multiple catch blocks?
Answer:
✅ Yes.
You can have multiple catch blocks to handle different types of exceptions.
Can we write a try block without catch?
Answer:
✅ Yes — but only if you use a finally block after it.
What happens if exception is not handled?
Answer:
If no try-catch is used, the program terminates abnormally and the JVM prints an
error message (stack trace).
Java Arrays
Java array is an object which contains elements of a similar data type
It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array
At the time of declaration of an array, you must specify the type of data with the
array name.
The elements of an array are stored in a contiguous memory location. all the
elements of an array are stored next to each other in memory
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Array inside array (Matrix)---- int[][] matrix = new int[3][3];
//declaration, instantiation and initialization of an array
int[] numbers = {10, 20, 30};
Creation (Memory Allocation)
arr = new int[5]; // creates array of size 5
For the arrays it self does not have any methods kani konni vunnai utility package
import chessukovali
What is the index range of an array?
Starts from 0 and ends at length - 1.
Can you change the size of an array after creation?
❌ No
Arrays have fixed size once created.
[Link]--------------- a number of elements present in an array.
The length() returns the number of characters stored in a string object
How to sort an array in Java?
import [Link];
[Link](arr); for accending order
[Link](arr, [Link]()); for decending order
Where is an Array stored in JVM memory?
An Array is an object in java. So, Array is stored in heap memory in Java Virtual
Machine
Can you declare an array without assigning the size of an array?
No, we cannot declare an array without assigning size. If we declare an array without
size, it will throw compile time error.
What is the default value of Array in Java?
If we don't specify the values by ourselves, then Java assigns default values in them
which are 0 for byte, short, int, and long, 0.0 for float and double, false for boolean,
and null for objects respectively.
Difference between Array and ArrayList?
Can we store different data types in an array?
No ❌ — All elements must be of the same data type.
Arrays meda mareeee akva questions vundavu vuntey array ki colletions meda
difference adugutharu antheyyy don’t think too much in case qn adigithai
adukkuthinandi