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

Java Complete

Uploaded by

rk5428832
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 views52 pages

Java Complete

Uploaded by

rk5428832
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

🔹 Introduction to Java

●​ Java is an object-oriented programming language developed by Sun Microsystems


(now owned by Oracle).
●​ It is platform-independent, meaning code written in Java can run anywhere using the
Java Virtual Machine (JVM).
●​ Java is widely used in:
o​ Web applications
o​ Mobile apps (Android)
o​ Enterprise software
o​ Game development

🔹 Features of Java
1.​ Simple – Easy to learn if you know C/C++ or other languages.
2.​ Object-Oriented – Everything revolves around classes and objects.
3.​ Platform-Independent – "Write once, run anywhere."
4.​ Secure – Provides strong security for applications.
5.​ Robust – Has strong memory management.
6.​ Multithreaded – Can perform multiple tasks at once.

🔹 Java Basics
Before coding, you should understand these:

1. Java Structure

A basic Java program looks like this:

public class MyFirstProgram {


public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}

👉 Breakdown:
●​ class → Every program must be inside a class.
●​ public static void main(String[] args) → Entry point of the program.
●​ System.out.println() → Used to print text on the screen.
2. Java Rules

●​ File name must match the class name. (e.g., MyFirstProgram.java)


●​ Java is case-sensitive (Hello ≠ hello).
●​ Statements end with semicolon (;).
●​ Curly braces { } define blocks of code.

3. Java Variables

Variables are used to store data.

int age = 27; // integer


double price = 99.5; // decimal number
char grade = 'A'; // single character
String name = "Rukhsar"; // text
boolean isStudent = true; // true or false

4. Java Data Types

●​ Primitive types: int, float, double, char, boolean, byte, short, long.
●​ Non-primitive types: String, Arrays, Objects, etc.

🔹 1. JDK, JRE, and JVM


These three terms confuse most beginners, so let’s simplify:

JVM (Java Virtual Machine)

●​ The heart of Java!


●​ It runs Java programs by converting compiled code (bytecode) into machine code.
●​ JVM makes Java platform-independent ("Write once, run anywhere").

JRE (Java Runtime Environment)

●​ Contains the JVM + libraries needed to run Java programs.


●​ If you only want to run Java apps, you just need JRE.
JDK (Java Development Kit)

●​ Contains JRE + development tools (compiler, debugger, etc.).


●​ Required for writing and compiling Java programs.
●​ Example: javac (compiler) converts .java → .class (bytecode).

👉 As a developer, you need the JDK installed.

🔹 2. Package
●​ A package in Java is a way to group classes together.
●​ Think of it like a folder in your computer that organizes files.

Example:

package university; // package name (like a folder)

public class Student {


String name;
int age;
}

●​ Java has built-in packages (like java.util, java.io).


●​ Example:

import java.util.Scanner; // importing package

🔹 3. Class
●​ A class is a blueprint for creating objects.
●​ It defines properties (variables) and behaviors (methods).

Example:

public class Car {


String color; // property
int speed; // property

void drive() { // method


System.out.println("The car is driving.");
}
}
🔹 4. Object
●​ An object is an instance of a class (real-world example).

Example:

public class CarExample {


public static void main(String[] args) {
Car myCar = new Car(); // create an object
myCar.color = "Red";
myCar.speed = 100;

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


myCar.drive();
}
}

🔹 5. Method
●​ A method is a function inside a class that performs some action.

Example:

public class MathOperations {


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

✅ To summarize:
●​ JDK = Tools + JRE → For developers.
●​ Package = Folder to organize classes.
●​ Class = Blueprint.
●​ Object = Instance of class.
●​ Method = Function inside a class.

🔹 1. Java Hello World Program


This is always the first program in Java.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}

👉 Explanation:
}
●​ public class HelloWorld → class name (must match file name HelloWorld.java).
●​ main method → Starting point of every Java program.
●​ System.out.println() → prints text on the screen.
📌 Output:
Hello, World!

🔹 2. Java Variables
Variables are used to store values (like a box with a name).
Example:
public class VariablesExample {
public static void main(String[] args) {
int age = 27; // integer (whole number)
double height = 6.0; // decimal number
String name = "Rukhsar"; // text
boolean isStudent = true; // true or false

System.out.println("Name: " + name);


System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Is Student? " + isStudent);
}

📌 Output:
}

Name: Rukhsar
Age: 27
Height: 6.0
Is Student? true

🔹 3. Arithmetic Operators
Java can perform basic math operations using operators:
Operator Meaning Example (a=10, b=5) Result

+ Addition a + b 15

- Subtraction a - b 5

* Multiplication a * b 50

/ Division a / b 2

% Modulus (remainder) a % b 0

Example Program:
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10;
int b = 5;

System.out.println("Addition: " + (a + b));


System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Remainder: " + (a % b));
}

📌 Output:
}

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Remainder: 0

🔹 1. The
●​
Scanner Class
Java provides a Scanner class (in java.util package) to take input from the user.
●​ First, you must import it:
import java.util.Scanner;

🔹 2. Example: Taking Input


import java.util.Scanner; // importing Scanner class

public class UserInputExample {


public static void main(String[] args) {
Scanner input = new Scanner(System.in); // create scanner object

System.out.print("Enter your name: ");


String name = input.nextLine(); // reads text input

System.out.print("Enter your age: ");


int age = input.nextInt(); // reads integer input

System.out.println("Hello " + name + ", you are " + age + " years
old!");
}

📌 Example Run:
}

Enter your name: Rukhsar


Enter your age: 27
Hello Rukhsar, you are 27 years old!
🔹 3. Example: Arithmetic with User Input
import java.util.Scanner;

public class CalculatorExample {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter first number: ");


int a = input.nextInt();

System.out.print("Enter second number: ");


int b = input.nextInt();

System.out.println("Addition: " + (a + b));


System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Remainder: " + (a % b));
}

📌 Example Run:
}

