24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
ASSIGNMENT 1
——————————————————————
Question 1: Java Basics and Data Types Practice
Write a Java program that:
1. Prints "Hello, World!" to the screen.
public class Main {
public static void main(String[] args) {
[Link]("Hello, World!");
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
2. Declares and initializes variables of different data types:
o int (e.g., age)
o double (e.g., height)
o String (e.g., name)
o char (e.g., grade)
o boolean (e.g., isPassed)
public class Main {
public static void main(String[] args) {
int age = 20;
double height = 5.8;
String name = "Alice";
char grade = 'A';
boolean isPassed = true;
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Height: " + height);
[Link]("Grade: " + grade);
[Link]("Passed: " + isPassed);
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
3. Demonstrates the use of a constant using the final keyword.
public class Main {
public static void main(String[] args) {
final double PI = 3.14159;
[Link]("The value of PI is: " + PI);
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
4. Performs and prints results of different arithmetic operations
(like addition and multiplication).
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 5;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
[Link]("Sum: " + sum);
[Link]("Difference: " + difference);
[Link]("Product: " + product);
[Link]("Quotient: " + quotient);
[Link]("Remainder: " + remainder);
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
5. Uses relational and logical operators in simple comparisons
(e.g., check if age is greater than 18 and isPassed is true).
public class Main {
public static void main(String[] args) {
int age = 20;
boolean isPassed = true;
boolean eligible = (age > 18) && isPassed;
[Link]("Is the person eligible? " + eligible);
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
6. Add comments to explain the code (what each line does and
why it is used).
// This is the class declaration. Every Java program must be inside a class.
public class Main {
// This is the main method. It is the entry point where the program starts running.
public static void main(String[] args) {
// This line prints the text "Hello, World!" to the console.
// [Link] is used to access the output stream, and println prints a line of
text.
[Link]("Hello, World!");
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
Question 2: Java Conditions and Number Checks
Write a Java program using if-else statements to do the following:
1. Check whether a number is positive or negative.
public class PositiveNegative {
public static void main(String[] args) {
int num = -5;
if (num > 0)
[Link]("Positive");
else if (num < 0)
[Link]("Negative");
else
[Link]("Zero");
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
2. Swap a number using third variable.
public class Swap {
public static void main(String[] args) {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
[Link]("a = " + a + ", b = " + b);
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
3. Find the largest among them three numbers.
public class Largest {
public static void main(String[] args) {
int a = 8, b = 15, c = 10;
if (a >= b && a >= c)
[Link]("Largest: " + a);
else if (b >= a && b >= c)
[Link]("Largest: " + b);
else
[Link]("Largest: " + c);
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 OOPS WITH JAVA
4. Check whether a number is prime number or not.
public class Largest {
public static void main(String[] args) {
int a = 8, b = 15, c = 10;
if (a >= b && a >= c)
[Link]("Largest: " + a);
else if (b >= a && b >= c)
[Link]("Largest: " + b);
else
[Link]("Largest: " + c);
}
}
24SE02CS127 PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
Assignment - 2
——————————————————
1. Class Creation
Create a class called Person with the following fields: name,
age, and gender.
Add a method displayInfo() to print all the details of the
person.
CODE:
// Program 1: Class Creation
public class Person {
// Fields (attributes)
String name;
int age;
String gender;
// Constructor with all fields
Person(String name, int age, String gender) {
[Link] = name;
[Link] = age;
[Link] = gender;
// Method to display information
void displayInfo() {
[Link]("Name : " + name);
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
[Link]("Age : " + age);
[Link]("Gender : " + gender);
// Main method
public static void main(String[] args) {
// Creating an object and calling displayInfo
Person person1 = new Person("Anjali", 20, "Female");
[Link]();
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
2. Constructor Overloading
In the Person class, add three constructors:
• One with no parameters
• One with name and age
• One with name, age, and gender
CODE:
// Program 2: Constructor Overloading
public class Person {
// Fields
String name;
int age;
String gender;
// Constructor 1: No parameters
Person() {
name = "Unknown";
age = 0;
gender = "Not specified";
// Constructor 2: Name and age
Person(String name, int age) {
[Link] = name;
[Link] = age;
gender = "Not specified";
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
// Constructor 3: Name, age, and gender
Person(String name, int age, String gender) {
[Link] = name;
[Link] = age;
[Link] = gender;
// Method to display information
void displayInfo() {
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("Gender : " + gender);
[Link]("---------------------");
// Main method
public static void main(String[] args) {
Person p1 = new Person(); // Constructor 1
Person p2 = new Person("Ravi", 22); // Constructor 2
Person p3 = new Person("Sneha", 19, "Female"); // Constructor 3
[Link]();
[Link]();
[Link]();
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
3. Book Class with Constructor and Method
Create a class called Book with title, author, and price fields.
Write a constructor to initialize these fields, and a method
displayBookDetails() to print them.
CODE:
// Program 3: Book Class with Constructor and Method (Fixed)
public class Book {
String title;
String author;
double price;
// Constructor to initialize the fields
Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
// Method to display book details
void displayBookDetails() {
[Link]("Title : " + title);
[Link]("Author: " + author);
[Link]("Price : ₹" + price);
// ✅ Add main method here
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
public static void main(String[] args) {
Book book = new Book("Atomic Habits", "James Clear", 399.00);
[Link]();
4. Creating and Displaying a Book Object
In the main method, create an object of the Book class and call
displayBookDetails() to show the book's information.
CODE:
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
5. Factory Method in Book Class
Inside the Book class, create a method createBook(String title,
String author, double price) that returns a new Book object.
CODE:
// Program 5: Factory Method inside Book Class
public class Book {
String title;
String author;
double price;
// Constructor
Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
// Method to display book details
void displayBookDetails() {
[Link]("Title : " + title);
[Link]("Author: " + author);
[Link]("Price : ₹" + price);
// Factory Method
static Book createBook(String title, String author, double price) {
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
return new Book(title, author, price);
public static void main(String[] args) {
Book b1 = [Link]("Wings of Fire", "A.P.J Abdul Kalam", 350.00);
[Link]();
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
6. Comparing Book Prices
In the Book class, create a method comparePrice(Book
otherBook) that compares the price of the current book with
another book and prints which one is more expensive.
CODE:
// Program 6: Comparing Book Prices
public class Book {
String title;
String author;
double price;
Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
void displayBookDetails() {
[Link]("Title : " + title);
[Link]("Author: " + author);
[Link]("Price : ₹" + price);
// Method to compare prices
void comparePrice(Book otherBook) {
if ([Link] > [Link]) {
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
[Link]([Link] + " is more expensive than " + [Link]);
} else if ([Link] < [Link]) {
[Link]([Link] + " is more expensive than " + [Link]);
} else {
[Link]("Both books have the same price.");
public static void main(String[] args) {
Book book1 = new Book("Book A", "Author X", 250.0);
Book book2 = new Book("Book B", "Author Y", 300.0);
[Link](book2);
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
7. Object References in Student Class
Create a Student class with fields name and rollNumber.
Instantiate two student objects. Assign one object to another
and change a field. Observe how both references reflect the
change.
CODE:
// Program 7: Object References in Student Class
public class Student {
String name;
int rollNumber;
public static void main(String[] args) {
// Creating two student objects
Student s1 = new Student();
[Link] = "Rahul";
[Link] = 101;
Student s2 = new Student();
[Link] = "Anita";
[Link] = 102;
// Assigning s1 to s2 (both point to same object now)
s2 = s1;
// Changing the name using s2 reference
[Link] = "Changed Name";
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
SEIT2210 (OOPS WITH JAVA) 24SE02CS127
// Both references will reflect the change
[Link]("s1 Name: " + [Link]); // Changed Name
[Link]("s2 Name: " + [Link]); // Changed Name
PATEL ANSHITA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
ASSIGNMENT-3
——————————————————
To understand and implement the use of various access specifiers
in Java (private, default, protected, public) through simple
programs.
Assignment Questions
Q1. Demonstrate private Access Specifier
Write a Java class Student with private data members name and
age. Create getter and setter methods to access and modify these
private members. Then, in a Main class, create an object of Student
and access these members using getter and setter.
ú Hint: You cannot access private variables directly from outside
the class.
CODE: class Student {
private String name;
private int age;
// Setter for name
public void setName(String name) {
[Link] = name;
// Getter for name
public String getName() {
return name;
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
// Setter for age
public void setAge(int age) {
[Link] = age;
// Getter for age
public int getAge() {
return age;
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]("Anshita");
[Link](15);
[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q2. Demonstrate default (package-private) Access Specifier
Create two classes Teacher and School in the same package. In
Teacher, define a method displayInfo() with default access. Call this
method from the School class.
ú Note: Do not use any access specifier — that means it defaults
to package-private.
CODE: // Teacher class with default access method
class Teacher {
void displayInfo() {
[Link]("This is Teacher's Info (default access).");
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
// Main class to test default access
public class Main {
public static void main(String[] args) {
Teacher t = new Teacher();
[Link](); // Accessible because both classes are in the same file and package
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q3. Demonstrate protected Access Specifier via Inheritance
Create a class Employee with a protected method calculateSalary().
Then, extend this class in a Manager class and call the
calculateSalary() method inside it.
ú Try to understand how protected access works within
subclasses even if they are in different packages.
CODE: class Employee {
protected void calculateSalary() {
[Link]("Calculating salary in Employee (protected method)");
public class Main {
public static void main(String[] args) {
Manager m = new Manager();
[Link]();
class Manager extends Employee {
void callSalary() {
calculateSalary(); // Accessible due to inheritance and protected
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q4. Demonstrate public Access Specifier
Create a class Book with a public method showDetails() and call it
from another class in the same or different package.
ú Public methods can be accessed from anywhere.
CODE: class Book {
public void showDetails() {
[Link]("Showing book details (public method).");
public class Main {
public static void main(String[] args) {
Book b = new Book();
[Link](); // Public method, accessible from anywhere
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q5. Mixed Access Specifiers: One Program Using All
Create a class BankAccount with:
• private balance,
• default account number,
• protected method calculateInterest(),
• public method displayAccount().
CODE: class BankAccount {
private double balance = 10000.0; // private
int accountNumber = 12345678; // default (package-private)
protected double calculateInterest() { // protected
return balance * 0.05;
}
public void displayAccount() { // public
[Link]("Account Number: " + accountNumber);
[Link]("Balance: ₹" + balance);
[Link]("Interest: ₹" + calculateInterest());
}
}
public class Main {
public static void main(String[] args) {
BankAccount ba = new BankAccount();
[Link]();
}
}
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
CSE3B OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
ASSIGNMENT 4
——————————————————————
Q1. Use Method Overloading
Task:
Create a class CircleCalculator with:
• An overloaded method area():
o area(double radius) → returns area of circle.
o area(double radius, double pi) → returns area using custom
pi value.
• In the main() method, call both versions with appropriate
values.
CODE: class CircleCalculator {
// Method 1: Uses default pi
double area(double radius) {
return 3.14159 * radius * radius;
// Method 2: Uses custom pi
double area(double radius, double pi) {
return pi * radius * radius;
public static void main(String[] args) {
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
CircleCalculator cc = new CircleCalculator();
[Link]("Area with default pi: " + [Link](5.0));
[Link]("Area with custom pi (3.14): " + [Link](5.0, 3.14));
Q2. Use Objects as Method Parameters
Task:
Create a class Rectangle with:
• Two variables length and breadth.
• A method compare(Rectangle r) which compares current
object with another.
• A method display() that prints dimensions.
Create two objects and compare them.
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
CODE: class Rectangle {
int length, breadth;
Rectangle(int l, int b) {
length = l;
breadth = b;
void compare(Rectangle r) {
if ([Link] == [Link] && [Link] == [Link])
[Link]("Rectangles are equal.");
else
[Link]("Rectangles are not equal.");
void display() {
[Link]("Length: " + length + ", Breadth: " + breadth);
public static void main(String[] args) {
Rectangle r1 = new Rectangle(10, 20);
Rectangle r2 = new Rectangle(10, 20);
[Link]();
[Link]();
[Link](r2);
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q3. Assigning Object Reference Variables
Task:
Create a class Student with:
• name, rollNo fields.
• A method showDetails() to print student data.
Create two objects s1 and s2. Then assign s2 = s1; and show
how changes to s1 affect s2.
CODE: class Student {
String name;
int rollNo;
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
void showDetails() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Anshita";
[Link] = 101;
Student s2 = new Student();
[Link] = "Rahul";
[Link] = 102;
s2 = s1; // s2 now refers to the same object as s1
[Link] = "Updated Name"; // changing s1 also affects s2
[Link]();
[Link](); // same output as s1
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q4. Demonstrate static, final, and this keyword
Task:
Create a class Employee with:
• final String company = "ABC Corp";
• A static counter to generate employeeID
• A constructor that uses this keyword to set name and ID
• A method display() that prints employee info.
Create multiple objects to see static counter behavior.
CODE: class Employee {
final String company = "ABC Corp";
static int counter = 0;
int empId;
String name;
Employee(String name) {
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
[Link] = name;
[Link] = ++counter;
void display() {
[Link]("Employee ID: " + empId + ", Name: " + name + ", Company: " +
company);
public static void main(String[] args) {
Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Bob");
Employee e3 = new Employee("Charlie");
[Link]();
[Link]();
[Link]();
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
Q5. Use finalize() and Garbage Collection
Task:
Create a class Book with:
• A constructor to print when object is created.
• A finalize() method to print when object is destroyed.
In main(), create and nullify multiple Book objects and call
[Link]()
CODE: class Book {
String title;
Book(String title) {
[Link] = title;
[Link]("Book created: " + title);
void destroy() {
[Link]("Book destroyed: " + title);
public static void main(String[] args) {
Book b1 = new Book("Java");
Book b2 = new Book("Python");
Book b3 = new Book("C++");
// Simulate destroying objects
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 PATEL ANSHITA
[Link]();
[Link]();
// Nullify references
b1 = null;
b2 = null;
[Link]("Objects b1 and b2 are now eligible for garbage collection.");
[Link]("End of main");
SEIT2210(OOPS WITH JAVA) CSE3B
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
Java Assignment: Arrays and ArrayList
——————————————————
Q1. Array Initialization and Display (1D & 2D)(user input)
a. Declare and initialize a 1D integer array with the first 5 prime
numbers taking
b. Declare and initialize a 2D array (3x3) with numbers from 1
to 9.
Write a program to display all elements of both arrays in
proper format.
CODE: import [Link];
public class ArrayInit {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// 1D array of first 5 prime numbers
int[] primes = {2, 3, 5, 7, 11};
[Link]("1D Array (Prime Numbers): ");
for (int i = 0; i < [Link]; i++) {
[Link](primes[i] + " ");
// 2D array 3x3 with numbers 1 to 9
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
int[][] matrix = new int[3][3];
int num = 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = num++;
[Link]("\n\n2D Array (3x3 Matrix):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i][j] + " ");
[Link]();
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
Q2. Sum of Elements in a 1D Array
Write a Java program to:
- Accept n numbers from the user and store them in a 1D array.
- Calculate and display the sum of all the elements.
CODE: import [Link];
public class SumArray {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
int sum = 0;
[Link]("Enter " + n + " numbers: ");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
sum += arr[i];
[Link]("Sum of array elements: " + sum);
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
Q3. Find Maximum Element in Array (1D)
Write a method that takes a 1D integer array as input and
returns the maximum
value in the array.
CODE: public class MaxInArray {
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < [Link]; i++) {
if (arr[i] > max) {
max = arr[i];
return max;
public static void main(String[] args) {
int[] numbers = {12, 45, 7, 23, 89, 34};
[Link]("Maximum value: " + findMax(numbers));
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
Q4. Search for an Element in a 1D Array (Linear Search)
Write a Java program to:
- Accept a number from the user.
- Search if the number exists in the array.
- Print its index if found; otherwise, print a message that it is
not found.
CODE: import [Link];
public class LinearSearch {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[] arr = {10, 20, 30, 40, 50};
[Link]("Enter number to search: ");
int key = [Link]();
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
int index = -1;
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) {
index = i;
break;
if (index != -1) {
[Link]("Element found at index: " + index);
} else {
[Link]("Element not found!");
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
Q5. ArrayList – Basic Operations
Create an ArrayList<String> for storing names of 5 fruits.
Perform the following:
- Add the names to the list.
- Display all fruit names using a loop.
CODE: import [Link];
public class ArrayListFruits {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
// Adding fruits
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("Orange");
[Link]("Grapes");
[Link]("Fruits in the list:");
for (String fruit : fruits) {
[Link](fruit);
Q6. ArrayList – Add, Remove, and Search
Create an ArrayList<Integer> and perform the following
operations:
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
- Add 5 numbers
- Remove one number by index
- Search for a number and print its index if found
CODE: import [Link];
public class ArrayListOps {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
// Adding 5 numbers
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link]("Original List: " + numbers);
// Remove by index
[Link](2); // removes element at index 2 (30)
[Link]("After removal: " + numbers);
// Search for a number
int searchNum = 40;
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
int index = [Link](searchNum);
if (index != -1) {
[Link](searchNum + " found at index: " + index);
} else {
[Link](searchNum + " not found!");
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA. 24SE02CS127
OBJECT ORIENTED PROGRAMMING WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
Assignment_6
Part A – Arrays
Q1. Check if Two Arrays are Equal
Write a Java program to check if two arrays are equal (same length and same elements in the
same order).
CODE: import [Link];
public class ArrayEqual {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 3, 4, 5};
boolean isEqual = [Link](arr1, arr2);
if (isEqual) {
[Link]("Both arrays are equal.");
} else {
[Link]("Arrays are not equal.");
Q2. Copy an Array into Another
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
Write a Java program to copy all elements from one array into another.
CODE: import [Link];
public class ArrayCopy {
public static void main(String[] args) {
int[] arr1 = {10, 20, 30, 40};
int[] arr2 = new int[[Link]];
// Copying
for (int i = 0; i < [Link]; i++) {
arr2[i] = arr1[i];
[Link]("Original Array: " + [Link](arr1));
[Link]("Copied Array: " + [Link](arr2));
Q3. Merge and Sort Two Arrays
Write a Java program to merge two arrays into a single array and then sort the result.
CODE: import [Link];
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
public class MergeSort {
public static void main(String[] args) {
int[] arr1 = {3, 5, 7};
int[] arr2 = {1, 4, 6};
int[] merged = new int[[Link] + [Link]];
[Link](arr1, 0, merged, 0, [Link]);
[Link](arr2, 0, merged, [Link], [Link]);
[Link](merged);
[Link]("Merged & Sorted Array: " + [Link](merged));
Q4. Search an Element in an Array
Write a Java program to search for an element in an array and display:
• The number of occurrences
• The positions (indices) where the element appears
CODE: public class SearchElement {
public static void main(String[] args) {
int[] arr = {5, 3, 7, 3, 9, 3};
int target = 3;
int count = 0;
[Link]("Element " + target + " found at indices: ");
for (int i = 0; i < [Link]; i++) {
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
if (arr[i] == target) {
[Link](i + " ");
count++;
}
}
[Link]("\nNumber of occurrences: " + count);
}
}
Part B – Strings
Q5. String Creation and Concatenation
Create one string using string literals and another using the new keyword, concatenate
them, and print the result.
CODE: public class StringConcat {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String(" World");
String result = s1 + s2;
[Link]("Concatenated String: " + result);
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
Q6. String Representation using valueOf()
Write a Java program to display the string representation of different data types using the
[Link]() method.
CODE: public class ValueOf {
public static void main(String[] args) {
int num = 100;
double d = 12.34;
boolean b = true;
String s1 = [Link](num);
String s2 = [Link](d);
String s3 = [Link](b);
[Link]("Integer to String: " + s1);
[Link]("Double to String: " + s2);
[Link]("Boolean to String: " + s3);
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
Q7. Find Second Occurrence of a Character
Write a Java program to find the second occurrence of the character 'a' in the string "java".
CODE: public class SecondOccurrence {
public static void main(String[] args) {
String str = "java";
char ch = 'a';
int firstIndex = [Link](ch);
int secondIndex = [Link](ch, firstIndex + 1);
if (secondIndex != -1) {
[Link]("Second occurrence of '" + ch + "' is at index: " +
secondIndex);
} else {
[Link]("Character does not occur twice.");
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
Q8. Reverse a String using Recursion
Write a Java program to reverse a string using recursion.
CODE: public class ReverseRecursion {
public static String reverse(String str) {
if ([Link]()) {
return str;
return reverse([Link](1)) + [Link](0);
public static void main(String[] args) {
String str = "hello";
[Link]("Original: " + str);
[Link]("Reversed: " + reverse(str));
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
Q9. Reverse a Sentence
Write a Java program to reverse the order of words in a sentence. Example:
Input : I am learning Java programming language.
Output: language programming Java learning am I
CODE: public class ReverseSentence {
public static void main(String[] args) {
String sentence = "I am learning Java programming language.";
String[] words = [Link](" ");
[Link]("Reversed Sentence: ");
for (int i = [Link] - 1; i >= 0; i--) {
[Link](words[i] + " ");
}
}
}
Q10. StringBuffer Capacity Write
a Java program to:
1. Display the default capacity of a StringBuffer.
2. Append more strings to increase its capacity.
CODE: public class StringBufferCapacity {
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
[Link]("Default Capacity: " + [Link]());
[Link]("Hello, this is a test to increase capacity.");
[Link]("After appending: " + sb);
[Link]("New Capacity: " + [Link]());
Q11. Delete Characters from String
Write a Java program to delete a character or substring from a given string.
CODE: public class DeleteChar {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
// Delete single character at index 5
[Link](5);
// Delete substring from index 0 to 4
[Link](0, 4);
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
[Link]("After Deletion: " + sb);
Q12. Use of StringTokenizer
Write a Java program using the StringTokenizer class to split a given string using space (" ")
as a delimiter and print each token separately.
CODE: import [Link];
public class StringTokenizer {
public static void main(String[] args) {
String str = "I am learning Java";
StringTokenizer st = new StringTokenizer(str, " ");
while ([Link]()) {
[Link]([Link]());
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127 CSE3B PATEL ANSHITA
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
Assignment-7
Q1. Single Inheritance
Write a Java program to demonstrate single inheritance.
• Create a parent class Employee with attributes name and salary,
and a method displayDetails().
• Create a child class Manager that extends Employee and adds
the attribute department.
• In the main() method, create an object of Manager and display
all details.
CODE:
class Employee {
String name;
double salary;
Employee(String name, double salary) {
[Link] = name;
[Link] = salary;
}
void displayDetails() {
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}
class Manager extends Employee {
String department;
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
Manager(String name, double salary, String department) {
super(name, salary); // calling parent constructor
[Link] = department;
}
void displayDetails() {
[Link]();
[Link]("Department: " + department);
}
}
public class SingleInheritanceDemo {
public static void main(String[] args) {
Manager m1 = new Manager("Alice", 50000, "IT");
[Link]();
}
}
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
Q2. Multilevel Inheritance
Write a Java program to demonstrate multilevel inheritance.
• Create a base class Person with attributes name and age.
• Derive a class Student from Person, adding the attribute rollNo.
• Further derive a class GraduateStudent from Student, adding
the attribute specialization.
• In the main() method, create an object of GraduateStudent and
display complete details.
CODE:
class Person {
String name;
int age;
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
class Student extends Person {
int rollNo;
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
Student(String name, int age, int rollNo) {
super(name, age);
[Link] = rollNo;
}
void display() {
[Link]();
[Link]("Roll No: " + rollNo);
}
}
class GraduateStudent extends Student {
String specialization;
GraduateStudent(String name, int age, int rollNo, String specialization) {
super(name, age, rollNo);
[Link] = specialization;
}
void display() {
[Link]();
[Link]("Specialization: " + specialization);
}
}
public class MultilevelInheritanceDemo {
public static void main(String[] args) {
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
GraduateStudent g1 = new GraduateStudent("Bob", 22, 101, "Computer
Science");
[Link]();
}
}
Q3. Hierarchical Inheritance
Write a Java program to demonstrate hierarchical inheritance.
• Create a parent class Shape with a method area().
• Derive a class Circle from Shape and override the area() method
to calculate the area of a circle.
• Derive a class Rectangle from Shape and override the area()
method to calculate the area of a rectangle.
• In the main() method, create objects of both Circle and
Rectangle and display their areas.
CODE:
class Shape {
void area() {
[Link]("Area of Shape is not defined");
}
}
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
class Circle extends Shape {
double radius;
Circle(double radius) {
[Link] = radius;
}
@Override
void area() {
double result = [Link] * radius * radius;
[Link]("Area of Circle: " + result);
}
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
@Override
void area() {
double result = length * width;
[Link]("Area of Rectangle: " + result);
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
PATEL ANSHITA CSE3B 24SE02CS127
}
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Circle c1 = new Circle(5);
Rectangle r1 = new Rectangle(4, 6);
[Link]();
[Link]();
}
}
OOPS WITH JAVA
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 Anshita
PATEL Patel
ANSHITA
24SE02CS115 SEIT2210
Assignment_8
Q.1 Write a Java program to demonstrate the use of the super keyword in the
following cases:
1. To call the parent class variable when the child class has a variable with the
same name.
2. To call the parent class method when it is overridden in the child class.
3. To call the parent class constructor from the child class.
Instructions:
• Create a parent class named Animal with a variable name, a method display(),
and a constructor.
• Create a child class named Dog that extends Animal, and use the super
keyword to:
o Access the parent’s variable.
o Call the parent’s display() method.
o Call the parent’s constructor.
• Write a main() method to test the above functionality.
Code:
class Animal {
String name = "Animal";
Animal() {
[Link]("Animal constructor called");
void display() {
[Link]("This is the Animal class display method");
class Dog extends Animal {
String name = "Dog";
AASTHA PATEL
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 Anshita
PATEL Patel
ANSHITA
24SE02CS115 SEIT2210
Dog() {
super();
[Link]("Dog constructor called");
@Override
void display() {
[Link]("This is the Dog class display method");
void showDetails() {
[Link]("Parent class variable: " + [Link]);
[Link]("Child class variable: " + [Link]);
[Link]();
[Link]();
public class SuperKeywordDemo {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
AASTHA PATEL
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 Anshita
PATEL Patel
ANSHITA
24SE02CS115 SEIT2210
Q.2 Write a Java program to demonstrate Method Overriding. Create a parent class
Animal with a method sound(). Derive two subclasses Dog and Cat which override
the sound() method to print their own sounds. In the main() method, create objects of
Dog and Cat and call their sound() method.
Code:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks: Woof Woof!");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows: Meow Meow!");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
}
}
AASTHA PATEL
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 Anshita
PATEL Patel
ANSHITA
24SE02CS115 SEIT2210
Q.3 Write a Java program to demonstrate Dynamic Method Dispatch (runtime
polymorphism) by creating a base class Animal with a method sound(). Derive two
subclasses Dog and Cat that override the sound() method. In the main program, use a
base class reference to call the overridden methods and show how the method to be
executed is decided at runtime.
Code:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks: Woof Woof!");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows: Meow Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();
a = new Cat();
[Link]();
}
}
AASTHA PATEL
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 Anshita
PATEL Patel
ANSHITA
24SE02CS115 SEIT2210
Q.4 Write a Java program to demonstrate the use of abstract class. Create an
abstract class Shape with an abstract method calculateArea(). Derive two subclasses:
• Circle (with radius)
• Rectangle (with length and breadth)
Each subclass should implement the calculateArea() method. In the main() method,
create objects of both subclasses and display their areas.
Code:
abstract class Shape {
abstract double calculateArea();
}
class Circle extends Shape {
double radius;
Circle(double radius) {
[Link] = radius;
}
@Override
double calculateArea() {
return [Link] * radius * radius;
}
}
class Rectangle extends Shape {
double length, breadth;
Rectangle(double length, double breadth) {
[Link] = length;
[Link] = breadth;
}
@Override
double calculateArea() {
return length * breadth;
AASTHA PATEL
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 Anshita
PATEL Patel
ANSHITA
24SE02CS115 SEIT2210
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
[Link]("Area of Circle: " + [Link]());
Shape rectangle = new Rectangle(4, 6);
[Link]("Area of Rectangle: " + [Link]());
}
}
AASTHA PATEL
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
Assignment_10: Exception Handling in Java
Question 1: Handling ArithmeticException using try-catch
• Write a program that accepts two numbers from the user.
• Perform division and handle the case when the denominator is zero using
try-catch.
• Display an appropriate error message when an exception occurs.
import [Link];
public class DivisionHandling {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter numerator: ");
int numerator = [Link]();
[Link]("Enter denominator: ");
int denominator = [Link]();
try {
int result = numerator / denominator;
[Link]("Result = " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
[Link]();
}
}
Output :
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
Question 2: Creating and Throwing a Custom Exception
• Create a user-defined exception class InvalidAgeException.
• Write a program that takes the age of a person as input.
• If the age is less than 18, throw the exception and handle it using catch.
• Display a suitable message such as “Not eligible for voting.”
import [Link];
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class VotingEligibility {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter age: ");
int age = [Link]();
try {
if (age < 18) {
throw new InvalidAgeException("Not eligible for voting.");
} else {
[Link]("Eligible for voting.");
}
} catch (InvalidAgeException e) {
[Link]("Exception caught: " + [Link]());
}
[Link]();
}
}
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
Output :
Question 3: Using throws with Input Validation
• Write a method checkNumber(int num) that throws an exception if the
number is
negative.
• In the main method, call checkNumber() inside a try-catch block.
• Handle the exception and display a proper message.
import [Link];
public class NumberValidation {
static void checkNumber(int num) throws Exception {
if (num < 0) {
throw new Exception("Number cannot be negative!");
} else {
[Link]("Valid number: " + num);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
try {
checkNumber(number);
} catch (Exception e) {
[Link]("Exception caught: " + [Link]());
}
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
[Link]();
}
}
Output :
Question 4: Using finally Block
• Write a program that performs division of two numbers entered by the user.
• Use try-catch to handle exceptions.
• Use the finally block to print the message “Execution Completed” whether
an
exception occurs or not.
import [Link];
public class DivisionWithFinally {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter numerator: ");
int numerator = [Link]();
[Link]("Enter denominator: ");
int denominator = [Link]();
try {
int result = numerator / denominator;
[Link]("Result = " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
} finally {
[Link]("Execution Completed");
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
[Link]();
}
}
Output :
Question 5: Combining try, catch, throw, throws, and finally
• Create a class BankAccount with a balance.
• Write a method withdraw(int amount) that throws a custom
exception InsufficientBalanceException if the withdrawal amount is
greater than the balance.
• Handle this exception using try-catch in the main method.
• Ensure that the message “Transaction Ended” is displayed using the finally
block.
import [Link];
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
class BankAccount {
private int balance;
public BankAccount(int balance) {
[Link] = balance;
}
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
public void withdraw(int amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient Balance! Your
balance is " + balance);
} else {
balance -= amount;
[Link]("Withdrawal successful. Remaining balance: " +
balance);
}
}
}
public class BankingApp {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
BankAccount account = new BankAccount(5000);
[Link]("Enter withdrawal amount: ");
int amount = [Link]();
try {
[Link](amount);
} catch (InsufficientBalanceException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("Transaction Ended");
}
[Link]();
}
}
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS046 Object Oriented Programming with Java
Italia Vishwa SEIT2210
Output :
OBJECT ORIENTED
OOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210 CSE3B
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
Multithreading in Java – Assignment Questions
Q1. Creating a Thread (Extending Thread Class).
Write a Java program to create a thread by extending the Thread class.
The thread should display numbers from 1 to 10.
Ans:- class NumberThread2 extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
[Link](i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}
public class NumberThread1 {
public static void main(String[] args) {
NumberThread2 thread = new NumberThread2();
[Link]();
}
}
Q2. Creating a Thread (Implementing Runnable Interface).
Write a Java program to create a thread by implementing the Runnable
interface. The thread should print a message five times: "Hello from
Runnable Thread!".
Ans:-class RunnableThread implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
[Link]("Hello from Runnable Thread!");
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}
public class NumberThread1 {
public static void main(String[] args) {
RunnableThread runnable = new RunnableThread();
Thread thread = new Thread(runnable);
[Link]();
}
}
Q3. Life Cycle of a Thread.
Write a Java program to demonstrate the life cycle of a thread.
(New → Runnable → Running → Waiting → Terminated). Use sleep() and
join() methods to show different states.
Ans:- class LifeCycleThread extends Thread {
public void run() {
[Link]("Thread state inside run(): " +
[Link]().getState());
try {
[Link]("Thread going to sleep (Waiting state)...");
[Link](2000);
[Link]("Thread woke up, running again...");
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
[Link]("Thread run() method finishing (Terminated
soon)...");
}
}
public class NumberThread1 {
public static void main(String[] args) {
LifeCycleThread thread = new LifeCycleThread();
[Link]("After creation, thread state: " + [Link]());
[Link]();
[Link]("After start(), thread state: " + [Link]());
try {
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}
[Link]("After thread finishes, thread state: " +
[Link]());
}
}
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
Q4. Thread Methods.
Write a program that creates two threads and demonstrates the following
thread methods: - sleep() - join() - isAlive() Show their effect in the output.
Ans:- class MyThread extends Thread {
private String threadName;
MyThread(String name) {
[Link] = name;
}
public void run() {
[Link](threadName + " started.");
for (int i = 1; i <= 5; i++) {
[Link](threadName + " prints: " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
[Link](threadName + " finished.");
}
}
public class NumberThread1 {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
[Link]();
[Link]();
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
[Link]("Is Thread-1 alive? " + [Link]());
[Link]("Is Thread-2 alive? " + [Link]());
try {
[Link]();
[Link]("Thread-1 has finished; now main thread will wait
for Thread-2.");
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("Is Thread-1 alive after join? " + [Link]());
[Link]("Is Thread-2 alive after join? " + [Link]());
[Link]("Main thread exiting.");
}
}
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
Q5. Thread Priority.
Create three threads with different priorities (MAX_PRIORITY,
NORM_PRIORITY, MIN_PRIORITY). Each thread should print its name 5
times. Observe the output and explain whether priority affects execution
order.
Ans:- class PriorityThread extends Thread {
public PriorityThread(String name) {
super(name);
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](getName() + " is running, count: " + i);
try {
[Link](200);
} catch (InterruptedException e) {
[Link](getName() + " interrupted.");
}
}
}
}
public class NumberThread1 {
public static void main(String[] args) {
PriorityThread t1 = new PriorityThread("MAX_PRIORITY Thread");
PriorityThread t2 = new PriorityThread("NORM_PRIORITY Thread");
PriorityThread t3 = new PriorityThread("MIN_PRIORITY Thread");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MIN_PRIORITY);
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
[Link]();
[Link]();
[Link]();
}
}
Q6. Thread Synchronization.
Create a class Printer with a method printTable(int n) that prints the
multiplication table of a given number. - Create two threads that share the
same Printer object. - Demonstrate the difference in output with and without
synchronization.
Ans:-class Printer {
public void printTableUnsynchronized(int n) {
for (int i = 1; i <= 5; i++) {
[Link](n + " * " + i + " = " + (n * i));
try {
[Link](100);
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
public synchronized void printTableSynchronized(int n) {
for (int i = 1; i <= 5; i++) {
[Link](n + " * " + i + " = " + (n * i));
try {
[Link](100);
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}
class MyThread extends Thread {
Printer printer;
int number;
boolean useSync;
MyThread(Printer printer, int number, boolean useSync) {
[Link] = printer;
[Link] = number;
[Link] = useSync;
}
public void run() {
if (useSync) {
[Link](number);
} else {
[Link](number);
}
}
}
public class NumberThread1 {
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
public static void main(String[] args) {
Printer printer = new Printer();
[Link]("---- Without Synchronization ----");
MyThread t1 = new MyThread(printer, 5, false);
MyThread t2 = new MyThread(printer, 10, false);
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("\n---- With Synchronization ----");
MyThread t3 = new MyThread(printer, 5, true);
MyThread t4 = new MyThread(printer, 10, true);
[Link]();
[Link]();
}
}
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
Q7. Inter-thread Communication.
Write a Java program to demonstrate inter-thread communication using
wait(), notify(), and notifyAll(). Example scenario: A Customer thread tries
to withdraw money from an account, but must wait until another thread
deposits enough balance.
Ans:- class Account {
private int balance = 0;
public synchronized void withdraw(int amount) {
[Link]("Customer tries to withdraw " + amount);
while (balance < amount) {
[Link]("Insufficient balance. Waiting for deposit...");
try {
wait();
} catch (InterruptedException e) {
[Link]("Withdraw thread interrupted.");
}
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
}
balance -= amount;
[Link]("Withdrawal successful! New balance: " + balance);
}
// Deposit method adds money and notifies waiting threads
public synchronized void deposit(int amount) {
[Link]("Depositing " + amount);
balance += amount;
[Link]("Deposit complete. New balance: " + balance);
notifyAll(); // Notify all waiting threads
}
}
class Customer extends Thread {
private Account account;
private int amount;
Customer(Account account, int amount) {
[Link] = account;
[Link] = amount;
}
public void run() {
[Link](amount);
}
}
class Deposit extends Thread {
private Account account;
private int amount;
Deposit(Account account, int amount) {
[Link] = account;
[Link] = amount;
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS134 SHREYANSH RAI
public void run() {
try {
[Link](2000);
} catch (InterruptedException e) {
[Link]("Deposit thread interrupted.");
}
[Link](amount);
}
}
public class NumberThread1 {
public static void main(String[] args) {
Account account = new Account();
Customer customer = new Customer(account, 1000);
Deposit deposit = new Deposit(account, 2000);
[Link]();
[Link]();
}
}
OBJECT ORIENTED
OOOPS WITH JAVA PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127. ANSHITA PATEL
Java Swing Assignment - Questions and Answers
Q1. Simple Calculator Using Java Swing
Write a Java Swing program to create a simple calculator that can perform Addition,
Subtraction, Multiplication, and Division of two numbers.
Java Code:
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleCalculator extends JFrame implements ActionListener {
JTextField t1, t2, result;
JButton add, sub, mul, div;
SimpleCalculator() {
setLayout(new FlowLayout());
t1 = new JTextField(10);
t2 = new JTextField(10);
result = new JTextField(10);
[Link](false);
add = new JButton("Add");
sub = new JButton("Subtract");
mul = new JButton("Multiply");
div = new JButton("Divide");
add(t1); add(t2);
add(add); add(sub); add(mul); add(div);
add(result);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
setSize(250, 250);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127. ANSHITA PATEL
public void actionPerformed(ActionEvent e) {
try {
double n1 = [Link]([Link]());
double n2 = [Link]([Link]());
double res = 0;
if ([Link]() == add) res = n1 + n2;
else if ([Link]() == sub) res = n1 - n2;
else if ([Link]() == mul) res = n1 * n2;
else if ([Link]() == div) res = n1 / n2;
[Link]([Link](res));
} catch (Exception ex) {
[Link]("Error");
}
}
public static void main(String[] args) {
new SimpleCalculator();
}
}
Example Output Screenshot:
Q2. Bill Generation Application Using Java Swing
Create a Java Swing application to generate bills in a retail store. The app should allow the
user to:
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127. ANSHITA PATEL
1. Select items using a JComboBox.
2. Enter quantity and price in text fields.
3. Apply discount using a JCheckBox.
4. Choose payment method with JRadioButtons (Cash/Credit).
5. Add items and generate the bill in a JTextArea using a Submit button.
6. Use Drag and Drop to move items into a selection list.
Java Code:
import [Link].*;
import [Link].*;
import [Link].*;
public class BillGenerator extends JFrame implements ActionListener {
JComboBox<String> items;
JTextField qty, price;
JCheckBox discount;
JRadioButton cash, credit;
JButton submit;
JTextArea output;
ButtonGroup paymentGroup;
BillGenerator() {
setLayout(new FlowLayout());
items = new JComboBox<>(new String[]{"Pen", "Book", "Pencil"});
qty = new JTextField(5);
price = new JTextField(5);
discount = new JCheckBox("Apply 10% Discount");
cash = new JRadioButton("Cash");
credit = new JRadioButton("Credit");
paymentGroup = new ButtonGroup();
[Link](cash);
[Link](credit);
submit = new JButton("Generate Bill");
output = new JTextArea(10, 30);
[Link](false);
add(items); add(qty); add(price); add(discount);
add(cash); add(credit);
add(submit); add(new JScrollPane(output));
[Link](this);
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210
24SE02CS127 PATEL ANSHITA
24SE02CS127. ANSHITA PATEL
setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String item = (String) [Link]();
int q = [Link]([Link]());
double p = [Link]([Link]());
double total = q * p;
if ([Link]()) total *= 0.9;
String pay = [Link]() ? "Cash" : "Credit";
[Link]("Item: " + item + "\nQty: " + q + "\nPrice: " + p +
"\nDiscount: " + ([Link]() ? "Yes" : "No") +
"\nPayment: " + pay + "\nTotal: " + total);
}
public static void main(String[] args) {
new BillGenerator();
}
}
Example Output Screenshot:
OBJECT ORIENTED PROGRAMMING WITH JAVA - SEIT2210