[Go to site: main page, start]

0% found this document useful (0 votes)
10 views66 pages

Java

Java is a high-level, object-oriented programming language known for its platform independence, simplicity, and security features. It includes key components like the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK) for running and developing applications. The document also covers variables, data types, literals, type conversion, and operators in Java.
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)
10 views66 pages

Java

Java is a high-level, object-oriented programming language known for its platform independence, simplicity, and security features. It includes key components like the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK) for running and developing applications. The document also covers variables, data types, literals, type conversion, and operators in Java.
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

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.

🔑 Key Features of Java:

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.

✅ 1. JVM (Java Virtual Machine) – The Engine

• 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).

✅ 2. JRE (Java Runtime Environment) – The Car

• 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).

✅ 3. JDK (Java Development Kit) – The Factory

• What it is: JDK is a full toolkit for Java developers.


• What it does: It lets you write, compile, and run Java programs.
• What's inside: JDK = JRE + development tools like:
o javac (Java compiler)
o java (JVM launcher)
o javadoc (for documentation)
o jshell, javap, and more

Example: JDK is like a car manufacturing unit where you build the car (develop software). Once built, the car
(JRE) can run anywhere.

---------------------------------------------------------------------------------------

5.🧠 What is a Variable in Java?

A variable is like a container or box in your program that holds some data or value.

Imagine it like this:

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!

🧾 Basic Structure of a Variable in Java:

dataType variableName = value;

For example: int age = 20;

• int → tells Java the type of data (here, an integer/number)


• age → is the name of the variable
• 20 → is the value stored in it
🧃 Types of Variables (Based on Data Type):

Data Type Meaning Example


int Whole numbers int x = 10;
double Decimal numbers double pi = 3.14;
char Single character char grade = 'A';
String Text (words) String name = "Aisha";
boolean True or false boolean isCool = true;

🧩 Example:

public class Main {


public static void main(String[] args) {
String name = "Aisha";
int age = 21;
double height = 5.4;
boolean isStudent = true;
[Link](name + " is " + age + " years old.");
} }

Output: Aisha is 21 years old.

✅ 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.

🧱 Two Main Categories of Data Types: 🥇 Primitive Data Types (8 types)

Data Type What It Stores Example


int Whole numbers int age = 20;
float Decimal numbers (less float price = 19.99f;
precise)
double Decimal numbers (more double pi = 3.14159;
precise)
char Single character char grade = 'A';
boolean True or False boolean isJavaFun = true;
byte Tiny numbers (-128 to 127) byte smallNum = 100;
short Small numbers (-32k to 32k) short temperature = 25000;
long Big whole numbers long distance = 100000000L;

Note: Add f after float values, and L after long values.

🥈 Non-Primitive Data Types : These are more complex types made from primitive types or defined by you.

Data Type What It Stores Example


String A sequence of characters String name = "Aisha";
(text)
Array A group of values int[] marks = {90, 80, 70};
Class User-defined blueprint You can create your own type like class
Student {}

🎯 Why Data Types Matter : Java is strict. You have to tell it exactly what kind of data you're working with.

int age = 22; // Correct


String age = 22; // Error! 22 is a number, not text

🧪 Example:

public class Main {


public static void main(String[] args) {
int age = 21;
double height = 5.4;
char grade = 'A';
boolean isStudent = true;
String name = "Aisha";
[Link](name + " is " + age + " years old and got grade " + grade);
} }

Output: Aisha is 21 years old and got grade A

---------------------------------------------------------------------------------------

7.🧠 What Are Literals in Java?

A literal is just a fixed value that you write directly in your code.

Think of literals as the actual value you assign to a variable.

Example: int age = 21;

Here, 21 is a literal — it’s the actual value you're storing in the variable age.

🧱 Types of Literals in Java:

Let’s go through them with simple examples:


1. Integer Literal (Whole numbers) Used with int, long, byte, short

int age = 25; // 25 is an integer literal


long distance = 100000L; // Add L for long

2. Floating-point Literal (Decimal numbers) Used with float, double


double pi = 3.14; // 3.14 is a double literal
float price = 9.99f; // Add 'f' for float

3. Character Literal (Single character) Use single quotes

char grade = 'A'; // 'A' is a char literal

4. String Literal (Text) Use double quotes

String name = "Aisha"; // "Aisha" is a string literal

5. Boolean Literal (True/False)java

boolean isJavaFun = true; // true is a boolean literal

6. Null Literal

String data = null; // null means "no value"

🧪 Example Using All:

public class Example {


public static void main(String[] args) {
int age = 20;
float temp = 98.6f;
char letter = 'B';
String name = "Java";
boolean isCool = true;
String nothing = null;

[Link](name + " is cool: " + isCool);


}}

--------------------------------------------------------------------------------

8.🧠 What is Type Conversion?

Type Conversion in Java means changing a value from one data type to another.

Example: Converting an int to a double, or a float to a String.

It's like pouring water from a small cup into a big glass — or the other way around!
🔄 Two Types of Type Conversion:

🟢 1. Implicit Type Conversion (Automatic)

Also called Widening Conversion Java automatically converts a smaller data type to a bigger one safely.

Safe because there's no data loss.

📌 Example:

Int num=10;
double d= num;// int→double(automatic)

[Link](d); //Output:10.0

Other examples: byte → short → int → long → float → double

🔴 2. Explicit Type Conversion (Manual)

Also called Type Casting You manually tell Java to convert a bigger type into a smaller one.

Risk of data loss.

📌 Example:

Double pi= 3.14;


int whole = (int) pi;//You cast it manually
[Link](whole); // Output: 3 (loses decimal part)
Syntax: dataType variableName = (newDataType) value;

🧪 Mini Example (Both Types):

public class Example {


public static void main(String[] args) {
int x = 100;
double y = x; // Implicit
[Link](y); // 100.0

double z = 9.99;
int w = (int) z; // Explicit
[Link](w); // 9
} }

🎯 Quick Recap:

Type Also Called Done By Safe? Example


Implicit Widening Java Yes int →
double
Explicit Narrowing You Maybe not double →
int
[Link] are Arithmetic Operators? 📋