Enter first number: 20


Enter second number: 7
Addition: 27
Subtraction: 13
Multiplication: 140
Division: 2
Remainder: 6

🔹 Why OOP is Beneficial?


OOP helps us organize code like real life.​
Instead of writing messy functions and variables everywhere, we group related data + actions
inside objects and classes.

🔹 Real-Life Examples
1. Car Example
●​ A Car has:
o​ Properties → color, brand, speed.
o​ Methods → start(), stop(), drive().
In OOP, we make a Car class.​
Then we can create many cars (Toyota, Honda, BMW) without rewriting code.
👉 Benefit: Reusability (don’t write code again and again).
2. University Student Example
●​ A Student has:
o​ Properties → name, rollNo, marks.
o​ Methods → study(), giveExam(), getResult().
We create a Student class, and then objects like:
●​ Student 1: Ali, rollNo 101.
●​ Student 2: Rukhsar, rollNo 102.
👉 Benefit: Organization & Scalability (easy to handle 100s of students).
3. Bank Account Example
●​ A BankAccount has:
o​ Properties → accountNumber, balance.
o​ Methods → deposit(), withdraw(), checkBalance().
We don’t need separate code for each person’s account.​
We just create objects for each account.
👉 Benefit: Encapsulation (security — each account’s data is private).
4. Animal Example (Polymorphism)
●​ Animal class → sound().
●​ Dog → sound() = "Bark".
●​ Cat → sound() = "Meow".
When we call sound(), different animals make different sounds.
👉 Benefit: Flexibility (same code works differently for each case).
🔹 Key Benefits of OOP
1.​ Reusability → Write code once, use it many times (Car class → many cars).
2.​ Organization → Code is cleaner, easier to understand.
3.​ Scalability → Easy to add new features (e.g., add Truck class without breaking Car).
4.​ Security (Encapsulation) → Data is protected inside objects.
5.​ Real-world Modeling → Programs match real-world objects → easier to think.

✅ In short:​
OOP makes programming like real life.​
Instead of thinking in terms of boring code, you think in objects (Car, Student, Account).

🔹 1. What is an if statement?
An if statement checks a condition.
●​ If the condition is true, code inside it runs.
●​ If it’s false, code is skipped.

🔹 2. Basic if Example
public class IfExample {
public static void main(String[] args) {
int age = 20;

if (age >= 18) {


System.out.println("You are an adult.");
}
}

📌 Output:
}

You are an adult.

🔹 3. if–else
public class IfElseExample {
public static void main(String[] args) {
int age = 16;

if (age >= 18) {


System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
}

📌 Output:
}

You are a minor.


🔹 4. if–else if–else
Used when you have multiple conditions.
public class IfElseIfExample {
public static void main(String[] args) {
int marks = 75;

if (marks >= 90) {


System.out.println("Grade: A");
} else if (marks >= 75) {
System.out.println("Grade: B");
} else if (marks >= 50) {
System.out.println("Grade: C");
} else {
System.out.println("Fail");
}
}

📌 Output:
}

Grade: B

🔹 5. Using if with User Input


import java.util.Scanner;

public class IfWithInput {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter your age: ");


int age = input.nextInt();

if (age >= 18) {


System.out.println("You can vote!");
} else {
System.out.println("You cannot vote.");
}
}

📌 Example Run:
}

Enter your age: 20


You can vote!

✅ Summary:
●​ if → run code if condition true.
●​ if–else → choose between two options.
●​ if–else if–else → choose between multiple options.
🔹 1. What are Comparison Operators?
Comparison operators are used to compare two values.​
The result is always true or false (boolean).

🔹 2. List of Comparison Operators in Java


Operator Meaning Example (a = 10, b = 5) Result

== Equal to a == b false

!= Not equal to a != b true

> Greater than a > b true

< Less than a < b false

>= Greater than or equal to a >= 10 true

<= Less than or equal to b <= 5 true

🔹 3. Example Program
public class ComparisonExample {
public static void main(String[] args) {
int a = 10;
int b = 5;

System.out.println("a == b: " + (a == b));


System.out.println("a != b: " + (a != b));
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
}

📌 Output:
}

a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false

🔹 4. Using in if Statements
public class AgeCheck {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
}

📌 Output:
}

You are an adult.

✅ Summary:
●​ Use == to check equality.
●​ Use != to check not equal.
●​ Use >, <, >=, <= for number comparisons.

🔹 1. Types of Loops in Java


1.​ for loop → repeat a fixed number of times.
2.​ while loop → repeat as long as a condition is true.
3.​ do-while loop → runs at least once, then checks condition.

🔹 2. for Loop
Used when you know how many times to repeat.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Hello " + i);
}
}

📌 Output:
}

Hello 1
Hello 2
Hello 3
Hello 4
Hello 5

🔹 3. while Loop
Used when you don’t know how many times, but want to repeat while condition is true.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;

while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
}

📌 Output:
}

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

🔹 4. do-while Loop
Runs at least once, even if condition is false.
public class DoWhileExample {
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

🔹 5. Example with User Input


Print numbers from 1 to user’s choice.
import java.util.Scanner;

public class LoopWithInput {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");


int n = input.nextInt();

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


System.out.println(i);
}
}

