Java
Java
Java is a high-level, object-oriented programming language that is widely used for building applications across
different platforms—like web, mobile (Android), desktop, and enterprise systems.
1. Platform Independent
Java code is compiled into bytecode which runs on the Java Virtual Machine (JVM) . This allows Java
programs to run on any system with a JVM — “Write Once, Run Anywhere”.
2. Object - Oriented
Java focuses on objects and classes, which makes it modular, reusable, and easier to manage for large
projects.
3. Simple & Familiar
Java is easy to learn, especially if you know C or C++, but it removes complex features like pointers and
operator overloading.
4. Secure
Java has built-in security features like runtime checking, bytecode verification, and a security manager for
defining access rules.
5. Multithreaded
Java supports multithreading, meaning multiple parts of a program can run at the same time—useful for
games, animations, or server handling.
6. Rich API & Ecosystem
Java has a powerful standard library and a massive ecosystem (Spring, Hibernate, Maven, etc.) for all kinds
of applications.
• What it is: JVM is the engine that runs your Java programs.
• What it does: It takes the compiled Java .class files (which contain bytecode) and runs them.
• Why it’s useful: It allows Java to be platform-independent – the same Java code runs on Windows, Mac,
or Linux.
Example: Think of JVM like a car engine. You give it fuel (bytecode), and it makes the car run (your Java program
executes).
• What it is: JRE includes the JVM + libraries + files needed to run Java programs.
• What it does: It provides everything needed to run a Java application, but not to develop it.
• What's inside: JVM + core libraries (like [Link], [Link]) + other supporting files.
Example: If JVM is the engine, JRE is the whole car (engine + fuel system + wheels) that lets you drive (run Java
programs).
Example: JDK is like a car manufacturing unit where you build the car (develop software). Once built, the car
(JRE) can run anywhere.
---------------------------------------------------------------------------------------
A variable is like a container or box in your program that holds some data or value.
A cup that can hold different drinks. You give it a name, and you can fill it with tea, coffee, water, etc.
In Java, a variable is like that cup, and the "drink" is the value it stores!
🧩 Example:
✅ Quick Rules:
• A variable must start with a letter, no spaces, and can't be a Java keyword like int, class, etc.
• Java is case-sensitive: age and Age are two different variables.
• You must declare the data type when creating a variable.
--------------------------------------------------------------------------------------
[Link] are Data Types in Java?
In Java, data types tell the computer what kind of value you're storing in a variable.
Think of it like labels on boxes—one box says "Numbers", one says "Text", one says "True/False", and so on.
Java needs to know the type of value so it can store it properly and perform the right actions.
🥈 Non-Primitive Data Types : These are more complex types made from primitive types or defined by you.
🎯 Why Data Types Matter : Java is strict. You have to tell it exactly what kind of data you're working with.
🧪 Example:
---------------------------------------------------------------------------------------
A literal is just a fixed value that you write directly in your code.
Here, 21 is a literal — it’s the actual value you're storing in the variable age.
6. Null Literal
--------------------------------------------------------------------------------
Type Conversion in Java means changing a value from one data type to another.
It's like pouring water from a small cup into a big glass — or the other way around!
🔄 Two Types of Type Conversion:
Also called Widening Conversion Java automatically converts a smaller data type to a bigger one safely.
📌 Example:
Int num=10;
double d= num;// int→double(automatic)
[Link](d); //Output:10.0
Also called Type Casting You manually tell Java to convert a bigger type into a smaller one.
📌 Example:
double z = 9.99;
int w = (int) z; // Explicit
[Link](w); // 9
} }
🎯 Quick Recap:
🧪 Example Code:
Note:
• In Java, if you divide two integers, the result is also an integer. So 10 / 3 = 3 (not 3.33).
• To get a decimal result, use double:
double x = 10;
double y = 3;
[Link](x / y); // 3.333...
🧠 Quick Tip: You can also use arithmetic operators with variables, like: int total = marks1 + marks2;
---------------------------------------------------------------------------------------------------------------------------------------------
[Link] operators
In Java, relational operators are used to compare two values. These operators return a boolean result: either
true or false.
🧪 Example Code:
public class RelationalExample {
public static void main(String[] args) {
int a = 10, b = 20;
📌 Notes:
• You can use relational operators with primitive data types: int, float, char, double, etc.
• For objects (like String), use .equals() instead of == to compare contents.
Example:
String s1 = "hello";
String s2 = "hello";
[Link](s1 == s2); // true (because of string pool)
[Link]([Link](s2)); // true (safe way to compare)
Example:
int x = 5;
int y = 5;
[Link](x == y); // true → because 5 equals 5
== compares memory addresses (references) — whether both variables point to the same object.
String a = "hello";
String b = "hello";
[Link] Operators
In Java, logical operators are used to combine two or more boolean expressions or values and return a boolean result
(true or false). These are mostly used in conditions, such as if statements or loops.
🧪 Example Code:
public class LogicalOperators {
public static void main(String[] args) {
int a = 10, b = 20;
// Logical AND
[Link]((a < b) && (a > 5)); // true
// Logical OR
[Link]((a < b) || (a > 50)); // true
// Logical NOT
boolean condition = (a < b);
[Link](!condition); // false
}}
📌 When to Use:
1. AND (&&):
2. if (age > 18 && hasLicense) {
3. [Link]("You can drive.");
4. }
5. OR (||):
6. if (isWeekend || isHoliday) {
7. [Link]("You can relax!");
8. }
9. NOT (!):
10. if (!isLoggedIn) {
11. [Link]("Please log in.");
12. }
🚫 Short-circuiting Behavior:
A B A && B
true true true
true false false
false true false
false false false
🔸 OR (||) – Logical OR
A B A || B
true true true
true false true
false true true
false false false
-----------------------------------------------------------------------------------------------------------------------------------
In Java, the if, else if, and else statements are used to make decisions in code based on boolean conditions.
They allow your program to execute different blocks of code depending on the condition’s result.
✅ Syntax
if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition1 is false and condition2 is true
} else {
// Executes if all conditions are false
}
📌 Key Points
• You can have only one if and else block, but multiple else if blocks.
• Conditions are evaluated in order, and only the first matching block is executed.
• All conditions must return a boolean (true or false).
✅ Nested If Example
int age = 22;
String gender = "Female";
-----------------------------------------------------------------------------------------------------------------------------------
[Link] Operators
The ternary operator in Java is a shorthand for if-else statements. It’s used to evaluate a condition and return one
of two values depending on whether the condition is true or false.
📌 Notes:
• The ternary operator is not a replacement for all if-else statements — use it for simple conditions.
• You can nest ternary operators, but that may reduce readability:
int x = 30;
String res = (x > 50) ? "High" : (x > 20) ? "Medium" : "Low";
[Link](res); // Output: Medium
---------------------------------------------------------------------------------------------------------------------------------
[Link] Statement
In Java, the switch statement is used to select one of many code blocks to be executed based on the value of
a variable or expression. It’s an alternative to writing multiple if-else-if statements when comparing a single
variable to many constant values.
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}}}
📌 Key Points:
• The expression must be byte, short, int, char, enum, or String (from Java 7 onward).
• The break statement exits the switch block.
• If break is omitted, execution continues to the next case (called fall-through).
• The default case is optional but useful for handling unexpected values.
-----------------------------------------------------------------------------------------------------------------------------------
In Java, loops are used to execute a block of code repeatedly based on a condition. The while, do-while, and for
loops are the three main types.
🔁 1. while Loop
The while loop checks the condition first, then executes the loop body only if the condition is true.
✅ Syntax:
while (condition) {
// code block
}
🧪 Example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
⏳ Output:
1
2
3
4
5
🔁 2. do-while Loop
The do-while loop executes the loop body first, then checks the condition. So it executes at least once, even if the
condition is false.
✅ Syntax:
do {
// code block
} while (condition);
🧪 Example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
⏳ Output:
1
2
3
4
5
🔁 3. for Loop
The for loop is compact and often used when the number of iterations is known.
✅ Syntax:
for (initialization; condition; update) {
// code block
}
🧪 Example:
for (int i = 1; i <= 5; i++) {
[Link](i);
🔁 Comparison:
Feature while do-while for
Condition Check Before loop body After loop body Before loop body
Runs At Least Once? No Yes No
Best Use Case Unknown iterations At least 1 execution needed Known number of iterations
----------------------------------------------------------------------------------------------------------------------------------
🔹 Class in Java : A class is a user-defined data type that represents what an object is and what it can do.
A class contains:
A class is a blueprint or template from which objects are created. It can contain:
• Fields (variables)
• Methods
• Constructors
• Blocks
• Nested classes
Example
// Class definition
public class Car {
// Fields (attributes)
String color;
int speed;
// Method
void drive() {
[Link]("The car is driving at " + speed + " km/h.");
}}
🔹 Object in Java
An object is an instance of a class. It represents a specific entity that has state (attributes) and behavior (methods).
✅ Example:
-----------------------------------------------------------------------------------------------------------------------------------
24. Methods
Methods in Java is a block of code that performs a specific task . It helps in code reuse, modularity, and
organization.
You can think of it like a function (same as in other programming languages) — it executes a task when called.
🔹 Syntax of a Method
🔹 Example:
return a + b; }
void greet() {
Type Description
Instance Belongs to an object. Needs object to call.
Method
Static Method Belongs to the class. Called using class
name.
Constructor Special method used to create objects.
✅ 1. Static Method
✅ 2. Non-static Method
• No input is required.
[Link]("Noparametershere!");
}
publicstaticvoidmain(String[]args){
Exampleobj=newExample();
[Link](); // Output: No parameters here!
}}
---------------------------------------------------------------------------------------------------------------------------------
[Link] overloading
Method Overloading means having multiple methods with the same name in a class, but with different
parameters (type, number, or order).
To overload a method, the methods must differ in at least one of the following:
1. Number of parameters
2. Type of parameters
3. Order of parameters (if types are different)
// Area of square
int area(int side) {
return side * side;
}
// Area of rectangle
int area(int length, int breadth) {
return length * breadth;
}
// Area of circle
double area(double radius) {
return 3.14 * radius * radius;
}
🔴 Not Allowed:
📌 Simple Definition: Heap is a memory area in JVM where all Java objects and class instances are stored
during program execution.
🔍 How it works:
📌 Key Characteristics:
Feature Description
Dynamic Objects are created at runtime.
Garbage JVM automatically deletes unused objects (using Garbage
Collected Collector).
Shared Memory All threads share the heap memory.
Stores Objects, class fields, and arrays.
🔄 Stack vs Heap
Stack Heap
Stores method calls and local variables Stores all Java objects
Faster Slower (because of GC)
Each thread has its own stack Heap is shared by all threads
Memory is automatically freed when method Objects live until garbage
ends collected
📌 Example:
-----------------------------------------------------------------------------------------------------------------------------------
27-30. Array
Sure! Let's explore arrays in Java completely — from simple (1D) to multidimensional, jagged, and 3D arrays —
with simple explanations and examples for each.
Definition: A 1D array is a collection of elements (of the same data type) stored in a single row.
🔹 Example:
🔹 Example :
} [Link]();
} } }
Definition: A jagged array is a 2D array where each row can have different number of columns.
🔴 4. 3D Array in Java
int count = 1;
cube[i][j][k] = count++;
[Link]();
}
}}}
--------------------------------------------------------------------------------------
[Link] of array
1. Fixed Size:
a. Once declared, array size cannot be changed.
2. Same Data Type Only:
a. Can store only one type (e.g., all int or all String) .
3. No Built-in Methods:
a. No direct methods like add(), remove() (unlike ArrayList).
4. Wasted Memory:
a. If array size is large but not fully used.
5. Insertion/Deletion is Hard:
a. Requires shifting elements manually.
-------------------------------------------------------------------------------------
The Enhanced For Loop is used to iterate over arrays or collections (like ArrayList) in a simpler and cleaner
way.
Example 1: Loop through an Array
Output:
10
20
30
40
import [Link].*;
⚠️ Notes:
• You can’t modify elements (like deleting) while using enhanced for.
• Use a regular for loop or Iterator if you need to access index or remove elements.
--------------------------------------------------------------------------------------
34 & 35 .Strings
In Java, a String is a sequence of characters (letters, numbers, symbols) enclosed in double quotes.
It is one of the most commonly used non-primitive (reference) data types.
✅ Example:
Feature Explanation
Immutable Once a string is created, it cannot be changed. Any change creates a new object.
Stored in String Java stores strings in a special memory area called the String pool for better memory
Pool management.
Belongs to You don't need to import anything to use String.
[Link]
Example:
String name = "navin";
name = name + " reddy";
[Link]("hello " + name);
Output:
hello navin reddy
But this does not mean that String is mutable.
Strings in Java are immutable, which means once a String object is created, its contents
cannot be changed.
🧠 So, you didn’t modify the original string — you just created a new one and reassigned
it to the same variable.
🔹 1. StringBuffer
Example:
Example:
If you are modifying strings repeatedly (e.g., inside loops), using StringBuffer or StringBuilder is more
efficient than String.
--------------------------------------------------------------------------------------
Example:
class Student {
static String college = "ABC College"; // Static variable
String name;
Student(String name) {
[Link] = name;
}
void show() {
[Link](name + " studies at " + college);
}}
Output:
🔸 2. Static Method
Example:
class Calculator {
static int square(int x) {
return x * x;
}}
🔹 3. Static Block
Example:
class Demo {
static int x;
static {
x = 100;
[Link]("Static block executed");
}}
Output:
Encapsulation is one of the four main pillars of Object-Oriented Programming (OOP) in Java. It means wrapping
data (variables) and code (methods) together into a single unit — typically a class — and restricting direct access to
some of the object's components.
✅ Definition: Encapsulation is the technique of hiding internal data from outside access and allowing it to be
accessed only through getter and setter methods.
📦 Real-life Example: Think of a capsule (medicine) — the ingredients are hidden inside, and you access their
effect without knowing how they work.
🧪 Java Example:
public class Student {
private String name; // private = hidden from outside
private int age;
Getters and Setters are special methods used in Java to access (get) and modify (set) the private fields of a class. They
are a key part of encapsulation in object-oriented programming.
📌 Naming Conventions:
--------------------------------------------------------------------------------------
The this keyword in Java is a reference to the current object — the object whose method or constructor is being
called.
When method parameters have the same name as instance variables, this is used to refer to the current object's
variable.
You can use this() to call another constructor in the same class.
public Student() {
this("Unknown", 0); // calls the parameterized constructor
}
public Student(String name, int age) {
[Link] = name;
[Link] = age;
} }
3. Pass Current Object as Argument
Sometimes you pass the current object to another method or constructor using this.
🧠 Example Summary:
public class Person {
String name;
--------------------------------------------------------------------------------------
A constructor is a special method used to initialize objects in Java. It is called when an object of a class is created.
✅ Key Points:
🔸 Types of Constructors:
✅ 1. Default Constructor:
public class Student {
// Constructor
Student() {
[Link]("Default constructor called");
}
Student(String n) {
name = n;
}
// Copy constructor
Student(Student s) {
name = [Link];
}
🚫 Important Notes:
--------------------------------------------------------------------------------------
45. Naming Convention
Element Convention Example
Class PascalCase StudentDetails
Interface PascalCase EmployeeService
Method camelCase calculateMarks()
Variable camelCase totalMarks
Constant UPPER_CASE MAX_LIMIT
Package lowercase [Link]
--------------------------------------------------------------------------------------
🔹 Anonymous Object in Java : An anonymous object in Java is an object that is created without being
assigned to a reference variable.
✅ Example:
new Student().display();
In this example, an object of the Student class is created anonymously and immediately used to call the display()
method.
✅ Complete Example:
class Student {
void display() {
[Link]("Hello, I am an anonymous object!");
}}
🚫 Drawbacks:
✅ Comparison:
// Regular object
Student s = new Student();
[Link](); // Can use s again
// Anonymous object
new Student().display(); // Cannot use this object again
--------------------------------------------------------------------------------------
• Code reusability
• Improves maintainability
• Supports polymorphism and extensibility
🔹 Syntax:
class Parent {
// properties and methods
}
1. Single Inheritance
class Animal {
void sound() {
[Link]("Animal makes sound");
}}
2️ .Multilevel Inheritance
A class inherits from a class, which itself inherits from another class.
class Animal {
void sound() {
[Link]("Animal makes sound");
}}
Java does not support multiple inheritance with classes to avoid ambiguity (diamond problem),
but supports it via interfaces.
interface A {
void display();
}
interface B {
void show();
}
class C implements A, B {
public void display() {
[Link]("Display from A");
}
public void show() {
[Link]("Show from B");
}}
✅ Summary Table:
Type Description Example
Single One child, one parent class A → class B
Multilevel Inheritance in a chain A → B → C
Multiple (via interface) One class implements multiple interfaces class C implements A, B
--------------------------------------------------------------------------------------------------------------------------------------
In Java, this and super are special keywords used to refer to the current object and the parent class respectively.
They are often used in inheritance and constructor chaining.
🔹 this keyword
this refers to the current object (the instance of the current class).
✅ Common Uses of this:
void display() {
[Link]("ID: " + [Link] + ", Name: " + [Link]);
}}
📌 Example 2: Constructor chaining using this()
public class Student {
int id;
String name;
Student() {
this(101, "Default");
}
void display() {
[Link](id + " " + name);
}}
🔹 super keyword
------------------------------------------------------------------------------------------------------------------------------------------
[Link] Overrriding
Method Overriding means redefining a method in a subclass that is already defined in its superclass. It allows a
subclass to provide a specific implementation of a method that is already provided by its parent class.
🔁 Overriding vs Overloading
Feature Overriding Overloading
Class Relation Parent and child classes Same class (or subclass)
Parameters Same parameters Different number/type of parameters
Runtime/Compile Happens at runtime Happens at compile-time
✅ Real-World Example:
class Bank {
int getRateOfInterest() {
return 0;
}}
------------------------------------------------------------------------------------
[Link]
[Link] Modifiers
Access modifiers in Java control the visibility (or accessibility) of classes, methods, constructors, and variables.
public class A {
public int x = 10;
public void show() {
[Link]("Public method");
}}
class A {
private int x = 10;
private void show() {
[Link]("Private method");
}}
🔸 4. protected - Accessible within the same package and in subclasses (even outside the package)
class A {
protected void show() {
[Link]("Protected method");
}}
--------------------------------------------------------------------------------------
55 - Polymorphism
Polymorphism means "many forms". In Java, it allows one action (like calling a method) to behave differently based
on the object.
🔹 Types of Polymorphism
Type When It Happens Also Called
Compile-time At compile time Method Overloading
Runtime At runtime Method Overriding
Same method name with different parameters (number or type) in the same class.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}}
👉 Usage:
Calculator c = new Calculator();
[Link]([Link](2, 3)); // 5
[Link]([Link](2.5, 3.5)); // 6.0
[Link]([Link](1, 2, 3)); // 6
Same method in superclass and subclass, but the call is resolved at runtime.
class Animal {
void sound() {
[Link]("Animal sound");
}}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}}
👉 Usage:
Animal a1 = new Dog(); // Upcasting
Animal a2 = new Cat();
[Link](); // Dog barks
[Link](); // Cat meows
• Code reusability – Write generic code for parent class, works with all subclasses.
• Extensibility – Easily add new behavior via overriding.
• Flexibility – Decide behavior at runtime (e.g., in dynamic apps, GUIs, frameworks).
🔁 Summary:
Feature Overloading Overriding
Class Same class Different classes (inheritance)
Parameters Must differ Must be the same
Return type Can be different Should be same (or covariant)
Time Compile time Runtime
--------------------------------------------------------------------------------------
[Link] method dispatch
Dynamic Method Dispatch is the process of resolving a method call at runtime rather than at compile time. It is also
called runtime polymorphism.
🔹 Definition: Dynamic Method Dispatch allows Java to decide at runtime which version of an overridden
method to call, depending on the object type (not the reference type).
📌 Key Points:
🔸 Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}}
Even though a is an Animal reference, Java calls the overridden method of the actual object (Dog or Cat).
🔸 Real-World Example: Suppose you have a Payment class and subclasses like CreditCard, UPI, and Cash.
You can use dynamic dispatch to process all payments with one reference.
class Payment {
void pay() {
[Link]("Processing payment");
}}
👉 Using it:
public class Main {
public static void main(String[] args) {
Payment p;
p = new UPI();
[Link](); // Paid via UPI
p = new CreditCard();
[Link](); // Paid via Credit Card
}}
🔁 Summary:
Feature Description
Type Runtime Polymorphism
Requires Inheritance + Method Overriding
Uses Superclass reference, subclass object
Benefit Flexible, extensible code
------------------------------------------------------------------------------------
[Link] Keyword
The final keyword in Java is a non-access modifier used to restrict modification. It can be applied to variables,
methods, and classes.
📌 Example:
public class Example {
final int speedLimit = 60;
void show() {
// speedLimit = 100; Error: Cannot assign a value to final variable
[Link]("Speed Limit: " + speedLimit);
}}
• Declaration
• Constructor (for instance variables)
📌 Example:
class Bike {
final void run() {
[Link]("Running safely...");
}}
Useful when you want to protect method logic from being changed.
📌 Example:
final class Car {
void drive() {
[Link]("Driving...");
}}
--------------------------------------------------------------------------------------
[Link] class equals tostring
🔸 Characteristics:
📌 Example:
class Animal {
void sound(){
[Link]("Animal sound");
}}
🔸 Characteristics:
🔁 Summary Table:
Feature Upcasting Downcasting
Direction Child → Parent Parent → Child
Cast Needed? No Yes
Safe? Always safe Risky (check with instanceof)
Purpose Polymorphism, generalization Access child-specific methods
A wrapper class wraps (or boxes) a primitive data type into an object.
Think of it like this: Wrapper class = A box that contains a basic (primitive) value inside.
Reason Explanation
Java is object-oriented But primitive types (like int, char) are not objects
Collections (like ArrayList) only work
So we use Integer, Double, etc., instead of int, double
with objects
Useful methods Wrapper classes come with built-in methods, like parseInt()
Allows null values Primitives can’t be null, but wrappers can (e.g., Integer a = null;)
--------------------------------------------------------------------------------------
An abstract class is a partially defined class — it cannot be used directly to create objects, but it serves as a
blueprint for other classes.
Rule Description
abstract keyword Used to declare an abstract class or method
Cannot be instantiated You can’t do Animal a = new Animal();
Can have constructors But you use them through child classes
Can have both abstract and normal methods So it gives flexibility
Subclasses must implement abstract methods Or they also become abstract
You don’t create a generic "Car" in real life. You create specific Car like WagonR, Ertiga, or Fortuner.
--------------------------------------------------------------------------------------
62.🧩 What is an Inner Class?
Type Description
1. Non-static Inner Class Normal inner class that belongs to an object
2. Static Nested Class Acts like a static member of outer class
3. Local Inner Class Defined inside a method
4. Anonymous Inner Class No name, used for quick one-time implementation
An interface in Java is like a contract that says: "Any class that implements me must provide its own version of
these methods." It's like a blueprint — it only declares methods, but doesn't define how they work.
interface Animal {
void makeSound(); // method with no body
}
Another class:
🔁 Output:
a = new Cat();
[Link](); // Meow!
✅ Key Points:
Feature Interface
Contains Method declarations (and constants)
Access modifier All methods are public abstract by default
Variables All are public static final
Can have default and static methods (Java 8+)
Inheritance type Multiple inheritance supported
interface Vehicle {
void start();
Example:
interface A
{ int age=44; // final and static
String area="Mumbai";
void show();
void config();
}
class B implements A
{
public void show()
{
[Link]("in show");
}
public void config()
{
[Link]("in config");
} }
A obj;
obj=new B();
[Link]();
[Link]();
} }
--------------------------------------------------------------------------------------
66. Need of interface
An interface says: “Any class that implements we must follow certain rules (i.e., implement
these methods).”
• Interfaces let you define what a class should do, but not how.
• It hides the implementation details and only shows the method structure.
interface Payment {
void pay(double amount);
}
Now whether it's CreditCard, UPI, or PayPal, each class can implement it in its own way.
Java doesn’t allow multiple inheritance with classes (i.e., you can’t extend 2 classes),
but:
For example:
Interfaces help in building systems where you can change parts without affecting the rest.
For example, if your Database interface is implemented by MySQL or PostgreSQL, switching
databases is easy.
When writing unit tests, you can use mock interfaces easily instead of actual classes.
Makes testing faster and simpler.
Example:
interface Computer
{
void code();
}
} }
--------------------------------------------------------------------------------------
[Link] on interfaces
interface A
{
int age=44; // final and static
String area="Mumbai";
void show();
void config();
}
interface X
{ void run();
}
interface Y extends X {
}
class B implements A,Y
{
public void show()
{
[Link]("in show");
}
public void config()
{
[Link]("in config");
}
public void run()
{
[Link]("running...");
}}
A obj;
obj=new B();
[Link]();
[Link]();
X obj1=new B();
[Link]();
[Link]([Link]);
}}
--------------------------------------------------------------------------------------
68. Enum
An enum (enumeration) in Java is a special type used to define a set of constant values.
🧪 Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Example:
enum Status{
Running, Failed, Pending, Success;
}
public class Demo {
public static void main(String[] args) {
int i=5;
// Status s= [Link];
// Status s= [Link];
// Status s= [Link];
// Status s= [Link];
// [Link](s);
// [Link]([Link]());
Status[] ss=[Link]();
[Link](ss);
for(Status s:ss)
{
[Link](s);
[Link](s+" : "+[Link]());
}}}
✨Features of enum:
enum Status {
PENDING(" "), APPROVED(" "), REJECTED(" ");
private String icon;
Status(String icon) {
[Link] = icon;
}
public String getIcon() {
return icon;
}}
public class Main {
public static void main(String[] args) {
Status s = [Link];
[Link](s + " " + s.getIco5n()); // Output: APPROVED
}}
Method Description
values() Returns all enum constants
valueOf() Returns enum constant by name
ordinal() Returns index (starts from 0)
Example:
--------------------------------------------------------------------------------------
69. Enum with switch
enum Status{
Running, Failed, Pending, Success;
}
public class Demo {
public static void main(String[] args) {
Status s = [Link];
switch(s)
{
case Running:
[Link]("All Good");
break;
case Failed:
[Link]("Try Again");
break;
case Pending:
[Link]("Please Wait");
break;
default:
[Link]("Done");
break;
}
if(s==[Link])
[Link]("All Good");
else if(s==[Link])
[Link]("Try Again");
else if ( s==[Link])
[Link]("Please Wait");
else
[Link]("Done");
}}
--------------------------------------------------------------------------------------
[Link] class
enum Laptop{
// Mackbook(2000), XPS(2200), Surface(1500), ThinkPad(1800);
Mackbook(2000), XPS(2200), Surface, ThinkPad(1800);
private Laptop()
{
price=500;
}
private Laptop(int price)
{
[Link]=price;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
[Link] = price ;
[Link]("in Laptop" + [Link]());
}}
public class Demo {
public static void main (String[] args) {
// Laptop lap=[Link];
// [Link](lap+ " : "+[Link]());
{
[Link]("in show B");
}}
public class Demo {
public static void main(String[] args) {
B obj=new B();
[Link]();
}}
--------------------------------------------------------------------------------------
[Link] of Interface
--------------------------------------------------------------------------------------
[Link] Interface
A Functional Interface in Java is an interface that has exactly one abstract method. It
can have any number of default or static methods, but only one abstract method.
Functional Interfaces are used with Lambda Expressions, method references, and streams,
especially introduced in Java 8 to support functional programming.
✅ Syntax:
@FunctionalInterface
interface MyFunctionalInterface {
void show(); // only one abstract method
}
{
A obj = new A()
[Link]("in show");
}};
[Link]();
}}
The @FunctionalInterface annotation is optional, but if you use it, the compiler will give
an error if you add more than one abstract method.
@FunctionalInterface
interface Greeting {
void sayHello();
}
🎯 Summary:
A obj=new A()
{
public void show()
{
[Link]("in Show");
}
};
// A obj=new A();
// A obj=new B();
[Link]();
}}
--------------------------------------------------------------------------------------
74-75 Lambda Expression in java
A lambda expression is a short way to write code for a method, especially for functional interfaces (interfaces with
only one method).
✅ Syntax:
(parameter) -> { body }
📦 Real-World Analogy:
Imagine a cook (function) you call just once to fry an egg — you don’t need to give them a name or remember them.
That’s a lambda — a one-time, short, useful piece of logic.
Great! Let's now see how to use lambda expressions in Java with a return statement.
If your lambda has multiple lines, or you want to use return explicitly, use curly braces {} and a return keyword.
🧪 Example:
@FunctionalInterface
interface MyMath {
int operation(int a, int b);
}
✅ Explanation:
• (a, b) → parameters
• { ... } → lambda body (can have multiple lines)
• return a - b; → explicitly returning a value
--------------------------------------------------------------------------------------
[Link]
An exception is an event that occurs during the execution of a program that disrupts the normal flow.
• try
• catch
• finally
• throw
• throws
Exception handling allows you to catch runtime errors and handle them gracefully without crashing the program.
🔹 Rules:
• More specific exceptions must be caught before general ones like Exception.
• Only one catch block will be executed per exception.
• Use Exception e as a generic catch-all at the end.
try {
int a = 5 / 1;
} catch (Exception e) {
[Link]("Handled");
} finally {
[Link]("Finally block always runs.");
}
--------------------------------------------------------------------------------------
80. Exception with throw keyword
Output:
🔹 throw vs throws
throw throws
Used to actually throw an exception Used to declare possible exceptions in method signature
Can throw only one exception at a time Can declare multiple exceptions
Placed inside method body Placed in method declaration
🔹 Real-World Use:
• Input validation
• Custom logic checks
• Raising custom exceptions (like InvalidAmountException)
--------------------------------------------------------------------------------------
81. Custom Exception
A custom exception is a user-defined class that extends Java’s Exception or RuntimeException class to
represent specific error conditions in your application.
🔁 Output:
Caught Exception: Age is less than 18 — Not allowed
Ducking an exception means passing the responsibility of handling an exception up the call stack using the throws
keyword — instead of catching it immediately.
When a method does not handle a checked exception using try-catch, it can "duck" the exception using the
throws clause to tell the caller that it must handle the exception.
🔸 Syntax:
returnType methodName(...) throws ExceptionType {
// code that may throw exception
}
class Example {
// Method ducks the IOException
static void readFile() throws IOException {
FileReader fr = new FileReader("[Link]"); // may throw IOException
BufferedReader br = new BufferedReader(fr);
[Link]([Link]());
[Link]();
}
⚠️ You must handle or declare a checked exception, or the compiler will give an error.
🔁 Summary:
void methodA() throws IOException {
// exception ducked to caller
}
void methodB() {
try {
methodA(); // caller handles it
} catch (IOException e) {
[Link]("Handled exception");
}}
83.