List of Arithmetic Operators:

Operator Meaning Example Result


+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 6 / 2 3
% Modulus 5 % 2 1
(Remainder)

🧪 Example Code:

public class MathExample {


public static void main(String[] args) {
int a = 10;
int b = 3;
[Link]("Addition: " + (a + b)); // 13
[Link]("Subtraction: " + (a - b)); // 7
[Link]("Multiplication: " + (a * b)); // 30
[Link]("Division: " + (a / b)); // 3 (only whole number!)
[Link]("Modulus: " + (a % b)); // 1 (remainder)
}}

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.

✅ List of Relational Operators in Java:


Operator Description Example Output
== Equal to 5 == 5 true

!= Not equal to 5 != 3 true

> Greater than 10 > 6 true

< Less than 3 < 7 true


Operator Description Example Output
Greater than or equal
>= 5 >= 5 true
to
<= Less than or equal to 4 <= 6 true

🧪 Example Code:
public class RelationalExample {
public static void main(String[] args) {
int a = 10, b = 20;

[Link]("a == b: " + (a == b)); // false


[Link]("a != b: " + (a != b)); // true
[Link]("a > b: " + (a > b)); // false
[Link]("a < b: " + (a < b)); // true
[Link]("a >= b: " + (a >= b)); // false
[Link]("a <= b: " + (a <= b)); // true
}}

📌 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)

1. When comparing primitive values (like int, char, boolean, etc.):

== compares the actual values stored in the variables.

Example:

int x = 5;
int y = 5;
[Link](x == y); // true → because 5 equals 5

2. When comparing objects (like String, arrays, or custom objects):

== compares memory addresses (references) — whether both variables point to the same object.

Example with String objects:

String a = new String("hello");


String b = new String("hello");

[Link](a == b); // false → different memory locations


[Link]([Link](b)); // true → same content
Example with same reference:

String a = "hello";
String b = "hello";

[Link](a == b); // true (because of Java String pool)

[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.

✅ Logical Operators in Java


Operator Name Description Example
Logical true && true →
&& Returns true if both expressions are true
AND true
` ` Logical OR
Logical Reverses the result: true becomes false, false becomes
! !true → false
NOT true

🧪 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:

• In &&, if the first condition is false, second is not evaluated.


• In ||, if the first condition is true, second is not evaluated.

Example: if (false && someMethod()) // someMethod() won't be called

🔹 AND (&&) – Logical AND

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

-----------------------------------------------------------------------------------------------------------------------------------

12 & 13. If Else, else if

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
}

🧪 Example: Grade Checker


public class GradeChecker {
public static void main(String[] args) {
int marks = 75;

if (marks >= 90) {


[Link]("Grade: A+");
} else if (marks >= 80) {
[Link]("Grade: A");
} else if (marks >= 70) {
[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}}}

📌 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).

✅ Simple If-Else Example


int number = 5;
if (number % 2 == 0) {
[Link]("Even");
} else {
[Link]("Odd");
}

✅ Nested If Example
int age = 22;
String gender = "Female";