📌 Example Run:
}

Enter a number: 5
1
2
3
4
5

✅ Summary:
●​ for loop → known number of repetitions.
●​ while loop → repeat while condition is true.
●​ do-while loop → runs at least once.

🔹 Assignments
Part A: If–Else & Comparison Operators
1.​ Write a program that takes a number from the user and checks:
o​ If it is positive, negative, or zero.
2.​ Write a program that takes a student's marks (0–100) and prints:
o​ Grade A if marks ≥ 90
o​ Grade B if marks ≥ 75
o​ Grade C if marks ≥ 50
o​ Fail otherwise.

3.​ Write a program that takes two numbers and prints the largest one.
4.​ Write a program that checks if a number is even or odd.

Part B: for Loop


5.​ Print numbers from 1 to 10 using a for loop.
6.​ Print the multiplication table of a number entered by the user.​
Example: if input = 5
7.​ 5 x 1 = 5
8.​ 5 x 2 = 10
9.​ ...
10.​5 x 10 = 50
11.​ Write a program to calculate the sum of first N numbers (user input).​
Example: if N = 5 → 1+2+3+4+5 = 15.

Part C: while Loop


8.​ Print numbers from 1 to 100 that are divisible by 5.
9.​ Write a program that takes a number and prints its reverse.​
Example: 1234 → 4321.
10.​ Write a program that calculates the factorial of a number.​
Example: 5! = 5×4×3×2×1 = 120.

Part D: do–while Loop


11.​ Ask the user to enter numbers continuously. Stop only when the user enters 0.​
Then print the sum of all numbers entered.
12.​ Make a simple guessing game:
●​ Computer stores a secret number (e.g., 7).
●​ User keeps entering guesses until correct.
●​ Print "Correct!" when matched.

✅ These assignments cover:


●​ if–else conditions
●​ comparison operators
●​ for, while, and do-while loops

🔹 Part A: If–Else & Comparison Operators


1. Positive, Negative, Zero
import java.util.Scanner;

public class PositiveNegativeZero {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();

if (num > 0) {
System.out.println("Positive");
} else if (num < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
}
}

2. Student Grade
import java.util.Scanner;

public class StudentGrade {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter marks: ");
int marks = input.nextInt();

if (marks >= 90) {


System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
}
}

3. Largest of Two Numbers


import java.util.Scanner;

public class LargestNumber {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = input.nextInt();
System.out.print("Enter second number: ");
int b = input.nextInt();

if (a > b) {
System.out.println("Largest: " + a);
} else if (b > a) {
System.out.println("Largest: " + b);
} else {
System.out.println("Both are equal");
}
}
}

4. Even or Odd
import java.util.Scanner;

public class EvenOdd {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();

if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}

🔹 Part B: for Loop


5. Print 1 to 10
public class ForLoopNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}

6. Multiplication Table
import java.util.Scanner;

public class MultiplicationTable {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();

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


System.out.println(n + " x " + i + " = " + (n * i));
}
}
}

7. Sum of First N Numbers


import java.util.Scanner;

public class SumFirstN {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter N: ");
int n = input.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}

System.out.println("Sum = " + sum);


}
}

🔹 Part C: while Loop


8. Numbers Divisible by 5
public class DivisibleBy5 {
public static void main(String[] args) {
int i = 1;
while (i <= 100) {
if (i % 5 == 0) {
System.out.println(i);
}
i++;
}
}
}

9. Reverse a Number
import java.util.Scanner;

public class ReverseNumber {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();

int reverse = 0;
while (num != 0) {
int digit = num % 10;
reverse = reverse * 10 + digit;
num /= 10;
}

System.out.println("Reversed number: " + reverse);


}
}

10. Factorial
import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();

int fact = 1;
int i = 1;
while (i <= n) {
fact *= i;
i++;
}

System.out.println("Factorial = " + fact);


}
}

🔹 Part D: do–while Loop


11. Sum Until User Enters 0
import java.util.Scanner;

public class SumUntilZero {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int num;

do {
System.out.print("Enter a number (0 to stop): ");
num = input.nextInt();
sum += num;
} while (num != 0);

System.out.println("Total Sum = " + sum);


}
}

12. Guessing Game


import java.util.Scanner;

public class GuessingGame {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int secret = 7;
int guess;

do {
System.out.print("Guess the number (1-10): ");
guess = input.nextInt();

if (guess != secret) {
System.out.println("Wrong! Try again.");
}
} while (guess != secret);

System.out.println("Correct! You guessed it.");


}
}

25-8-2025

Problem Statement
Write a Java program that manages students’ marks and does the following:

Input:

Ask the user how many students are in the class.

Use a for loop to take each student’s name and marks (0–100).

Grade System (if–else + comparison operators)

Marks ≥ 90 → Grade A

Marks ≥ 75 → Grade B

Marks ≥ 50 → Grade C

Else → Fail

While Loop (search):

After entering all students, ask the user if they want to search a student by name.

Keep asking until the user types "no".

do–while Loop (menu system):

Create a simple menu that repeats until the user chooses to exit:
1. Show all students with grades

2. Show class average marks

3. Find highest marks

4. Exit
SOLUTION

import java.util.Scanner;

