Interface in Java:
An interface says what methods a class should have.
The class decides how to implement those methods.
Example 1: Very Simple Interface
// An interface is just a list of rules (methods)
interface Animal
{
void eat();
void sleep();
}
// A class must follow the rules if it "implements" the interface
class Dog implements Animal
{
public void eat()
{
System.out.println("Dog eats bones");
}
public void sleep()
{
System.out.println("Dog sleeps in kennel");
}
}
public class Main
{
public static void main(String[] args)
{
Animal a = new Dog(); // Use the interface reference
a.eat(); // Dog eats bones
a.sleep(); // Dog sleeps in kennel
}
}
What’s happening here?
1. interface Animal
o Says: every animal must have eat() and sleep() methods.
o But it does not say how.
2. class Dog implements Animal
o Dog promises: "Yes, I will provide my own code for eat() and sleep()."
3. Output
Dog eats bones
Dog sleeps in kennel
Why use interfaces?
To define rules that many classes can follow.
To achieve multiple inheritance (a class can follow many contracts).
To make code more flexible and organized.
Scope of variables
1. Instance Variables
Declared inside a class, but outside any method/constructor/block.
Belong to an object.
Each object has its own copy of instance variables.
Get default values if not initialized.
Example:
class Student {
// Instance variables
String name;
int age;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Amit";
s1.age = 20;
Student s2 = new Student();
s2.name = "Riya";
s2.age = 22;
s1.display(); // Name: Amit, Age: 20
s2.display(); // Name: Riya, Age: 22
}
}
Here, each Student object has its own name and age.
2. Class Variables (Static Variables)
Declared with the static keyword.
Shared by all objects of the class (only one copy exists).
Belong to the class, not to objects.
Can be accessed using class name.
Example:
class Counter {
// Static variable (class variable)
static int count = 0;
Counter() {
count++; // Increases whenever an object is created
}
void showCount() {
System.out.println("Object Count = " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
c1.showCount(); // Object Count = 3
c2.showCount(); // Object Count = 3
c3.showCount(); // Object Count = 3
// Access directly using class name
System.out.println("Total objects: " + Counter.count); // 3
}
}
✅ Here, count is shared by all objects.
3. Local Variables
Declared inside a method, constructor, or block.
Exist only during method execution.
Must be initialized before use (no default values).
Example:
class Calculator {
void addNumbers() {
// Local variables
int a = 5;
int b = 10;
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.addNumbers(); // Sum = 15
// System.out.println(a); ❌ ERROR - 'a' is local to addNumbers()
}
}
Variables a, b, and sum only exist inside the method addNumbers().
Java program on Logical oprartors:
class LogicalOperatorsDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;
// Logical AND (&&)
System.out.println("a > 5 && b > 15 : " + (a > 5 && b > 15));
// Logical OR (||)
System.out.println("a > 15 || b > 15 : " + (a > 15 || b > 15));
// Logical NOT (!)
System.out.println("!(a > b) : " + !(a > b));
}
}
Java Program on Assignment Operators :
class AssignmentOperatorsDemo
{
public static void main(String[] args)
{
int a = 10;
System.out.println("Initial value of a: " + a);
// Using +=
a += 5; // same as a = a + 5
System.out.println("After a += 5 : " + a);
// Using -=
a -= 3; // same as a = a - 3
System.out.println("After a -= 3 : " + a);
// Using *=
a *= 2; // same as a = a * 2
System.out.println("After a *= 2 : " + a);
// Using /=
a /= 4; // same as a = a / 4
System.out.println("After a /= 4 : " + a);
// Using %=
a %= 3; // same as a = a % 3
System.out.println("After a %= 3 : " + a);
}
}
CONDITIONAL OPERATOR
The conditional operator in Java is also known as the ternary operator because it works with three
operands.
It is a shorthand way of writing an if-else statement.
👉 Syntax:
condition ? expression1 : expression2;
condition → a boolean expression (true or false)
expression1 → value that gets returned if the condition is true
expression2 → value that gets returned if the condition is false
1) Find the larger of two numbers
public class ConditionalOperatorExample
{
public static void main(String[] args)
{
int a = 10, b = 20;
// Using conditional operator
int max = (a > b) ? a : b;
System.out.println("The larger number is: " + max);
}
}
Output:
The larger number is: 20
2) Java program to Check even or odd
Public class EvenOdd
{
public static void main(String[] args)
{
int num = 7;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(num + " is " + result);
}
}
Output:
7 is Odd
Bitwise Operators in Java
Bitwise operators work directly on bits (0s and 1s) of integer values.
They are mostly used in low-level programming, encryption, networking, and optimization.
👉 Types of Bitwise Operators
Operator Symbol Meaning Example (for a=5, b=3)
AND & Bitwise AND 5&3=1
OR | Bitwise OR 5|3=7
Bitwise XOR (exclusive
XOR ^ OR) <same bits = 0, else 1 5 ^ 3 = 6
in truth table>
Bitwise complement (flips
NOT ~ bits) < 0’s becomes 1 and ~5 = -6
1’s becomes 0’s>
Left Shift << Shifts bits left, adds 0s 5 << 1 = 10
Shifts bits right, keeps
Right Shift >> 5 >> 1 = 2
sign
Example Program: Bitwise Operators in Java
public class BitwiseExample {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
System.out.println("a & b = " + (a & b)); // AND
System.out.println("a | b = " + (a | b)); // OR
System.out.println("a ^ b = " + (a ^ b)); // XOR
System.out.println("~a = " + (~a)); // NOT
System.out.println("a << 1 = " + (a << 1));// Left shift
System.out.println("a >> 1 = " + (a >> 1));// Right shift
}
}
✅ Output:
a & b = 1
a | b = 7
a ^ b = 6
~a = -6
a << 1 = 10
a >> 1 = 2
🔎 Quick Explanation:
5 = 0101 (binary), 3 = 0011
AND (&) → 0101 & 0011 = 0001 → 1
OR (|) → 0101 | 0011 = 0111 → 7
XOR (^) → 0101 ^ 0011 = 0110 → 6
NOT (~5) → flips bits of 0101 → gives -6 in 2’s complement
Left shift (5 << 1) → 0101 → 1010 → 10
Right shift (5 >> 1) → 0101 → 0010 → 2
Special Operators in Java
1. instanceof Operator
Used to test whether an object is an instance of a particular class or subclass.
Returns a boolean (true or false).
✅ Example:
class Animal
{
class Dog extends Animal
{
public class Example
{
public static void main(String[] args)
{
Dog d = new Dog();
System.out.println(d instanceof Dog); // true
System.out.println(d instanceof Animal); // true
System.out.println(d instanceof Object); // true
}
}
}
}
2. Dot (.) Operator
Used to:
o Access class members (variables, methods).
o Access packages.
✅ Example:
public class Example
{
public static void main(String[] args)
{
String s = "Hello";
int length1 = s.length(); // using . operator
System.out.println("Length = " + length1);
}
}
OUTPUT: Length = 5
Types of Type Conversion in Java
1. Automatic Type Conversion (Type Promotion / Implicit Conversion)
Happens automatically when:
o A smaller data type is assigned to a bigger data type.
o Example: int → long → float → double
Called widening conversion because no data is lost.
public class AutoConversion {
public static void main(String[] args) {
int a = 10;
double b = a; // int automatically converted to double
System.out.println("a = " + a);
System.out.println("b = " + b);
}
Explicit Type Conversion (Casting)
Done manually using cast operator (type).
Used when converting from larger type → smaller type (possible data loss).
✅ Example:
public class ExplicitCasting {
public static void main(String[] args) {
double d = 9.78;
int i = (int) d; // manually casting double to int
System.out.println("Double value = " + d);
System.out.println("Integer value = " + i);
}
}
Output:
Double value = 9.78
Integer value = 9
4. Generic Type Casting in Expressions
Sometimes we use casting inside expressions to control result type.
✅ Example:
public class CastingInExpression {
public static void main(String[] args) {
int a = 7, b = 2;
// Without casting → integer division
System.out.println("Integer division: " + (a / b)); // 3
// With casting → floating point division
System.out.println("Floating division: " + ((double) a / b)); // 3.5
}
}
1. What is Operator Precedence?
Precedence decides which operator is evaluated first in an expression when there are multiple
operators.
Example:
int result = 10 + 5 * 2;
Here, * (multiplication) has higher precedence than +.
So:
5 * 2 = 10 → 10 + 10 = 20.
🔹 2. What is Associativity?
Associativity decides the order of evaluation when two operators have the same precedence.
It can be:
o Left-to-Right (most operators in Java)
o Right-to-Left (assignment =, ternary ?:, etc.)
Example:
int result = 100 / 10 * 2;
Both / and * have same precedence and are left-to-right associative.
So it is evaluated as: (100 / 10) * 2 = 10 * 2 = 20.
If it were right-to-left, it would be 100 / (10 * 2) = 100 / 20 = 5.
🔹 3. Operator Precedence Table (Highest → Lowest)
Precedence Operators Associativity
1 (highest) () (parentheses), [] (array), . (member access) Left-to-Right
2 ++ -- (postfix) Left-to-Right
3 ++ -- (prefix), + - (unary), ! (logical NOT), ~ (bitwise NOT), type cast Right-to-Left
4 */% Left-to-Right
5 +- Left-to-Right
6 << >> >>> (shift) Left-to-Right
7 < <= > >= instanceof Left-to-Right
8 == != Left-to-Right
9 & (bitwise AND) Left-to-Right
10 ^ (bitwise XOR) Left-to-Right
11 ` ` (bitwise OR)
12 && (logical AND) Left-to-Right
13 `
14 ?: (ternary) Right-to-Left
15 (lowest) = += -= *= /= etc. Right-to-Left
🔹 4. Examples
Example 1: Precedence
class Example1 {
public static void main(String[] args) {
int a = 10 + 5 * 2;
System.out.println(a);
}
}
Output:
20
(Multiplication first, then addition)
Example 2: Associativity
class Example2 {
public static void main(String[] args) {
int a = 100 / 10 * 2;
System.out.println(a);
}
}
Output:
20
(Division and multiplication → left to right)
Example 3: Right-to-Left Associativity
class Example3 {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
a = b = c; // Assignment is right-to-left
System.out.println(a + " " + b + " " + c);
}
}
Output:
30 30 30
✅ In short:
Precedence → which operator first.
Associativity → which direction (left/right) when same precedence.
Simple If Statement, If…..Else Statement, Nested If Statement, Else……. If Ladder
ststement.
1. Simple if statement
Executes a block of code only if the condition is true.
public class SimpleIfExample {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
System.out.println("Program ends.");
}
}
Output:
You are eligible to vote.
Program ends.
2. if...else statement
If condition is true → execute if block, otherwise → else block.
public class IfElseExample {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
✅ Output:
7 is Odd.
3. Nested if...else statement
An if inside another if (used when multiple conditions must be checked).
public class NestedIfExample {
public static void main(String[] args) {
int marks = 85;
if (marks >= 40) {
if (marks >= 75) {
System.out.println("Passed with Distinction!");
} else {
System.out.println("Passed!");
}
} else {
System.out.println("Failed!");
}
}
}
Output:
Passed with Distinction!
4. The Else If Ladder
It is a way to check many conditions one by one.
Think like this:
First check condition 1.
If it is true → do something and stop.
If not true → check condition 2.
If not true → check condition 3.
If none are true → do the final else.
That’s why it looks like a ladder of conditions.
Example
Imagine you want to say a student’s grade based on marks:
If marks ≥ 85 → Grade A
Else if marks ≥ 70 → Grade B
Else if marks ≥ 50 → Grade C
Else if marks ≥ 35 → Grade D
Else → Fail
Java Program
public class ElseIfLadderExample
{
public static void main(String[] args)
{
int marks = 72; // student marks
if (marks >= 85)
{
System.out.println("Grade: A");
}
else if (marks >= 70)
{
System.out.println("Grade: B");
}
else if (marks >= 50)
{
System.out.println("Grade: C");
}
else if (marks >= 35)
{
System.out.println("Grade: D");
}
else
{
System.out.println("Grade: Fail");
}
}
}
Step-by-step execution when marks = 72
1. First condition: if (marks >= 85) → 72 ≥ 85? ❌ False → Skip
2. Next: else if (marks >= 70) → 72 ≥ 70? ✅ True → Print "Grade: B"
3. Program stops checking further conditions.
4. Output will be:
Grade: B
Flow (like a ladder)
Is marks ≥ 85 ? → Yes → A
↓ No
Is marks ≥ 70 ? → Yes → B
↓ No
Is marks ≥ 50 ? → Yes → C
↓ No
Is marks ≥ 35 ? → Yes → D
↓ No
Fail
Switch Statements
A switch statement in Java is a multi-way branch statement. It allows a variable (or expression) to be
tested against a list of values, and based on the match, executes the corresponding block of code.
It works like an alternative to multiple if…else-if statements.
Syntax of Switch Statement
switch (expression)
{
case value1:
// code block
break;
case value2:
// code block
break;
...
case valueN:
// code block
break;
default:
// default block (optional)
}
Working of Switch Statements:
1. The expression inside switch is evaluated once.
2. Its result is compared with each case value.
3. If a match is found, the code inside that case runs.
4. The break statement stops the execution from falling into the next case.
5. If no case matches, the default block executes (if provided).
public class SwitchExample
{
public static void main(String[] args)
{
int day = 3;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Wednesday
Example with string
public class SwitchStringExample
{
public static void main(String args[])
{
String fruit = "Mango";
switch(fruit)
{
case "Apple":
System.out.println("Red fruit");
break;
case "Mango":
System.out.println("King of fruits");
break;
case "Banana":
System.out.println("Yellow fruit");
break;
default:
System.out.println("Unknown fruit");
}
}
}
Output:
King of fruits
Looping Statements in Java
Definition:
Looping statements in Java are used to execute a block of code repeatedly as long as a certain condition
is true.
Instead of writing the same code many times, loops allow us to execute it multiple times automatically.
Types of Loops in Java
Java provides three main looping statements:
1. for loop
2. while loop
3. do...while loop
1. for Loop
Used when the number of iterations is known in advance.
Syntax:
for(initialization; condition; update)
{
// code to be executed
}
Initialization → sets the starting value of the loop variable.
Condition → checked before every iteration; if false, loop stops.
Update → modifies the loop variable after each iteration.
Example: Print numbers 1 to 5
public class ForLoopExample
{
public static void main(String[] args)
{
for(int i = 1; i <= 5; i++)
{
System.out.println("Number: " + i);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example - Print Even Numbers from 2 to 10
public class ForLoopExample
{
public static void main(String[] args)
{
System.out.println("Even numbers from 2 to 10:");
for(int i = 2; i <= 10; i += 2)
{
System.out.println(i);
}
}
}
Output
Even numbers from 2 to 10:
2
4
6
8
10
2.while Loop
Used when the number of iterations is not known in advance. The condition is checked before each
iteration.
Syntax:
while(condition)
{
// code to be executed
}
Example - Calculate the Sum of First 5 Natural Numbers
public class WhileLoopExample
{
public static void main(String[] args)
{
int i = 1, sum = 0;
while(i <= 5)
{
sum += i; // add i to sum
i++;
}
System.out.println("Sum of first 5 numbers = " + sum);
}
}
Output:
Sum of first 5 numbers = 15
3. do...while Loop
a) Similar to while loop, but the condition is checked after the loop body.
b) So, the loop runs at least once, even if the condition is false.
Syntax:
do
{
// code to be executed
} while(condition);
Example: Print numbers 1 to 5
public class DoWhileLoopExample
{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println("Number: " + i);
i++;
} while(i <= 5);
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Jumps in Loops in Java
Definition
Jumps in loops are control flow statements in Java that allow us to alter the normal
execution sequence of a loop.
They can:
Skip the remaining part of the current iteration.
Terminate the loop prematurely.
Transfer control to another part of the program.
Types of Jump Statements in Java
Java provides 2 jump statements that are commonly used with loops:
1. break
2. continue
1. break Statement
The break statement is used to terminate a loop immediately, regardless of whether the
loop’s condition is true or not.
Control is transferred to the statement just after the loop.
Syntax:
break;
Example: Breaking a loop
public class BreakExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // loop stops when i = 5
}
System.out.println("i = " + i);
}
}
}
Output:
i = 1
i = 2
i = 3
i = 4
The loop stops when i == 5.
2. continue Statement
The continue statement is used to skip the current iteration of the
loop and jump to the next iteration.
Syntax:
continue;
Example: Skipping specific values
public class ContinueExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // skip when i = 3
}
System.out.println("i = " + i);
}
}
}
Output:
i = 1
i = 2
i = 4
i = 5
When i == 3, the loop skips printing.
The concepts of object and class with a suitable Java program
• Class is the core of Java language.
• It can be defined as a template that describe the behaviors and states of a particular
entity. • A class defines new data type. Once defined this new type can be used to create
object of that type.
• Object is an instance of class.
• A class contain both data and methods that operate on that data.
• The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods.
• Thus, the instance variables and methods are known as class members.
Java class Syntax
class class_name
{
field;
method;
}
Java Object Syntax
className variable_name = new className();
JAVA PROGRAM
Constructors
Definition
A constructor in Java is a special method used to initialize objects.
It looks like a method, but:
It has the same name as the class.
It does not have a return type (not even void).
It is automatically called when you create an object using new.
Key Points
1. Constructors are used to set initial values for object variables.
2. If you don’t write any constructor, Java provides a default constructor automatically.
3. You can create multiple constructors in the same class (this is called constructor overloading).
Types of Constructors in Java
1. Default Constructor
A constructor with no parameters.
If you don’t define any constructor, Java automatically provides one.
Example:
class Student
{
String name;
int age;
// Default constructor
Student()
{
name = "Unknown";
age = 0;
}
void display()
{
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Example1
{
public static void main(String[] args)
{
Student s1 = new Student(); // calls default constructor
s1.display();
}
}
Output:
Name: Unknown, Age: 0
2. Parameterized Constructor
A constructor that takes arguments to initialize values.
Example:
class Student
{
String name;
int age;
// Parameterized constructor
Student(String n, int a)
{
name = n;
age = a;
}
void display()
{
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Example2
{
public static void main(String[] args)
{
Student s1 = new Student("Arun", 21);
Student s2 = new Student("Meera", 20);
s1.display();
s2.display();
}
}
Output:
Name: Arun, Age: 21
Name: Meera, Age: 20
3. Constructor Overloading
A class can have multiple constructors with different parameter lists.
Java decides which constructor to call based on arguments passed.
Example:
class Student
{
String name;
int age;
// Default constructor
Student()
{
name = "Unknown";
age = 0;
}
// Parameterized constructor (1 parameter)
Student(String n)
{
name = n;
age = 0;
}
// Parameterized constructor (2 parameters)
Student(String n, int a)
{
name = n;
age = a;
}
void display()
{
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Example3
{
public static void main(String[] args)
{
Student s1 = new Student();
Student s2 = new Student("Kiran");
Student s3 = new Student("Divya", 22);
s1.display();
s2.display();
s3.display();
}
}
Output:
Name: Unknown, Age: 0
Name: Kiran, Age: 0
Name: Divya, Age: 22
Difference between Constructor and Method
Feature Constructor Method
Name Same as class name Any name
Return type No return type (not even void) Must have a return type
When called Automatically when object is created Must be called explicitly
Purpose To initialize object To perform some action
Method Overloading
Definition
Method Overloading in Java means defining multiple methods with the same name in a class but
with different parameter lists.
The method name is the same.
The number of parameters or type of parameters must be different.
The return type can be the same or different, but it alone cannot differentiate overloaded
methods.
In simple words: Same method name, but different inputs.
Key Points
1. It increases readability and code reusability.
2. It is an example of Compile-Time Polymorphism (decided at compile time).
3. Overloading is done by:
o Changing the number of parameters.
o Changing the type of parameters.
Easy Example
class Calculator
{
// Method 1: Add two integers
int add(int a, int b)
{
return a + b;
}
// Method 2: Add three integers (different number of parameters)
int add(int a, int b, int c)
{
return a + b + c;
}
// Method 3: Add two double values (different type of parameters)
double add(double a, double b)
{
return a + b;
}
}
public class MethodOverloadingExample
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
System.out.println("Sum of 2 integers: " + calc.add(10, 20));
// calls method 1
System.out.println("Sum of 3 integers: " + calc.add(10, 20, 30));
// calls method 2
System.out.println("Sum of 2 doubles: " + calc.add(5.5, 4.5));
// calls method 3
}
}
Output
Sum of 2 integers: 30
Sum of 3 integers: 60
Sum of 2 doubles: 10.0
Explanation
When you call calc.add(10, 20), the compiler looks for a method with two int parameters
→ calls method 1.
When you call calc.add(10, 20, 30), it finds a method with three int parameters → calls
method 2.
When you call calc.add(5.5, 4.5), it finds a method with two double parameters → calls
method 3.
So, the same method name add behaves differently based on the arguments.
Example 1: Concatenation using Overloading
class StringOverload1
{
// concatenate two strings
String join(String a, String b)
{
return a + b;
}
// concatenate three strings
String join(String a, String b, String c)
{
return a + b + c;
}
public static void main(String[] args)
{
StringOverload1 obj = new StringOverload1();
System.out.println("Two strings: " + obj.join("Hello", "World"));
System.out.println("Three strings: " + obj.join("Java", " is ", "Powerful"));
}
}
OUTPUT:
Two strings: HelloWorld
Three strings: Java is Powerful
STATIC MEMBERS
In Java, a static member means it belongs to the class itself, not to individual objects.
Static variables → shared by all objects of the class.
Static methods → can be called without creating an object.
Static blocks → used for initializing static variables.
So, if something is static, it exists only once for the whole class, not separately for each object.
Real life example:
Imagine a School Example
1. Each student has their own name.
o This is a normal (non-static) variable.
o Example: Rahul’s name = “Rahul”, Priya’s name = “Priya”.
2. But all students study in the same school.
o This is a static variable (shared by everyone).
o Example: School name = “ABC School”.
class Student
{
String name; // Each student has own name
static String schoolName = "ABC School"; // Shared by ALL students
}
public class TestStatic
{
public static void main(String[] args)
{
Student s1 = new Student();
s1.name = "Rahul";
Student s2 = new Student();
s2.name = "Priya";
// Print names and school
System.out.println(s1.name + " studies in " + Student.schoolName);
System.out.println(s2.name + " studies in " + Student.schoolName);
// Change school name (static variable)
Student.schoolName = "XYZ School";
System.out.println(s1.name + " studies in " + Student.schoolName);
System.out.println(s2.name + " studies in " + Student.schoolName);
}
}
Output
Rahul studies in ABC School
Priya studies in ABC School
Rahul studies in XYZ School
Priya studies in XYZ School
Explanation in Simple Words
name → Each student has their own (Rahul, Priya).
schoolName → Only one copy exists for all students. If it changes once, it changes for everyone.
Static Method Example
Like a calculator in the school office.
Any student can use it, no need to create their own.
class Calculator
{
static int add(int a, int b)
{
return a + b;
}
}
public class TestStaticMethod
{
public static void main(String[] args)
{
System.out.println(Calculator.add(5, 3)); // 8
}
}
We don’t create a Calculator object; we just call it directly.
Static variable → one value for all objects (school name).
Static method → can be used without object (calculator).
Nesting of Methods
Nesting of methods means calling one method inside another method within the same class.
It helps to reuse code instead of writing the same logic again.
Methods work together like building blocks.
Example: Nesting of Methods
class NestingExample
{
// Method 1: checks if a number is even
int isEven(int num)
{
if (num % 2 == 0)
return 1; // return 1 if even
else
return 0; // return 0 if odd
}
// Method 2: calls isEven() to check and display result
void checkNumber(int num)
{
if (isEven(num) == 1)
{ // calling method inside another
System.out.println(num + " is Even");
} else {
System.out.println(num + " is Odd");
}
}
public static void main(String[] args)
{
NestingExample obj = new NestingExample();
obj.checkNumber(10); // Calls checkNumber(), which calls isEven()
obj.checkNumber(7); // Nested call happens again
}
}
Output:
10 is Even
7 is Odd
Explanation:
1. isEven(int num) → checks if number is even or odd.
2. checkNumber(int num) → instead of repeating the check, it calls isEven() inside
it.
3. In main(), when obj.checkNumber(10) runs:
o checkNumber() is called
o Inside it → isEven() is called
o Based on result, it prints whether the number is even or odd.
So, one method is nested inside another.
INHERITANCE IN JAVA
Definition
Inheritance in Java is a mechanism by which one class (child / subclass / derived class) can acquire
the properties and behaviors (fields and methods) of another class (parent / superclass / base class).
It allows code reusability and helps implement polymorphism.
Superclass: The class whose features are inherited.
Subclass: The class that inherits from another class using the “extends” keyword.
Syntax
class Parent
{
// fields and methods
}
class Child extends Parent
{
// additional fields and methods
}
Types of Inheritance in Java
Java supports the following types of inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
1. Single Inheritance
One class inherits another class.
Example: Child inherits from Parent.
Example Program
class Parent
{
void displayParent()
{
System.out.println("This is the Parent class.");
}
}
class Child extends Parent
{
void displayChild()
{
System.out.println("This is the Child class.");
}
}
public class SingleInheritanceDemo
{
public static void main(String[] args)
{
Child obj = new Child();
obj.displayParent(); // inherited method
obj.displayChild(); // child method
}
}
Output:
This is the Parent class.
This is the Child class.
2. Multilevel Inheritance
A class inherits from another class, and then another class inherits from it.
Example: Grandchild ← Child ← Parent.
Example Program
class GrandParent
{
void displayGrandParent()
{
System.out.println("This is the GrandParent class.");
}
}
class Parent extends GrandParent
{
void displayParent()
{
System.out.println("This is the Parent class.");
}
}
class Child extends Parent
{
void displayChild()
{
System.out.println("This is the Child class.");
}
}
public class MultilevelInheritanceDemo
{
public static void main(String[] args)
{
Child obj = new Child();
obj.displayGrandParent();
obj.displayParent();
obj.displayChild();
}
}
Output:
This is the GrandParent class.
This is the Parent class.
This is the Child class.
3. Hierarchical Inheritance
Multiple classes inherit from the same parent.
Example: Child1 and Child2 inherit from Parent.
Example Program
class Parent
{
void displayParent()
{
System.out.println("This is the Parent class.");
}
}
class Child1 extends Parent
{
void displayChild1()
{
System.out.println("This is Child1 class.");
}
}
class Child2 extends Parent
{
void displayChild2()
{
System.out.println("This is Child2 class.");
}
}
public class HierarchicalInheritanceDemo
{
public static void main(String[] args)
{
Child1 obj1 = new Child1();
obj1.displayParent();
obj1.displayChild1();
Child2 obj2 = new Child2();
obj2.displayParent();
obj2.displayChild2();
}
}
Output:
This is the Parent class.
This is Child1 class.
This is the Parent class.
This is Child2 class.
4. Multiple Inheritance (with Interfaces)
Java does not support multiple inheritance with classes.
But, with interfaces, it is possible.
Multiple Inheritance means that a class can inherit features from more than one parent class.
Example
interface X
{
void methodX();
}
interface Y
{
void methodY();
}
class Z implements X, Y
{
public void methodX()
{
System.out.println("Method from Interface X");
}
public void methodY()
{
System.out.println("Method from Interface Y");
}
}
public class MultipleInheritanceDemo
{
public static void main(String[] args)
{
Z obj = new Z();
obj.methodX();
obj.methodY();
}
}
OUTPUT:
Method from Interface X
Method from Interface Y
Method Overriding
Definition:
Method overriding occurs when a subclass (child class) provides a specific implementation of
a method that is already defined in its superclass (parent class).
The method in the subclass must have:
1. Same name
2. Same parameter list
3. Same or covariant return type
Rules for Method Overriding
1. Inheritance is required – overriding happens between parent and child classes.
2. Method signature (name + parameters) must be exactly the same.
3. The access modifier in the child class should not be more restrictive.
o Example: If parent method is public, child method cannot be private.
4. Static methods cannot be overridden (they are hidden instead).
5. Constructors cannot be overridden.
6. Final methods cannot be overridden.
Example:
class Animal
{
void sound()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal // Child class
void sound() // overriding parent method
{
System.out.println("Dog barks");
}
}
// Main class
public class MethodOverridingExample
{
public static void main(String[] args)
{
Animal a = new Animal(); // reference of Animal
a.sound(); // Output: Animal makes a sound
Animal b = new Dog();
b.sound(); // Output: Dog barks (runtime polymorphism)
}
}
Example:
// Parent class
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
// Child class
class Bike extends Vehicle
{
void run()
{ // overriding parent method
System.out.println("Bike is running safely");
}
}
// Main class
public class TestOverride
{
public static void main(String[] args)
{
Vehicle v = new Bike(); // object of Bike but reference of Vehicle
v.run(); // Output: Bike is running safely
}
}