if (age >= 18) {


if ([Link]("Female")) {
[Link]("You are an adult woman.");
} else {
[Link]("You are an adult man.");
}
} else {
[Link]("You are a minor.");

-----------------------------------------------------------------------------------------------------------------------------------

[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.

✅ Syntax of Ternary Operator


condition ? Expression 1 : expression 2;

• If condition is true, expression1 is evaluated.


• If condition is false, expression2 is evaluated

🧪 Example 1: Even or Odd


int number = 5;
String result = (number % 2 == 0) ? "Even" : "Odd";
[Link](result); // Output: Odd

🧪 Example 2: Maximum of Two Numbers


int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Maximum: " + max); // Output: Maximum: 20

🧪 Example 3: Pass or Fail


int marks = 45;
String status = (marks >= 40) ? "Pass" : "Fail";
[Link](status); // Output: Pass

📌 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.

✅ Syntax of switch Statement


switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}

🧪 Example: Weekday Checker


public class SwitchExample {
public static void main(String[] args) {
int day = 3;

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.

🧪 Example with String (Java 7+)


String fruit = "Mango";
switch (fruit) {
case "Apple":
[Link]("Red fruit");
break;
case "Mango":
[Link]("Yellow fruit");
break;
default:
[Link]("Unknown fruit");
}

🧠 When to Use switch:

Use switch when:

• You're comparing one variable to many constant values.


• The code becomes too long or messy with if-else-if.

-----------------------------------------------------------------------------------------------------------------------------------

17,18 &19. While ,do while and for loop

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

----------------------------------------------------------------------------------------------------------------------------------

21. Class and Object

🔹 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:

1. Fields (Attributes/Variables) – to store the object’s data


2. Methods (Functions) – to define the object’s behavior

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:

Public class Main {


Public static void main (String[] args) { // Creating an object of Car class
Car myCar = new Car(); // Assign values
[Link] = “Red”;
[Link] = 100 // Call method
[Link](); // Output: The car is driving at 100 km/h.

-----------------------------------------------------------------------------------------------------------------------------------
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

returnType methodName(parameter1, parameter2, ...) {

// method body // code to execute

return value; // if returnType is not void

🔹 Example:

public class Calculator {

// Method to add two numbers

int add(int a, int b) {

return a + b; }

// Method to print a message

void greet() {

[Link]("Welcome to the Calculator!");

public static void main(String[] args) {

Calculator calc = new Calculator();

[Link](); // Output: Welcome to the Calculator!

int sum = [Link](5, 10);

[Link]("Sum = " + sum); // Output: Sum = 15


} }

🔹 Types of Methods in Java

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

• Belongs to the class, can be called without creating an object.

public class Example {


static void staticMethod() {
[Link]("This is a static method.");
}

public static void main(String[] args) {


staticMethod(); // called directly
}}

✅ 2. Non-static Method

• Belongs to an object, needs an object to call.

public class Example {


void nonStaticMethod() {
[Link]("This is a non-static method.");
}

public static void main(String[] args) {


Example obj = new Example();
[Link](); // called using object
}}

✅ 3. Method With Return

• Returns a value (like int, String, etc.)

public class Example {


int square(int x) {
return x * x;
}

public static void main(String[] args) {


Example obj = new Example();
int result = [Link](5);
[Link]("Square: " + result); // Output: 25
}}
✅ 4. Void Method

• Returns nothing (just performs an action).

public class Example {


void greet() {
[Link]("Hello, welcome!");
}

public static void main(String[] args) {


Example obj = new Example();
[Link](); // Output: Hello, welcome!
}}

✅ 5. Method With Parameters

• Accepts input (parameters or arguments).


public class Example {
void displayName(String name) {
[Link]("Your name is: " + name);
}

public static void main(String[] args) {


Example obj = new Example();
[Link]("Nupur"); // Output: Your name is: Nupur
}}

✅ 6. Method Without Parameters

• No input is required.

Public class Example{


voidshowMessage(){

[Link]("Noparametershere!");

}
publicstaticvoidmain(String[]args){
Exampleobj=newExample();
[Link](); // Output: No parameters here!
}}

---------------------------------------------------------------------------------------------------------------------------------

[Link] overloading

🔄 Method Overloading in Java

Method Overloading means having multiple methods with the same name in a class, but with different
parameters (type, number, or order).

It's a form of compile-time polymorphism in Java.


✅ Why Use Method Overloading?

• Improves code readability


• Allows methods to perform similar tasks with different input
• Avoids creating multiple method names for similar functionality

🔹 Rules for Method Overloading

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)

🔸 Example: Method Overloading

public class Calculator {


// Method 1: Adding two integers

int add(int a, int b) {


return a + b;
}

// Method 2: Adding three integers


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

// Method 3: Adding two doubles


double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator();

[Link]([Link](5, 10)); // Calls method 1


[Link]([Link](5, 10, 15)); // Calls method 2
[Link]([Link](5.5, 4.5)); // Calls method 3
} }

✅ Example 2: greet() with different types of parameters

public class Greeter {


// No parameter
void greet() {
[Link]("Hello!"); }

// With String parameter


void greet(String name) {
[Link]("Hello, " + name + "!"); }
// With int parameter
void greet(int age) {
[Link]("You are " + age + " years old."); }

public static void main(String[] args) {


Greeter g = new Greeter();
[Link](); // Hello!
[Link]("Nupur"); // Hello, Nupur!
[Link](21); // You are 21 years old.
}}

✅ Example 3: area() for different shapes

public class AreaCalculator {

// 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;
}

public static void main(String[] args) {


AreaCalculator ac = new AreaCalculator();
[Link]("Square: " + [Link](4)); // 16
[Link]("Rectangle: " + [Link](4, 5)); // 20
[Link]("Circle: " + [Link](2.5)); // 19.625
}}

🔴 Not Allowed:

You cannot overload a method by changing only the return type.

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


// double add(int a, int b) { return a + b; } Not allowed
-----------------------------------------------------------------------------------------------------------------------------------

[Link] and Heap


🧠 What is Heap in Java? In Java, the Heap is a part of the memory where objects are stored at runtime.

📌 Simple Definition: Heap is a memory area in JVM where all Java objects and class instances are stored
during program execution.

🔍 How it works:

• Whenever you create an object using new, it is stored in the heap.


• For example: Student s = new Student(); // Stored in heap
• The reference (s) is stored in the stack, but the actual Student object is stored in the heap.

📌 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:

public class Demo {


public static void main(String[] args) {
String name = "Nupur"; // "Nupur" stored in heap (interned)
int x = 10; // 'x' stored in stack
Student s1 = new Student(); // s1 → reference in stack, object in heap
}}

💡 Why is heap important?

• It stores real-world data (like objects of your app).


• It's where memory leaks or out of memory errors may occur if too many objects are created and not
released.

-----------------------------------------------------------------------------------------------------------------------------------

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.

1. Normal (1D) Array in Java

Definition: A 1D array is a collection of elements (of the same data type) stored in a single row.

Syntax: dataType[] arrayName = new dataType[size];

🔹 Example:

public class OneDArray {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

for (int i = 0; i < [Link]; i++) {


[Link](numbers[i]);
}}}

🔵 2. Multidimensional (2D) Array in Java

Definition: A 2D array is like a matrix or a table — with rows and columns.

Syntax: dataType[][] arrayName = new dataType[rows][columns];

🔹 Example :

public class twoDArray {

public static void main ( String [] args) {

Int [][] matrix = { {1, 2} , {3, 4} , {5, 6} } ;

for (int i = 0 ; i < [Link] ; i ++ ) {

for (int j = 0 ; j < matrix[i].length ; j ++ ) {

[Link](matrix [i] [j] + " ") ;

} [Link]();

} } }

3. Jagged Array (Array of Arrays) in Java

Definition: A jagged array is a 2D array where each row can have different number of columns.

Syntax: dataType[][] arrayName = new dataType[rows][];


🔹 Example:

Public class JaggedArray {


Public static void main (String [] args) {
Int [][] jagged = new int [3][] ;
Jagged[0] = new int[2]; // row 0 has 2 columns
Jagged[1] = new int[3]; // row 1 has 3 columns
Jagged[2] = new int[1]; // row 2 has 1 column
// Filling and printing
Int value = 1;
For (int i = 0; I < [Link]; i++) {
For (int j = 0; j < jagged[i].length; j++) {
Jagged[i][j] = value++;
[Link]( jagged[i][j] + “ “ ) }
[Link]();
}}}

🔴 4. 3D Array in Java

Definition: 3D array is an array of 2D arrays — imagine a cube or multiple matrices.

Syntax: datatype[][][] arrayName = new dataType[x][y][z];


🔹 Example:

public class ThreeDArray {

public static void main(String[] args) {

int[][][] cube = new int[2][2][2];

int count = 1;

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < cube[i].length; j++) {

for (int k = 0; k < cube[i][j].length; k++) {

cube[i][j][k] = count++;

[Link](cube[i][j][k] + " ");

[Link]();
}

[Link]("---- Block " + (i + 1) + " ----");

}}}

--------------------------------------------------------------------------------------

[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.

-------------------------------------------------------------------------------------

[Link] for loop

🔁 Enhanced For Loop in Java (Also called For-Each Loop)

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

public class Main {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {


[Link](num);
}}}

Output:

10
20
30
40

🔹 Example 2: Loop through a String Array

String[] names = {"Aisha", "Riya", "Meera"};

for (String name : names) {


[Link](name);
}

🔹 Example 3: Loop through an ArrayList

import [Link].*;

public class Main {


public static void main(String[] args) {
ArrayList<String> tasks = new ArrayList<>();
[Link]("Wake up");
[Link]("Code");
[Link]("Sleep");

for (String task : tasks) {


[Link](task);
}}}

⚠️ 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

📌 What is a String in Java?

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:

String name = "Aisha";


[Link](name);

📘 Key Points about Strings:

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.

What really happens here:

1. "navin" is stored in the name variable.


2. When you do name = name + " reddy", Java creates a new String object "navin reddy"
in memory.
3. The original "navin" string is not changed — it stays in memory (possibly in the
String pool).
4. The variable name is now pointing to the new string "navin reddy".

🧠 So, you didn’t modify the original string — you just created a new one and reassigned
it to the same variable.

🔧 Common String Methods:

Method Description Example


length() Returns length of the string "Java".length() → 4
charAt(index) Returns character at index "Java".charAt(2) → 'v'
toUpperCase() Converts to upper case "java".toUpperCase() → "JAVA"
toLowerCase() Converts to lower case "JAVA".toLowerCase() → "java"
contains("text") Checks if contains given "hello".contains("he") → true
text
equals(str) Compares contents "abc".equals("abc") → true
equalsIgnoreCase( Compares ignoring case
"abc".equalsIgnoreCase("ABC"
) )
substring(start, Extracts part of string "Hello".substring(1, 3) →
end) "el"
concat() Adds two strings "Hello".concat(" World")
replace() Replaces characters "apple".replace('a','A') →
"Apple"
--------------------------------------------------------------------------------------

[Link] and StringBuilder

🔹 1. StringBuffer

• Introduced in Java 1.0


• Thread-safe (synchronized): multiple threads can safely use it, but slower
• Used when multiple threads are working on the same string

Example:

StringBuffer sb = new StringBuffer("Hello");


[Link](" World") ;
[Link](sb); // Output: Hello World
🔸 2. StringBuilder

• Introduced in Java 1.5


• Not thread-safe (not synchronized): faster but not safe for multi-threading
• Used when string is modified by a single thread

Example:

StringBuilder sb = new StringBuilder("Hello");


[Link](" Java");
[Link](sb); // Output: Hello Java

🔍 Key Differences Table:

Feature String StringBuffer StringBuilder


Mutability Immutable Mutable Mutable
Thread-safe Yes (internally safe) Yes (synchronized) No (not synchronized)
Performance Slow (new object created each time) Slower (due to sync) Faster
When to Use Fixed data Multi-threaded app Single-threaded app

🔁 Why use StringBuffer/StringBuilder?

If you are modifying strings repeatedly (e.g., inside loops), using StringBuffer or StringBuilder is more
efficient than String.

--------------------------------------------------------------------------------------

37,38, & 39 . Static variable, method and block

🔹 1. Static Variable (Class Variable)

• Shared among all objects of the class.


• Only one copy exists, regardless of how many objects are created.
• Useful for constants or common counters.

Example:

class Student {
static String college = "ABC College"; // Static variable
String name;

Student(String name) {
[Link] = name;
}

void show() {
[Link](name + " studies at " + college);

}}

public class Main {


public static void main(String[] args) {
Student s1 = new Student("Aisha");
Student s2 = new Student("Ravi");
[Link]();
[Link]();
}}

Output:

Aisha studies at ABC College


Ravi studies at ABC College

🔸 2. Static Method

• Can be called without creating an object.


• Can only access static data directly (not instance variables).
• Mostly used for utility or helper methods.

Example:

class Calculator {
static int square(int x) {
return x * x;
}}

public class Main {


public static void main(String[] args) {
[Link]([Link](5)); // No object needed
}}

🔹 3. Static Block

• Runs once when the class is loaded.


• Used to initialize static variables.
• Executes before main method (if the class is loaded first).

Example:

class Demo {
static int x;
static {
x = 100;
[Link]("Static block executed");
}}

public class Main {


public static void main(String[] args) {
[Link](Demo.x);
}}

Output:

Static block executed


100
🧠 Summary Table:

Feature Description Can Access


Static Shared across all instancesFrom class or
Variable object
Static MethodBelongs to class, not instance Only static
members
Static Block Initializes static data, runs Any static variables
once
--------------------------------------------------------------------------------------

40. Encapsulation in java

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.

🧱 Key Features of Encapsulation in Java:

1. Make variables private (not accessible directly)


2. Provide public getter and setter methods to access/update them
3. Class controls what is accessible and how it's modified

🧪 Java Example:
public class Student {
private String name; // private = hidden from outside
private int age;

// Getter for name


public String getName() {
return name;
}
// Setter for name
public void setName(String newName) {
name = newName;
}
// Getter for age
public int getAge() {
return age;
}

// Setter for age with validation


public void setAge(int newAge) {
if (newAge > 0) {
age = newAge;
}}}
🧾 Using the Class:
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]("Nupur");
[Link](20);
[Link]([Link]()); // Nupur
[Link]([Link]()); // 20
}}