public class StudentManagement {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Step 1: Input number of students


System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // to consume leftover newline

String[] names = new String[n];


int[] marks = new int[n];
String[] grades = new String[n];

// Step 2: Input student data using FOR loop


for (int i = 0; i < n; i++) {
System.out.print("Enter name of student " + (i + 1) + ": ");
names[i] = sc.nextLine();

System.out.print("Enter marks: ");


marks[i] = sc.nextInt();
sc.nextLine(); // consume newline

// Assign grade using IF-ELSE


if (marks[i] >= 90) {
grades[i] = "A";
} else if (marks[i] >= 75) {
grades[i] = "B";
} else if (marks[i] >= 50) {
grades[i] = "C";
} else {
grades[i] = "Fail";
}
}

System.out.println("\nGrades assigned successfully!\n");

// Step 3: Search student using WHILE loop


String choice;
System.out.print("Do you want to search a student? (yes/no): ");
choice = sc.nextLine();

while (choice.equalsIgnoreCase("yes")) {
System.out.print("Enter name to search: ");
String searchName = sc.nextLine();
boolean found = false;

for (int i = 0; i < n; i++) {


if (names[i].equalsIgnoreCase(searchName)) {
System.out.println(names[i] + " got " + marks[i] + " marks
→ Grade: " + grades[i]);
found = true;
break;
}
}

if (!found) {
System.out.println("Student not found.");
}

System.out.print("Do you want to search again? (yes/no): ");


choice = sc.nextLine();
}

// Step 4: Menu system using DO-WHILE loop


int option;
do {
System.out.println("\n---- MENU ----");
System.out.println("1. Show all students with grades");
System.out.println("2. Show class average marks");
System.out.println("3. Find highest marks");
System.out.println("4. Exit");
System.out.print("Enter choice: ");
option = sc.nextInt();

switch (option) {
case 1:
for (int i = 0; i < n; i++) {
System.out.println(names[i] + " → " + marks[i] + " →
Grade " + grades[i]);
}
break;

case 2:
int sum = 0;
for (int i = 0; i < n; i++) {
sum += marks[i];
}
double avg = (double) sum / n;
System.out.println("Class average marks = " + avg);
break;

case 3:
int maxMarks = marks[0];
String topper = names[0];
for (int i = 1; i < n; i++) {
if (marks[i] > maxMarks) {
maxMarks = marks[i];
topper = names[i];
}
}
System.out.println("Topper is " + topper + " with " +
maxMarks + " marks.");
break;

case 4:
System.out.println("Exiting... Goodbye!");
break;

default:
System.out.println("Invalid choice. Try again.");
}
} while (option != 4);

sc.close();
}
}

1. Switch Case in Java


A switch statement is used when you have to compare one variable with many possible values.​
It’s cleaner than writing many if-else if.

Syntax:
switch(variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no case matches
}

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

2. Pre and Post Increment/Decrement


These are operators that increase (++) or decrease (--) the value of a variable by 1.

●​ Pre-increment (++x): First increase, then use.


●​ Post-increment (x++): First use, then increase.
●​ Pre-decrement (--x): First decrease, then use.
●​ Post-decrement (x--): First use, then decrease.

Example:
public class IncrementExample {
public static void main(String[] args) {
int a = 5;

System.out.println("a = " + a); // 5

System.out.println("Pre-increment ++a = " + (++a)); // first increase →


6
System.out.println("After pre-increment a = " + a); // 6

System.out.println("Post-increment a++ = " + (a++)); // use first → 6,


then becomes 7
System.out.println("After post-increment a = " + a); // 7
System.out.println("Pre-decrement --a = " + (--a)); // first decrease →
6
System.out.println("Post-decrement a-- = " + (a--)); // use 6, then
becomes 5
System.out.println("Final value of a = " + a); // 5
}
}

➡️ Output:
a = 5
Pre-increment ++a = 6
After pre-increment a = 6
Post-increment a++ = 6
After post-increment a = 7
Pre-decrement --a = 6
Post-decrement a-- = 6
Final value of a = 5

✅ Summary:
●​ Use switch when you check one variable against many values.
●​ Pre/Post increment/decrement are useful in loops and calculations.

Assignments
Switch Case Assignments
1.​ Write a Java program using switch that takes a number (1–7) and prints the day of the
week.​
(Example: 1 → Monday, 7 → Sunday)
2.​ Write a program using switch that takes a number (1–12) and prints the month name.​
(Example: 1 → January, 12 → December)
3.​ Write a calculator program using switch that takes two numbers and an operator (+, -,
*, /) and performs the correct operation.

Pre & Post Increment/Decrement Assignments


4.​ Predict the output of the following code:
int x = 5;
System.out.println(++x);​ 6
System.out.println(x++);​ 6
System.out.println(--x);​ 6
System.out.println(x--);​ 6​
System.out.println(x);​ 5
5.​ Write a Java program to print numbers from 1 to 5 using pre-increment.
6.​ Write a Java program to print numbers from 5 to 1 using post-decrement

1. Arrays in Java
👉 An array is used to store multiple values of the same type in a single variable.
Example: Without Array
int mark1 = 85;
int mark2 = 90;
int mark3 = 78;
int mark4 = 88;
int mark5 = 95;
This is not efficient if we have many marks.

Example: With Array


int[] marks = new int[5]; // Declare array of size 5
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
marks[3] = 88;
marks[4] = 95;

Printing Array Values with Loop


public class ArrayExample {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 88, 95};

// Loop through array


for (int i = 0; i < marks.length; i++) {
System.out.println("Mark " + (i+1) + ": " + marks[i]);
}
}
}

Find Sum, Max, and Min


