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

🔹 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) {
[Link]("Hello, Java!");
}
}

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

●​ File name must match the class name. (e.g., [Link])


●​ 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 [Link], [Link]).


●​ Example:

import [Link]; // 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


[Link]("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
[Link] = "Red";
[Link] = 100;

[Link]("Car color: " + [Link]);


[Link]();
}
}

🔹 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) {
[Link]("Hello, World!");
}

👉 Explanation:
}
●​ public class HelloWorld → class name (must match file name [Link]).
●​ main method → Starting point of every Java program.
●​ [Link]() → 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

[Link]("Name: " + name);


[Link]("Age: " + age);
[Link]("Height: " + height);
[Link]("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;

[Link]("Addition: " + (a + b));


[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("Remainder: " + (a % b));
}

📌 Output:
}

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

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

🔹 2. Example: Taking Input


import [Link]; // importing Scanner class

public class UserInputExample {


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

[Link]("Enter your name: ");


String name = [Link](); // reads text input

[Link]("Enter your age: ");


int age = [Link](); // reads integer input

[Link]("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 [Link];

public class CalculatorExample {


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

[Link]("Enter first number: ");


int a = [Link]();

[Link]("Enter second number: ");


int b = [Link]();

[Link]("Addition: " + (a + b));


[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("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) {


[Link]("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) {


[Link]("You are an adult.");
} else {
[Link]("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) {


[Link]("Grade: A");
} else if (marks >= 75) {
[Link]("Grade: B");
} else if (marks >= 50) {
[Link]("Grade: C");
} else {
[Link]("Fail");
}
}

📌 Output:
}

Grade: B

🔹 5. Using if with User Input


import [Link];

public class IfWithInput {


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

[Link]("Enter your age: ");


int age = [Link]();

if (age >= 18) {


[Link]("You can vote!");
} else {
[Link]("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;

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


[Link]("a != b: " + (a != b));
[Link]("a > b: " + (a > b));
[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("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) {
[Link]("You are an adult.");
} else {
[Link]("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++) {
[Link]("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) {
[Link]("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 {
[Link]("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 [Link];

public class LoopWithInput {


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

[Link]("Enter a number: ");


int n = [Link]();

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


[Link](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 [Link];

public class PositiveNegativeZero {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

if (num > 0) {
[Link]("Positive");
} else if (num < 0) {
[Link]("Negative");
} else {
[Link]("Zero");
}
}
}

2. Student Grade
import [Link];

public class StudentGrade {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter marks: ");
int marks = [Link]();

if (marks >= 90) {


[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
}
}
}

3. Largest of Two Numbers


import [Link];

public class LargestNumber {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();

if (a > b) {
[Link]("Largest: " + a);
} else if (b > a) {
[Link]("Largest: " + b);
} else {
[Link]("Both are equal");
}
}
}

4. Even or Odd
import [Link];

public class EvenOdd {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

if (num % 2 == 0) {
[Link]("Even");
} else {
[Link]("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++) {
[Link](i);
}
}
}

6. Multiplication Table
import [Link];

public class MultiplicationTable {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();

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


[Link](n + " x " + i + " = " + (n * i));
}
}
}

7. Sum of First N Numbers


import [Link];

public class SumFirstN {


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

[Link]("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) {
[Link](i);
}
i++;
}
}
}

9. Reverse a Number
import [Link];

public class ReverseNumber {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();

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

[Link]("Reversed number: " + reverse);


}
}

10. Factorial
import [Link];

public class Factorial {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();

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

[Link]("Factorial = " + fact);


}
}

🔹 Part D: do–while Loop


11. Sum Until User Enters 0
import [Link];

public class SumUntilZero {


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

do {
[Link]("Enter a number (0 to stop): ");
num = [Link]();
sum += num;
} while (num != 0);

[Link]("Total Sum = " + sum);


}
}

12. Guessing Game


import [Link];

public class GuessingGame {


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

do {
[Link]("Guess the number (1-10): ");
guess = [Link]();

if (guess != secret) {
[Link]("Wrong! Try again.");
}
} while (guess != secret);

[Link]("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 [Link];

public class StudentManagement {


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

// Step 1: Input number of students


[Link]("Enter number of students: ");
int n = [Link]();
[Link](); // 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++) {
[Link]("Enter name of student " + (i + 1) + ": ");
names[i] = [Link]();

[Link]("Enter marks: ");


marks[i] = [Link]();
[Link](); // 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";
}
}

[Link]("\nGrades assigned successfully!\n");

// Step 3: Search student using WHILE loop


String choice;
[Link]("Do you want to search a student? (yes/no): ");
choice = [Link]();

while ([Link]("yes")) {
[Link]("Enter name to search: ");
String searchName = [Link]();
boolean found = false;

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


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

if (!found) {
[Link]("Student not found.");
}

[Link]("Do you want to search again? (yes/no): ");


choice = [Link]();
}

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


int option;
do {
[Link]("\n---- MENU ----");
[Link]("1. Show all students with grades");
[Link]("2. Show class average marks");
[Link]("3. Find highest marks");
[Link]("4. Exit");
[Link]("Enter choice: ");
option = [Link]();

switch (option) {
case 1:
for (int i = 0; i < n; i++) {
[Link](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;
[Link]("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];
}
}
[Link]("Topper is " + topper + " with " +
maxMarks + " marks.");
break;

case 4:
[Link]("Exiting... Goodbye!");
break;

default:
[Link]("Invalid choice. Try again.");
}
} while (option != 4);

[Link]();
}
}

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

➡️ 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;

[Link]("a = " + a); // 5

[Link]("Pre-increment ++a = " + (++a)); // first increase →


6
[Link]("After pre-increment a = " + a); // 6

[Link]("Post-increment a++ = " + (a++)); // use first → 6,


then becomes 7
[Link]("After post-increment a = " + a); // 7
[Link]("Pre-decrement --a = " + (--a)); // first decrease →
6
[Link]("Post-decrement a-- = " + (a--)); // use 6, then
becomes 5
[Link]("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;
[Link](++x);​ 6
[Link](x++);​ 6
[Link](--x);​ 6
[Link](x--);​ 6​
[Link](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 < [Link]; i++) {
[Link]("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 < [Link]; i++) {


sum += numbers[i];

if (numbers[i] > max) {


max = numbers[i];
}

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


min = numbers[i];
}
}

[Link]("Sum = " + sum);


[Link]("Max = " + max);
[Link]("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";

[Link]("Name: " + name);


[Link]("Length: " + [Link]()); // number of
characters
[Link]("First char: " + [Link](0)); // first character
[Link]("Substring: " + [Link](0, 4)); // "Rukh"
[Link]("Uppercase: " + [Link]()); // "RUKHSAR"
[Link]("Equals: " + [Link]("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};

[Link]("Numbers in reverse order:");


for (int i = [Link] - 1; i >= 0; i--) {
[Link](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 / [Link];


[Link]("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;
}
}

[Link]("Largest = " + max);


[Link]("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++;
}
}

[Link]("Even numbers = " + evenCount);


[Link]("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 < [Link]; i++) {


if (numbers[i] == search) {
[Link]("Number found at index " + i);
found = true;
break;
}
}
if (!found) {
[Link]("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";

[Link]("Length = " + [Link]());


[Link]("First char = " + [Link](0));
[Link]("Last char = " + [Link]([Link]() - 1));
}
}

Q2. Check equality of two strings


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

if ([Link](str2)) {
[Link]("Strings are equal");
} else {
[Link]("Strings are not equal");
}
}
}

Q3. Convert to uppercase and lowercase


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

[Link]("Uppercase = " + [Link]());


[Link]("Lowercase = " + [Link]());
}
}

Q4. Extract substring


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

String sub = [Link](12); // from index 12 → "Mirpurkhas"


[Link]("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 < [Link](); i++) {


char c = [Link]([Link](i));
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
count++;
}
}

[Link]("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() {
[Link]("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) {
[Link]("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);
[Link]("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) {


[Link]("Add = " + add(10, 5));
[Link]("Subtract = " + subtract(10, 5));
[Link]("Multiply = " + multiply(10, 5));
[Link]("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() {
[Link]("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) {
[Link]("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;
[Link]("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) {


[Link]("Square of 4 = " + square(4));
[Link]("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) {
[Link]("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) {


[Link]("Add = " + add(10, 5));
[Link]("Subtract = " + subtract(10, 5));
[Link]("Multiply = " + multiply(10, 5));
[Link]("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) {


[Link]("Square of 4 = " + square(4));
[Link]("Cube of 3 = " + cube(3));
}
}

Q4. Even or Odd


public class EvenOdd {
public static void checkEvenOdd(int num) {
if (num % 2 == 0) {
[Link](num + " is Even");
} else {
[Link](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) {


[Link]("Factorial of 5 = " + factorial(5));
[Link]("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) {


[Link]("Max of 10 and 20 = " + max(10, 20));
[Link]("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) {


[Link]("Is 7 Prime? " + isPrime(7));
[Link]("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};
[Link]("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() {


[Link]("The name of this Student is " + [Link]);
[Link]("The age of this Student is " + [Link]);
}
}

public class OOPS1 {


public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Rukhsar";
[Link] = 28;
[Link]();

Student s2 = new Student();


[Link] = "Ali";
[Link] = 22;
[Link]();
}
}

2. Another Object Example


class Pen {
String color;

public void printColor() {


[Link]("The color of this Pen is " + [Link]);
}
}

public class OOPS2 {


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

Pen p2 = new Pen();


[Link] = "Black";

Pen p3 = new Pen();


[Link] = "Red";

[Link]();
[Link]();
[Link]();
}
}

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

// Non-parameterized constructor
Student() {
[Link]("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) {
[Link] = name;
[Link] = age;
}

public void display() {


[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}

public class OOPS4 {


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

[Link]();
[Link]();
}
}

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

// Parameterized constructor
Student(String name, int age) {
[Link] = name;
[Link] = age;
}

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

public void display() {


[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}

public class OOPS5 {


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

[Link]();
[Link]();
}
}

📘 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() {
[Link](color + " car is driving at " + speed + " km/h");
}
}
class Bike {
String model;
int year;

void ride() {
[Link](model + " purchased in year " + year + " by him");
}
}

public class Main {


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

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();
[Link](5000);
[Link]("Balance = " + [Link]());
}
}

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() {
[Link]("This animal eats food.");
}
}

class Dog extends Animal { // Dog inherits from Animal


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

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited method
[Link](); // 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();
[Link]([Link](5, 10));
[Link]([Link](5, 10, 15));
}
}

Output:

15
30

Runtime Polymorphism (Method Overriding)


class Person {
void introduce() {
[Link]("Hello Person");
}
}

class Teacher extends Person {


@Override
void introduce() {
[Link]("Hello Teacher");
}
}

class Student extends Person {


@Override
void introduce() {
[Link]("Hello Student");
}
}

public class Main {


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

[Link]();
[Link]();
}
}

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() {
[Link]("Vehicle needs fuel.");
}
}

class Car extends Vehicle {


void start() {
[Link]("Car starts with a key.");
}
}

class Bike extends Vehicle {


void start() {
[Link]("Bike starts with a kick.");
}
}

public class Main {


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

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