🎯 Why Use Encapsulation?


Benefit Description
Data Hiding Prevents direct access to fields (more secure)
Control Access Add validation in setters
Easy to Maintain Changes in code won't affect external classes
Better Reusability Code is modular and cleaner

Quick Recap: Encapsulation = Data Hiding + Getters/Setters


--------------------------------------------------------------------------------------

[Link] and setter

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.

✅ Why Use Getters and Setters?

• Control access to private fields


• Add validation before setting values
• Maintain encapsulation
• Easily debug or log changes

📌 Naming Conventions:

• getFieldName() → for reading values


• setFieldName(value) → for writing values
• Follows JavaBeans standard (used in tools like Spring, Hibernate, etc.)

⚠️ Without Getters/Setters (Not Recommended):


public class Student {
public String name; // Public field
}

Anyone can access and modify the field directly:

[Link] = "Hacker"; // No control or validation

✅ With Getters/Setters: More Control


[Link]("Nupur"); // Safe & valid
[Link]([Link]()); // Controlled access

--------------------------------------------------------------------------------------

42. This keyword

The this keyword in Java is a reference to the current object — the object whose method or constructor is being
called.

✅ Uses of this Keyword:


1. Differentiate Instance Variables from Parameters

When method parameters have the same name as instance variables, this is used to refer to the current object's
variable.