public class ArrayOperations {
public static void main(String[] args) {
int[] numbers = {12, 45, 67, 23, 89, 5};

int sum = 0;
int max = numbers[0];
int min = numbers[0];

for (int i = 0; i < numbers.length; i++) {


sum += numbers[i];

if (numbers[i] > max) {


max = numbers[i];
}

if (numbers[i] < min) min = 5 {


min = numbers[i];
}
}

System.out.println("Sum = " + sum);


System.out.println("Max = " + max);
System.out.println("Min = " + min);
}
}

2. Strings in Java
👉 A String is a sequence of characters (like words or sentences).
String Basics
public class StringBasics {
public static void main(String[] args) {
String name = "Rukhsar";

System.out.println("Name: " + name);


System.out.println("Length: " + name.length()); // number of
characters
System.out.println("First char: " + name.charAt(0)); // first character
System.out.println("Substring: " + name.substring(0, 4)); // "Rukh"
System.out.println("Uppercase: " + name.toUpperCase()); // "RUKHSAR"
System.out.println("Equals: " + name.equals("Rukhsar")); // true
}
}

📘 Assignment – Arrays & Strings


Part A: Arrays
1.​ Write a Java program to input 5 numbers in an array and print them in reverse order.
2.​ Write a program to find the average of numbers in an array.
3.​ Find the largest and smallest number in an array without using built-in functions.
4.​ Count how many even and odd numbers are in the array {10, 23, 45, 66, 78, 91}.

5.​ Write a program that searches for a number in an array (linear search). If found, print its
index, otherwise print “Not Found”.
Part B: Strings
1.​ Input a string and print its length and the first and last character.
2.​ Check if two strings are equal or not (using .equals() method).

3.​ Convert a string into uppercase and lowercase.


4.​ Extract a substring from "UniversityOfMirpurkhas" (for example, print
"Mirpurkhas").

5.​ Count how many vowels are present in a string.

✅ Solutions – Arrays & Strings in Java


Part A: Arrays
Q1. Print 5 numbers in reverse order
public class ReverseArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

System.out.println("Numbers in reverse order:");


for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
}
}

Q2. Find average of numbers in an array


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

for (int num : numbers) {


sum += num;
}

double average = (double) sum / numbers.length;


System.out.println("Average = " + average);
}
}

Q3. Find largest and smallest


public class MaxMinArray {
public static void main(String[] args) {
int[] numbers = {25, 78, 12, 56, 89, 5};

int max = numbers[0];


int min = numbers[0];

for (int num : numbers) {


if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}

System.out.println("Largest = " + max);


System.out.println("Smallest = " + min);
}
}

Q4. Count even and odd numbers


public class EvenOddCount {
public static void main(String[] args) {
int[] numbers = {10, 23, 45, 66, 78, 91};
int evenCount = 0, oddCount = 0;

for (int num : numbers) {


if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

System.out.println("Even numbers = " + evenCount);


System.out.println("Odd numbers = " + oddCount);
}
}

Q5. Linear Search


public class LinearSearch {
public static void main(String[] args) {
int[] numbers = {5, 12, 34, 7, 19, 56};
int search = 19;
boolean found = false;

for (int i = 0; i < numbers.length; i++) {


if (numbers[i] == search) {
System.out.println("Number found at index " + i);
found = true;
break;
}
}
if (!found) {
System.out.println("Number not found");
}
}
}

Part B: Strings
Q1. Print length, first and last character
public class StringDetails {
public static void main(String[] args) {
String str = "Rukhsar";

System.out.println("Length = " + str.length());


System.out.println("First char = " + str.charAt(0));
System.out.println("Last char = " + str.charAt(str.length() - 1));
}
}

Q2. Check equality of two strings


public class StringEquality {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";

if (str1.equals(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
}
}

Q3. Convert to uppercase and lowercase


public class StringCase {
public static void main(String[] args) {
String name = "University";

System.out.println("Uppercase = " + name.toUpperCase());


System.out.println("Lowercase = " + name.toLowerCase());
}
}

Q4. Extract substring


public class SubstringExample {
public static void main(String[] args) {
String str = "UniversityOfMirpurkhas";

String sub = str.substring(12); // from index 12 → "Mirpurkhas"


System.out.println("Substring = " + sub);
}
}

Q5. Count vowels in a string


public class VowelCount {
public static void main(String[] args) {
String str = "Education";
int count = 0;

for (int i = 0; i < str.length(); i++) {


char c = Character.toLowerCase(str.charAt(i));
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
count++;
}
}

System.out.println("Number of vowels = " + count);


}
}

📘 Functions (Methods) in Java


👉 In Java, a function is called a method.​
It is a block of code that runs only when it is called.​
It helps us avoid code repetition and makes programs organized.

✅ Syntax of a Function
returnType functionName(parameters) {
// code block
return value; // only if returnType is not void
}

🔎 Example 1: A Simple Function


public class FunctionsExample {
// function with no return and no parameters
public static void greet() {
System.out.println("Hello! Welcome to Java Functions.");
}

public static void main(String[] args) {


greet(); // calling the function
greet(); // can call multiple times
}
}

Output:

Hello! Welcome to Java Functions.


Hello! Welcome to Java Functions.

🔎 Example 2: Function with Parameters


public class FunctionsExample {
public static void greetByName(String name) {
System.out.println("Hello " + name + "!");
}

public static void main(String[] args) {


greetByName("Rukhsar");
greetByName("Ali");
}
}

Output:

Hello Rukhsar!
Hello Ali!

🔎 Example 3: Function with Return Value


public class FunctionsExample {
public static int add(int a, int b) {
return a + b; // return the sum
}

public static void main(String[] args) {


int result = add(5, 7);
System.out.println("Sum = " + result);
}
}

Output:​

Sum = 12

🔎 Example 4: Multiple Functions Together


public class Calculator {
public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}

public static int multiply(int a, int b) {


return a * b;
}

public static double divide(int a, int b) {


return (double) a / b;
}

public static void main(String[] args) {


System.out.println("Add = " + add(10, 5));
System.out.println("Subtract = " + subtract(10, 5));
System.out.println("Multiply = " + multiply(10, 5));
System.out.println("Divide = " + divide(10, 5));
}
}