public class Student {


private String name;

public void setName(String name) {


[Link] = name; // "[Link]" refers to instance variable
}}
2. Call Another Constructor (Constructor Chaining)

You can use this() to call another constructor in the same class.

public class Student {


private String name;
private int age;

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.

public void printInfo(Student s) {


[Link]([Link]);
}

public void show() {


printInfo(this); // passes current object to printInfo
}
4. Return Current Object

This allows method chaining (fluent API style).


public class Student {
private String name;

public Student setName(String name) {


[Link] = name;
return this; // return current object
} }
Student s = new Student().setName("Nupur");

🧠 Example Summary:
public class Person {
String name;

public Person(String name) {


[Link] = name; // distinguishes local and instance variable
}

public void printName() {


[Link]("Name: " + [Link]); // refers to current object's
name
} }

📌 Key Point: this always refers to the current class instance.

--------------------------------------------------------------------------------------

43 & 44. Constructor

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:

• Constructor name must match the class name.


• It has no return type (not even void).
• Called automatically when an object is created.

🔸 Types of Constructors:

1. Default Constructor – No parameters


2. Parameterized Constructor – Takes arguments
3. Copy Constructor (manually created) – Copies data from another object

✅ 1. Default Constructor:
public class Student {
// Constructor
Student() {
[Link]("Default constructor called");
}

public static void main(String[] args) {


Student s1 = new Student(); // Constructor is called
}}
✅ 2. Parameterized Constructor:
public class Student {
String name;
int age;

// Constructor with parameters


Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link](name + " is " + age + " years old.");
}
public static void main(String[] args) {
Student s1 = new Student("Nupur", 21);
[Link]();
} }

✅ 3. Copy Constructor (Manual):


public class Student {
String name;

Student(String n) {
name = n;
}

// Copy constructor
Student(Student s) {
name = [Link];
}

public static void main(String[] args) {


Student s1 = new Student("Nupur");
Student s2 = new Student(s1); // copying s1 to s2
[Link]([Link]);
} }

🚫 Important Notes:

• If no constructor is written, Java provides a default constructor.


• If you define any constructor, Java won't provide the default one automatically.

--------------------------------------------------------------------------------------
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]
--------------------------------------------------------------------------------------

46. Anonymous Object

🔹 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!");
}}

public class Main {


public static void main(String[] args) {
// Anonymous object calling method
new Student().display();
}}
When to Use:

• When the object is used only once.


• To reduce memory usage if you don’t need to reuse the object.

🚫 Drawbacks:

• You can't reuse the object.


• You can't access other members of the object later.

✅ Comparison:
// Regular object
Student s = new Student();
[Link](); // Can use s again

// Anonymous object
new Student().display(); // Cannot use this object again
--------------------------------------------------------------------------------------

47-50 Inheritance in Java

Inheritance is one of the core features of Object-Oriented Programming (OOP).


It allows a class to inherit properties and behavior (fields and methods) from another class.

✅ Why Use Inheritance?

• Code reusability
• Improves maintainability
• Supports polymorphism and extensibility

🔹 Syntax:
class Parent {
// properties and methods
}

class Child extends Parent {


// additional properties and methods
}

🔸 Types of Inheritance in Java

Java supports single, multilevel, and hierarchical inheritance.


It does not support multiple inheritance with classes (to avoid ambiguity), but it supports it using interfaces.

1. Single Inheritance

One class inherits from one superclass.

class Animal {
void sound() {
[Link]("Animal makes sound");
}}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}}

public class Test {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited
[Link](); // own method
}}

2️ .Multilevel Inheritance

A class inherits from a class, which itself inherits from another class.

class Animal {
void sound() {
[Link]("Animal makes sound");
}}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}}

class Puppy extends Dog {


void weep() {
[Link]("Puppy weeps");
}}
public class Test {
public static void main(String[] args) {
Puppy p = new Puppy();
[Link](); // from Animal
[Link](); // from Dog
[Link](); // own method
}}

3️. Multiple Inheritance (Using Interfaces Only)

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");
}}

public class Test {


public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}}

✅ 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
--------------------------------------------------------------------------------------------------------------------------------------

51. This and super Method

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:

1. To refer to instance variables of the current class.


2. To call other constructors in the same class (constructor chaining).
3. To pass the current object as a parameter to another method.

📌 Example 1: Using this to refer to instance variables


public class Student {
int id;
String name;

Student(int id, String name) {


[Link] = id; // [Link] refers to instance variable
[Link] = name; // name is local, [Link] is instance
}

void display() {
[Link]("ID: " + [Link] + ", Name: " + [Link]);
}}
📌 Example 2: Constructor chaining using this()
public class Student {
int id;
String name;

Student() {
this(101, "Default");
}

Student(int id, String name) {


[Link] = id;
[Link] = name;
}

void display() {
[Link](id + " " + name);
}}

🔹 super keyword

super refers to the parent class (superclass) of the current object.

✅ Common Uses of super:

1. To call the parent class constructor.


2. To access parent class methods.
3. To access parent class variables (if hidden).

📌 Example 1: Calling superclass constructor


class Animal {
Animal() {
[Link]("Animal constructor");
}}
class Dog extends Animal {
Dog() {
super(); // Calls Animal constructor
[Link]("Dog constructor");
}}
📌 Example 2: Accessing parent class method/variable
class Animal {
void sound() {
[Link]("Animal makes a sound");
}}
class Dog extends Animal {
void sound() {
[Link](); // Calls Animal's sound()
[Link]("Dog barks");
}}

🆚 Difference Between this and super:


Feature this super
Refers to Current class object Parent class object
Accesses Current class variables/methods Superclass variables/methods
Constructor call this() calls another constructor in same class super() calls superclass constructor

------------------------------------------------------------------------------------------------------------------------------------------
[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.

🔹 Key Rules for Method Overriding


Rule Description
Inheritance Overriding happens between superclass and subclass.
Method Signature Must have same name, return type, and parameters.
Access Modifier Cannot reduce visibility (e.g., public → private ).
Non-final Method must not be final or static in superclass.
@Override Annotation used to ensure proper overriding (optional but recommended).

📌 Example of Method Overriding


class Animal {
void sound() {
[Link]("Animal makes a sound");
}}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}}
👉 Calling overridden method:
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
[Link](); // Output: Dog barks
}}

🔹 Why Use Method Overriding?

• Runtime Polymorphism (Dynamic Method Dispatch)


• Custom behavior in subclass
• To define specific behavior while keeping the interface same

❌ Method Overriding NOT Allowed When:


Case Reason
final method Final methods cannot be overridden
static method Static methods are not overridden; they are hidden
private method Private methods are not inherited, so can't be overridden
constructor Constructors are never overridden

🔁 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;
}}

class SBI extends Bank {


int getRateOfInterest() {
return 6;
}}

class ICICI extends Bank {


int getRateOfInterest() {
return 7;
}}

public class Main {


public static void main(String[] args) {
Bank b1 = new SBI();
Bank b2 = new ICICI();

[Link]("SBI ROI: " + [Link]() + "%");


[Link]("ICICI ROI: " + [Link]() + "%");
}}

------------------------------------------------------------------------------------
[Link]
[Link] Modifiers

Access modifiers in Java control the visibility (or accessibility) of classes, methods, constructors, and variables.

🔹 Types of Access Modifiers


Within
Modifier Within Package Subclass (other package) Outside Package
Class
public Yes Yes Yes Yes
protected Yes Yes Yes No (except through subclass)
(default) Yes Yes No No
private Yes No No No

🔸 1. public - Accessible from anywhere

public class A {
public int x = 10;
public void show() {
[Link]("Public method");
}}

🔸 2. private - Accessible only within the same class

class A {
private int x = 10;
private void show() {
[Link]("Private method");
}}

🔸 3. default (no modifier) - Accessible within the same package

class A { // default class


int x = 10; // default variable
void show() { // default method
[Link]("Default access");
}}

🔸 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

🔸 1. Compile-Time Polymorphism (Method Overloading)

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

🔸 2. Runtime Polymorphism (Method Overriding)

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

🔍 Why Polymorphism Is Useful:

• 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:

• Involves method overriding


• Uses upcasting (reference of parent class pointing to child class object)
• Java decides which method to call at runtime

🔸 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");
}}

👉 Main method using dynamic method dispatch:


public class Test {
public static void main(String[] args) {
Animal a; // reference of parent class

a = new Dog(); // object of Dog


[Link](); // Output: Dog barks

a = new Cat(); // object of Cat


[Link](); // Output: Cat meows
}}
🔍 How It Works:
Code Actual Object Method Called
Animal a = new Dog(); Dog [Link]()
Animal a = new Cat(); Cat [Link]()

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");
}}

class UPI extends Payment {


void pay() {
[Link]("Paid via UPI");
}}

class CreditCard extends Payment {


void pay() {
[Link]("Paid via Credit Card");
}}

👉 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.

🔸 1. final Variable – ❌ Cannot be Changed

• A final variable is constant — its value cannot be changed once assigned.


• Must be initialized only once.

📌 Example:
public class Example {
final int speedLimit = 60;

void show() {
// speedLimit = 100; Error: Cannot assign a value to final variable
[Link]("Speed Limit: " + speedLimit);
}}

You can assign it in:

• Declaration
• Constructor (for instance variables)

🔸 2. final Method – ❌ Cannot be Overridden

• A final method cannot be overridden by subclasses.

📌 Example:
class Bike {
final void run() {
[Link]("Running safely...");
}}

class Honda extends Bike {


// void run() Not allowed: Cannot override final method
}

Useful when you want to protect method logic from being changed.

🔸 3. final Class – ❌ Cannot be Inherited

• A final class cannot be extended (no subclass can be created).

📌 Example:
final class Car {
void drive() {
[Link]("Driving...");
}}

class Honda extends Car { // Error: Cannot subclass final class


}

Useful to prevent inheritance, e.g., Java’s String class is final.

--------------------------------------------------------------------------------------
[Link] class equals tostring

[Link] and Downcasting


In Java, upcasting and downcasting are related to inheritance and polymorphism. They deal with converting a
reference of one type into another within an object hierarchy.

🔹 1. Upcasting (Safe and Common)

👉 Definition: Upcasting is when a subclass object is referred by a superclass reference.


Parent p = new Child(); // upcasting

🔸 Characteristics:

• Implicit – happens automatically


• Used in runtime polymorphism
• Access only superclass methods and variables

📌 Example:
class Animal {
void sound(){
[Link]("Animal sound");
}}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}}

public class Main {


public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
[Link](); // Allowed
// [Link](); Not allowed (reference type is Animal)
}}

🔹 2. Down casting (Needs Explicit Cast)

👉 Definition: Downcasting is when a superclass reference is cast back to a subclass reference.


Child c = (Child) new Parent(); // unsafe, causes error

🔸 Characteristics:

• Explicit – must be done manually


• Risky – may throw ClassCastException if the object is not actually of the subclass type

📌 Example (Safe Downcasting):


class Animal {
void sound() {
[Link]("Animal sound");
}}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting safe here
[Link](); // Now accessible
}}

📌 Example (Unsafe Downcasting):


Animal a = new Animal();
Dog d = (Dog) a; // Error at runtime: ClassCastException
[Link]();

🔁 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

🔒 Tip: Use instanceof Before Downcasting


if (a instanceof Dog) {
Dog d = (Dog) a; // Safe downcasting
[Link]();
}
--------------------------------------------------------------------------------------

60.🎁 What is a Wrapper Class?

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.

✅ Primitive vs Wrapper Class

Primitive Type Wrapper Class