Output:

Add = 15
Subtract = 5
Multiply = 50
Divide = 2.0

📌 Types of Functions in Java


👉
1.​ No parameters, no return value​
Just performs a task.​
Example: void greet()

👉
2.​ With parameters, no return value​
Takes input but doesn’t return anything.​
Example: void greetByName(String name)

👉
3.​ No parameters, with return value​
Doesn’t take input but returns something.​
Example: int getNumber()

👉
4.​ With parameters, with return value​
Takes input and returns output.​
Example: int add(int a, int b)
✅ Functions are important because they help reuse code, divide program into small tasks,
and make debugging easier.

📘 What are Parameters?


👉 A parameter is a variable inside the parentheses of a function that receives data when the
function is called.

Think of it like a container that holds values you pass into the function.

✅ Example 1: Function without parameter


public class Example {
public static void greet() {
System.out.println("Hello, welcome!");
}

public static void main(String[] args) {


greet(); // no data passed
}
}

Here, the function greet() always prints the same message.​


No parameter → no customization.

✅ Example 2: Function with a parameter


public class Example {
public static void greetByName(String name) {
System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {


greetByName("Rukhsar");
greetByName("Ali");
}
}

●​ String name → this is the parameter.


●​ "Rukhsar" and "Ali" are called arguments (the actual values passed).
Output:

Hello, Rukhsar!
Hello, Ali!

📌 So, parameters = placeholders, arguments = actual values.

✅ Example 3: Multiple parameters


public class Example {
public static void add(int a, int b) {
int sum = a + b;
System.out.println("Sum = " + sum);
}

public static void main(String[] args) {


add(5, 10); // a=5, b=10
add(20, 7); // a=20, b=7
}
}

Output:

Sum = 15
Sum = 27

●​ Here, the function add(int a, int b) has two parameters.


●​ When calling add(5, 10), the values 5 and 10 are copied into a and b.

✅ Example 4: Return + Parameters


public class Example {
public static int square(int number) {
return number * number;
}

public static void main(String[] args) {


System.out.println("Square of 4 = " + square(4));
System.out.println("Square of 7 = " + square(7));
}
}

Output:

Square of 4 = 16
Square of 7 = 49
📌 Summary
●​ Parameter → variable inside function definition (like int a, String name).
●​ Argument → actual value passed when calling function (like 5, "Rukhsar").
●​ Parameters make functions flexible and reusable.

📘 Functions Assignment
Q1. Greeting Function

👉
Write a function greetByName(String name) that prints:​
"Hello, <name>! Welcome to Java."

Q2. Calculator Functions


Write four separate functions:
●​ add(int a, int b)

●​ subtract(int a, int b)

●​ multiply(int a, int b)

●​ divide(int a, int b)

Call each function in main() and print results.

Q3. Square and Cube


Write two functions:
●​ square(int num) → returns square of a number.
●​ cube(int num) → returns cube of a number.

Q4. Even or Odd


Write a function checkEvenOdd(int num) that prints whether a number is even or odd.
Q5. Factorial Function

👉
Write a function factorial(int n) that returns the factorial of n.​
Example: factorial(5) = 120

Q6. Maximum of Two Numbers


Write a function max(int a, int b) that returns the bigger number.

Q7. Prime Number Check


Write a function isPrime(int n) that returns true if the number is prime, otherwise false.

Q8. Sum of Array Elements (using Function)


Write a function sumArray(int[] arr) that takes an array as parameter and returns the sum of
all elements.

✅ Java Functions Assignment – Solutions


Q1. Greeting Function
public class Greeting {
public static void greetByName(String name) {
System.out.println("Hello, " + name + "! Welcome to Java.");
}

public static void main(String[] args) {


greetByName("Rukhsar");
greetByName("Ali");
}
}

Q2. Calculator Functions


public class Calculator {
public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}

public static double divide(int a, int b) {


return (double) a / b;
}

public static void main(String[] args) {


System.out.println("Add = " + add(10, 5));
System.out.println("Subtract = " + subtract(10, 5));
System.out.println("Multiply = " + multiply(10, 5));
System.out.println("Divide = " + divide(10, 5));
}
}

Q3. Square and Cube


public class PowerFunctions {
public static int square(int num) {
return num * num;
}

public static int cube(int num) {


return num * num * num;
}

public static void main(String[] args) {


System.out.println("Square of 4 = " + square(4));
System.out.println("Cube of 3 = " + cube(3));
}
}

Q4. Even or Odd


public class EvenOdd {
public static void checkEvenOdd(int num) {
if (num % 2 == 0) {
System.out.println(num + " is Even");
} else {
System.out.println(num + " is Odd");
}
}

public static void main(String[] args) {


checkEvenOdd(7);
checkEvenOdd(10);
}
}

Q5. Factorial Function


public class Factorial {
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

public static void main(String[] args) {


System.out.println("Factorial of 5 = " + factorial(5));
System.out.println("Factorial of 7 = " + factorial(7));
}
}

Q6. Maximum of Two Numbers