int Integer
char Character
double Double
boolean Boolean
float Float
long Long
short Short
byte Byte

🧠 Why Do We Need Wrapper Classes?

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;)

--------------------------------------------------------------------------------------

61.🧠 What is an Abstract Class?

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.

• Have abstract methods (without body)


• Have normal methods (with code)
• Be used as a base class for inheritance

Key Rules of Abstract 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

🎨 Real-Life Example (Simple Analogy): Imagine a class called Animal.

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?

An inner class is a class defined inside another class.

It’s like : A small class that belongs to another class.

🎯 Why Use Inner Classes?

To group classes that are only used together

Helps in code readability and organization

Inner class can access private members of outer class

📦 Types of Inner Classes in Java

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

When we make inner class static:


--------------------------------------------------------------------------------------
65. Interfaces
An interface in Java is a reference type, similar to a class, that can contain only abstract methods, static
methods, default methods, and constants.
It is used to achieve abstraction and multiple inheritance in Java.

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.

🔧 Why use Interfaces?

• To achieve abstraction (hide implementation).


• To achieve multiple inheritance (a class can implement many interfaces).
• To ensure consistency across classes (same methods, different behavior).
🧪 Example:

interface Animal {
void makeSound(); // method with no body
}

Now a class can implement this interface:

class Dog implements Animal {


public void makeSound() {
[Link]("Woof!");
}}

Another class:

class Cat implements Animal {


public void makeSound() {
[Link]("Meow!");
}}

🔁 Output:

Animal a = new Dog();


[Link](); // Woof!

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 with default method (Java 8+):

interface Vehicle {
void start();

default void fuelType() {


[Link]("Petrol or Diesel");
}}

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");
} }

public class Demo {


public static void main(String[] args) {

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).”

🔍 Why do we need interfaces?

1️⃣ Achieve Abstraction

• 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.

2️⃣ Multiple Inheritance (of type)

Java doesn’t allow multiple inheritance with classes (i.e., you can’t extend 2 classes),
but:

A class can implement multiple interfaces.

class SmartPhone implements Camera, MusicPlayer, GPS {


// implements all methods from all interfaces
}
3️⃣ Loose Coupling

Using interfaces makes code more flexible and easier to change.

For example:

void printDetails(Employee emp) { ... }

If Employee is an interface, you can pass different implementations like FullTimeEmployee,


Intern, etc., without changing the code.

4️⃣ Plug-and-Play Architecture

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.

5️⃣ Supports Testability and Mocking

When writing unit tests, you can use mock interfaces easily instead of actual classes.
Makes testing faster and simpler.

Example:
interface Computer
{
void code();
}

class Laptop implements Computer


{
public void code()
{
[Link]("code, compile, run");
}}

class Desktop implements Computer


{
public void code()
{
[Link]("code, compile, faster");
}}
class Developer
{
// public void devApp(Laptop lap)
public void devApp(Computer lap)
{
[Link]();
}}

public class Demo {


public static void main(String[] args) {
// Laptop lap=new Laptop();
// Desktop desk=new Desktop();
Computer lap=new Laptop();
Computer desk=new Desktop();

Developer navin=new Developer();


[Link](lap);

} }
--------------------------------------------------------------------------------------

[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...");
}}

public class Demo {


public static void main(String[] args) {

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.

✅ Why use enum?

• To represent fixed sets of constants like:


o Days of the week
o Directions (NORTH, SOUTH, etc.)
o Status (PENDING, APPROVED, REJECTED)

🧪 Example:

enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

You can use it like:

public class Main {


public static void main(String[] args) {
Day today = [Link];
if (today == [Link]) {
[Link]("Start of the week!");
}}}

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:

1. Type-safe – You can’t assign any other value accidentally.


2. Fixed values – Enum constants are predefined and unchangeable.
3. Can have fields, methods, and constructors.

🧪 Advanced Example (with fields & methods):

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
}}

🛠 Common Methods with Enum:

Method Description
values() Returns all enum constants
valueOf() Returns enum constant by name
ordinal() Returns index (starts from 0)

Example:

for (Day d : [Link]()) {


[Link](d + " at position " + [Link]());
}

--------------------------------------------------------------------------------------
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 int price;

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]());

for(Laptop lap : [Link]())