public class MaxNumber {
public static int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}

public static void main(String[] args) {


System.out.println("Max of 10 and 20 = " + max(10, 20));
System.out.println("Max of 25 and 15 = " + max(25, 15));
}
}

Q7. Prime Number Check


public class PrimeCheck {
public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] args) {


System.out.println("Is 7 Prime? " + isPrime(7));
System.out.println("Is 10 Prime? " + isPrime(10));
}
}

Q8. Sum of Array Elements


public class ArraySum {
public static int sumArray(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}

public static void main(String[] args) {


int[] numbers = {10, 20, 30, 40, 50};
System.out.println("Sum of array = " + sumArray(numbers));
}
}

📘 Object-Oriented Programming (OOP) in Java


🔹 1. What is OOP?
OOP is a way of programming where we design software using objects (like real-life entities).
●​ Objects have properties (data/attributes) and behaviors (methods/functions).
●​ Java is a fully object-oriented language (except for primitive types).
👉 Think of it as modeling real-world things in code.
🔹 2. Key Concepts of OOP
(a) Class
●​ A class is a blueprint/template for objects.
●​
👉
It defines what data (fields/variables) and what actions (methods) an object can have.​
Example: Car class
class Car {
String color;
int speed;

void drive() { ... }


}

(b) Object
●​
👉
An object is an instance of a class (a real thing created from the blueprint).​
Example: Car myCar = new Car();
If Car is the blueprint, then myCar is the actual car you can use.
(c) Encapsulation
●​ Wrapping data (variables) and methods (functions) together into a class.
●​
👉
Data is kept safe using access modifiers (private, public).​
Example: You can’t directly touch the engine of a car, but you can use buttons
(methods) to control it.

(d) Inheritance
●​ One class can inherit properties & methods from another class.
●​
👉
Promotes code reuse.​
Example:
o​ Vehicle class (general)

o​ Car and Bike classes inherit from Vehicle.

(e) Polymorphism
●​ Means many forms.
●​
👉
A single method or object behaves differently based on the context.​
Example:
o​ draw() method → behaves differently for Circle, Square, Triangle.

(f) Abstraction
●​ Hiding implementation details and showing only the essential features.
●​
👉
Achieved using abstract classes and interfaces in Java.​
Example: You press a button on a TV remote without knowing how it works
internally.

🔹 3. Benefits of OOP
1.​ Reusability → Inheritance allows code reuse.
2.​ Maintainability → Easy to modify code when logic is inside classes.
3.​ Security → Encapsulation hides sensitive data.
4.​ Flexibility → Polymorphism allows different behavior with same method.
5.​ Real-world modeling → Classes/objects map to real-world entities.
🔹 4. Real-Life Example of OOP
👉 Example: University System
●​ Class (Blueprint): Student
o​ Attributes: name, rollNo, marks
o​ Methods: study(), giveExam()
●​ Objects (Real):
o​ Student1: name = "Rukhsar", rollNo = 101
o​ Student2: name = "Ali", rollNo = 102
Encapsulation hides student’s data → only accessible via methods.​
Inheritance → GraduateStudent and UndergraduateStudent can extend Student.​
Polymorphism → study() can mean different styles of studying.

✅ In summary:
●​ Class = Blueprint
●​ Object = Real thing created from class
●​ Encapsulation = Data hiding
●​ Inheritance = Code reuse
●​ Polymorphism = One thing, many forms
●​ Abstraction = Show only necessary details

1. Class and Object Example


class Student {
String name;
int age;

public void getInfo() {


System.out.println("The name of this Student is " + this.name);
System.out.println("The age of this Student is " + this.age);
}
}

public class OOPS1 {


public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Rukhsar";
s1.age = 28;
s1.getInfo();

Student s2 = new Student();


s2.name = "Ali";
s2.age = 22;
s2.getInfo();
}
}

2. Another Object Example


class Pen {
String color;

public void printColor() {


System.out.println("The color of this Pen is " + this.color);
}
}

public class OOPS2 {


public static void main(String[] args) {
Pen p1 = new Pen();
p1.color = "Blue";

Pen p2 = new Pen();


p2.color = "Black";

Pen p3 = new Pen();


p3.color = "Red";

p1.printColor();
p2.printColor();
p3.printColor();
}
}

3. Non-Parameterized Constructor
class Student {
String name;
int age;

// Non-parameterized constructor
Student() {
System.out.println("Constructor called");
}
}

public class OOPS3 {


public static void main(String[] args) {
Student s1 = new Student(); // Constructor will be called automatically
}
}
4. Parameterized Constructor
class Student {
String name;
int age;

// Parameterized constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}

public void display() {


System.out.println("Name: " + this.name + ", Age: " + this.age);
}
}

public class OOPS4 {


public static void main(String[] args) {
Student s1 = new Student("Amar", 24);
Student s2 = new Student("Bilal", 22);

s1.display();
s2.display();
}
}

5. Copy Constructor
class Student {
String name;
int age;

// Parameterized constructor
Student(String name, int age) {
this.name = name;
this.age = age;
}

// Copy constructor
Student(Student s2) {
this.name = s2.name;
this.age = s2.age;
}

public void display() {


System.out.println("Name: " + this.name + ", Age: " + this.age);
}
}

public class OOPS5 {


public static void main(String[] args) {
Student s1 = new Student("Aman", 24);
Student s2 = new Student(s1); // Copy constructor

s1.display();
s2.display();
}
}

📘 1. Class & Object


👉 A class is a blueprint, and an object is an instance of that class.
class Car {
String color;
int speed;

void drive() {
System.out.println(color + " car is driving at " + speed + " km/h");
}
}
class Bike {
String model;
int year;

void ride() {
System.out.println(model + " purchased in year " + year + " by him");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // object created
myCar.color = "Red"; // assigning values
myCar.speed = 120;
myCar.drive(); // method call
​ Bike bike1 = new Bike();
​ bike1.model = “Honda”;
​ bike1.year = 2019;
​ bike1.ride();
}
}

Output:

Red car is driving at 120 km/h

📘 2. Encapsulation
👉 Wrapping data and methods together, and hiding variables using private.
class BankAccount {
private double balance; // private data

// public methods to access data


public void deposit(double amount) {
balance += amount;
}

public double getBalance() {


return balance;
}
}

public class Main {


public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(5000);
System.out.println("Balance = " + acc.getBalance());
}
}

Output:

Balance = 5000.0

👉 Notice: We can’t directly access balance, only via methods.

📘 3. Inheritance
👉 One class inherits from another using extends.

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal { // Dog inherits from Animal


void bark() {
System.out.println("Dog barks!");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited method
d.bark(); // Dog’s own method
}
}
Output:

This animal eats food.


Dog barks!

📘 4. Polymorphism
👉 Same method, different behavior.
Compile-time Polymorphism (Method Overloading)
class MathUtils {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) { // same method name, different params


return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
MathUtils m = new MathUtils();
System.out.println(m.add(5, 10));
System.out.println(m.add(5, 10, 15));
}
}

Output:

15
30

Runtime Polymorphism (Method Overriding)


class Person {
void introduce() {
System.out.println("Hello Person");
}
}

class Teacher extends Person {


@Override
void introduce() {
System.out.println("Hello Teacher");
}
}

class Student extends Person {


@Override
void introduce() {
System.out.println("Hello Student");
}
}

public class Main {


public static void main(String[] args) {
Person tchr1 = new Teacher(); // runtime polymorphism
Person std1 = new Student();

tchr1.introduce();
std1.introduce();
}
}

Output:

Dog barks
Cat meows

📘 5. Abstraction
👉 Hiding implementation, showing only essentials.​
Achieved by abstract classes or interfaces.

Using Abstract Class


abstract class Vehicle {
abstract void start(); // abstract method (no body)

void fuel() {
System.out.println("Vehicle needs fuel.");
}
}

class Car extends Vehicle {


void start() {
System.out.println("Car starts with a key.");
}
}

class Bike extends Vehicle {


void start() {
System.out.println("Bike starts with a kick.");
}
}

public class Main {


public static void main(String[] args) {
Vehicle v1 = new Car();
Vehicle v2 = new Bike();
v1.start();
v2.start();
}
}

Output:

Car starts with a key.


Bike starts with a kick.

✅ Summary
●​ Class & Object → Blueprint & real object.
●​ Encapsulation → Data hiding (private + getters/setters).
●​ Inheritance → Reuse code (extends).
●​ Polymorphism → Same method, many forms (overloading & overriding).
●​ Abstraction → Hiding details, showing essentials (abstract / interface).

📘
👉
What is Object-Oriented Programming (OOP)?
OOP is a way of programming where we design our code around objects (real-world things)
instead of just functions and logic.
Each object has:
●​ Attributes (variables / properties) → what it has
●​ Behaviors (methods / functions) → what it does
Example:
●​ A Car object has attributes → color, speed, model
●​ Behaviors → drive(), stop(), honk()

🔑 4 Main Concepts of OOP (with real-life examples)


1. Encapsulation (Data Hiding)
👉
👉 Wrapping data (variables) and methods (functions) into one unit (class).​
Protecting data from direct access.
🏠 Real-life Example:
●​ Think of a bank ATM.
o​ You don’t directly access the bank’s database.
o​ You interact via methods like deposit(), withdraw(), checkBalance().
o​ Your PIN (data) is hidden and secured.

2. Inheritance (Reusability)
👉
👉 Helps avoid rewriting the same code again.
One class inherits properties/behaviors of another class.​

🏠 Real-life Example:
●​ A Car is a type of Vehicle.
●​ Vehicle has attributes like fuel, speed, start().
●​ Car inherits these features and adds its own → airConditioner, musicSystem.
●​ Similarly, Bike also inherits from Vehicle.

3. Polymorphism (Many Forms)


👉 One method can have different implementations.
Types:
●​ Compile-time polymorphism (Overloading) → Same name, different parameters.
●​ Runtime polymorphism (Overriding) → Same method, but different behavior in
subclasses.
🏠 Real-life Example:
●​ A remote control button:
o​ Pressing "power" on TV → turns TV on.
o​ Pressing "power" on AC → turns AC on.
o​ Same action (press button), but different results depending on the device.

4. Abstraction (Hiding Details, Showing Essentials)


👉 Showing only important details and hiding unnecessary ones.
🏠 Real-life Example:
●​ Driving a car:
o​ You only see the steering wheel, accelerator, brake.
o​ You don’t know the internal engine mechanics, but you can still drive.
o​ Abstraction hides engine complexity and shows only what the driver needs.

✅ Summary (Quick Table)


Concept Meaning Real-Life Example

Encapsulation Bundling data & methods, data hiding ATM hides account data, only methods allowed

Reuse parent class features in child


Inheritance Car & Bike inherit from Vehicle
class

Polymorphism One action, many forms Power button works differently on TV vs AC

Car driver uses steering & pedals, not engine


Abstraction Show essentials, hide complexity
details

You might also like