{
[Link](lap + " : " + [Link]());
}}}
--------------------------------------------------------------------------------------
[Link]
@Deprecated
class A
{
public void showTheDataWhichBelongsToThisClass()
{
[Link]("in show A");
}}
class B extends A
{
@Override
// public void showTheDataWhichBelongToThisClass()
public void showTheDataWhichBelongsToThisClass()

{
[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.

✅ Why Functional Interface?

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
}

public class Demo

public static void main(String a[])

{
A obj = new A()

public void show()

[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.

✅ Example with Lambda:

@FunctionalInterface

interface Greeting {
void sayHello();
}

public class Test {


public static void main(String[] args) {
Greeting g = () -> [Link]("Hello!");
[Link](); // Output: Hello!
}}

✅ Real Examples of Functional Interfaces in Java:

Interface Abstract Method Use Case Example


Runnable run() Threads
Callable<V> call() Threads with return
Comparable<T> compareTo(T o) Object sorting
ActionListener actionPerformed() GUI events
Predicate<T> test(T t) Filtering with conditions
Function<T, R> apply(T t) Convert input to output
Consumer<T> accept(T t) Perform action on given input

🎯 Summary:

• Functional Interface = 1 abstract method


• Enables Lambda expressions
• Helps in writing cleaner, shorter code
@FunctionalInterface
interface A
{
void show();
// void run();
}
//class B implements A
//{
// public void show()
// {
// [Link]("in Show");
// }}

public class Demo {


public static void main(String[] args) {

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).

It allows you to write anonymous functions (functions without names).

✅ Syntax:
(parameter) -> { body }

Or even shorter if only one line:

parameter -> singleStatement

📦 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.

🧪 Example 1: Without Lambda


Runnable r = new Runnable() {
public void run() {
[Link]("Hello from thread");
}
};
✨ With Lambda
Runnable r = () -> [Link]("Hello from thread");

Much shorter and cleaner!

🧪 Example 2: With a custom functional interface


@FunctionalInterface
interface MyMath {
int operation(int a, int b);
}

public class Main {


public static void main(String[] args) {
MyMath add = (a, b) -> a + b;
MyMath multiply = (a, b) -> a * b;

[Link]("Sum: " + [Link](5, 3));


[Link]("Product: " + [Link](5, 3));
}}

📌 When to use Lambda Expressions?

• When working with functional interfaces.


• For short and readable code.
• Commonly used with Java Streams, Collections, and multithreading.

Great! Let's now see how to use lambda expressions in Java with a return statement.

✅ Full Syntax with return

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);
}

public class Main {


public static void main(String[] args) {
// Lambda with return and multiple lines
MyMath subtract = (a, b) -> {
[Link]("Subtracting...");
return a - b;
};

int result = [Link](10, 4);


[Link]("Result: " + result);
}}

✅ Explanation:

• (a, b) → parameters
• { ... } → lambda body (can have multiple lines)
• return a - b; → explicitly returning a value

✨ Short version (no return):

You can remove return and {} if it's just a single line:

MyMath multiply = (a, b) -> a * b;

🧠 When to use return?

Use return when:

• The lambda has more than one line.


• You want to add extra logic or debug prints inside the lambda.

--------------------------------------------------------------------------------------
[Link]

An exception is an event that occurs during the execution of a program that disrupts the normal flow.

Java uses a structured exception handling mechanism using:

• try
• catch
• finally
• throw
• throws

🔸 Types of Errors in Java


Error Type Description Example
Compile-Time Syntax error, missing semicolon, undeclared
Errors found by the compiler before execution
Error variable
Errors that occur while the program is ArithmeticException,
Runtime Error
running (aka Exceptions) NullPointerException
Code runs without crashing, but gives wrong
Logical Error Wrong formula used, incorrect loop logic
output

📌 Example for Each:


1. Compile-Time Error
int x = "hello"; // Type mismatch
2. Runtime Error (Exception)
int a = 10 / 0; // ArithmeticException: / by zero
3. Logical Error
// Finding area of rectangle but mistakenly multiplies wrong
int length = 5;
int breadth = 3;
[Link]("Area = " + (length + breadth)); // Wrong logic

🔹 Example of Exception Handling


public class Example {
public static void main(String[] args) {
try {
int a = 10 / 0; // Runtime error
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
} finally {
[Link]("This block always runs.");
}}}
--------------------------------------------------------------------------------------
77.-78 . Exception Handling with try, catch and multiple catch finally

Exception handling allows you to catch runtime errors and handle them gracefully without crashing the program.

🔸 1. Basic try-catch Syntax


try {
// risky code that may throw an exception
} catch (ExceptionType e) {
// handling code
}

🔸 2. Example with Single catch Block


public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
}}}

🔸 3. Multiple catch Blocks (Handling Different Exceptions)


public class MultiCatchExample {
public static void main(String[] args) {
try {
String str = null;
[Link]([Link]()); // NullPointerException
} catch (ArithmeticException e) {
[Link]("Arithmetic error occurred.");
} catch (NullPointerException e) {
[Link]("Null pointer error occurred.");
} catch (Exception e) {
[Link]("Some other exception occurred.");
}}}

🔹 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.

🔸 4. Optional finally Block

Executes always, whether exception occurs or not.

try {
int a = 5 / 1;
} catch (Exception e) {
[Link]("Handled");
} finally {
[Link]("Finally block always runs.");
}
--------------------------------------------------------------------------------------
80. Exception with throw keyword

The throw keyword is used to manually throw an exception in Java.

🔹 Syntax: throw new ExceptionType("custom message");

🔸 Example 1: Throwing a Built-in Exception


public class ThrowExample {
public static void main(String[] args) {
int age = 15;

if (age < 18) {


throw new ArithmeticException("You must be 18 or older to vote.");
} else {
[Link]("You can vote!");
}}}

Output:

Exception in thread "main" [Link]: You must be 18 or older


to vote.

🔹 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

🔸 Example 2: Custom Method with throw


public class Example {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least
18.");
} else {
[Link]("Access granted - You are old enough.");
}}

public static void main(String[] args) {


checkAge(16);
}}

🔹 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.

🔹 Why Use Custom Exceptions?

• To give meaningful names to errors


• To handle application-specific logic (e.g., InvalidAgeException,
InsufficientFundsException)
• To separate business errors from system errors

🔸 Steps to Create a Custom Exception

✅ 1. Extend the Exception or RuntimeException class


class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}}

Use Exception for checked exception, RuntimeException for unchecked.

✅ 2. Use throw to Raise It


public class TestCustomException {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is less than 18 — Not allowed");
} else {
[Link]("Valid age — Access granted.");
}}

public static void main(String[] args) {


try {
validateAge(16);
} catch (InvalidAgeException e) {
[Link]("Caught Exception: " + [Link]());
}}}

🔁 Output:
Caught Exception: Age is less than 18 — Not allowed

🔸 Another Example: InsufficientFundsException


class InsufficientFundsException extends Exception {
public InsufficientFundsException(String msg) {
super(msg);
}}
class Bank {
int balance = 5000;
void withdraw(int amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not enough balance!");
} else {
balance -= amount;
[Link]("Withdrawal successful! Remaining: " + balance);
}}}
public class Test {
public static void main(String[] args) {
Bank b = new Bank();
try {
[Link](6000);
} catch (InsufficientFundsException e) {
[Link]("Error: " + [Link]());
}}}
--------------------------------------------------------------------------------------
82. Ducking Exception

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
}

📌 Example: Ducking a Checked Exception


import [Link].*;

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]();
}

public static void main(String[] args) {


try {
readFile(); // caller handles the exception
} catch (IOException e) {
[Link]("Exception caught in main: " + [Link]());
}}}

🔹 Why Duck Exceptions?

• To delegate responsibility to a higher-level method.


• Keeps code clean in lower-level methods.
• Often used in library methods or frameworks.
✅ Key Points:
Feature Description
throw Actually throws an exception
throws Declares an exception to be handled later
Ducking applies to Checked exceptions only
Handled by The caller of the method

⚠️ 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.

You might also like