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

Java Lab Manual Pgms 2024 (R22)

Uploaded by

A V Krishna Sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

Java Lab Manual Pgms 2024 (R22)

Uploaded by

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

G.

NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE


(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Lab Cycle – 1

1. Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula. If the discriminant

PROGRAM:
import java.util.Scanner;
public class QuadraticEquation
{
public static void main(String[] Strings)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = input.nextDouble();
System.out.print("Enter the value of b: ");
double b = input.nextDouble();
System.out.print("Enter the value of c: ");
double c = input.nextDouble();
double d= b * b - 4.0 * a * c;
if (d> 0.0)
{
double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else if (d == 0.0)
{
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
}
else
{
System.out.println("Roots are not real.");
}
}
}

Output:
Output 1:

Page No. 1
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Output 2:

2. Write a Java program that checks whether the given string is a palindrome or not.

Page No. 2
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

PROGRAM:
import java.util.Scanner;
public class PalindromeChecker
{
public static void main(String[] args) {
// Create a scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Ask for input from the user
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Check if the input is a palindrome
if (isPalindrome(input)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
// Method to check if the string is a palindrome
public static boolean isPalindrome(String str) {
// Convert the string to lower case and remove non-alphanumeric characters
str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Use two pointers to check if the string reads the same from both ends
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false; // Not a palindrome
}
left++;
right--;
}
return true; // The string is a palindrome
}
}

Output: Enter a string: A man, a plan, a canal, Panama


The string is a palindrome.

3. Write a Java program to multiply given 3X3 matrices.

PROGRAM:
import java.util.Scanner;

Page No. 3
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

public class MatrixMultiplication {

public static void main(String[] args) {


// Create a scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Declare two 3x3 matrices and a result matrix


int[][] matrix1 = new int[3][3];
int[][] matrix2 = new int[3][3];
int[][] result = new int[3][3];

// Input for Matrix 1


System.out.println("Enter elements for Matrix 1 (3x3):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("Enter element at position (" + (i+1) + "," + (j+1) + "): ");
matrix1[i][j] = scanner.nextInt();
}
}

// Input for Matrix 2


System.out.println("Enter elements for Matrix 2 (3x3):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print("Enter element at position (" + (i+1) + "," + (j+1) + "): ");
matrix2[i][j] = scanner.nextInt();
}
}

// Matrix Multiplication (Matrix1 * Matrix2)


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
result[i][j] = 0; // Initialize the result matrix element to 0
for (int k = 0; k < 3; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Output the result matrix
System.out.println("Resultant Matrix (Matrix 1 * Matrix 2):");

Page No. 4
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

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


for (int j = 0; j < 3; j++) {
System.out.print(result[i][j] + "\t");
}
System.out.println(); // For new line after each row
}
// Close the scanner
scanner.close();
}
}

Output:
Enter elements for Matrix 1 (3x3):
Enter element at position (1,1): 1
Enter element at position (1,2): 2
Enter element at position (1,3): 3
Enter element at position (2,1): 4
Enter element at position (2,2): 5
Enter element at position (2,3): 6
Enter element at position (3,1): 7
Enter element at position (3,2): 8
Enter element at position (3,3): 9

Enter elements for Matrix 2 (3x3):


Enter element at position (1,1): 9
Enter element at position (1,2): 8
Enter element at position (1,3): 7
Enter element at position (2,1): 6
Enter element at position (2,2): 5
Enter element at position (2,3): 4
Enter element at position (3,1): 3
Enter element at position (3,2): 2
Enter element at position (3,3): 1

4. Write a Java program that accepts a number from the end-user and then prints
all prime numbers up to a given number.

PROGRAM:
import java.util.Scanner;

Page No. 5
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

public class PrimeNumberGenerator {

public static void main(String[] args) {


// Create a scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Ask the user for input


System.out.print("Enter a number: ");
int num = scanner.nextInt();

// Check if the input is less than 2 (no primes less than 2)


if (num < 2) {
System.out.println("There are no prime numbers less than 2.");
} else {
System.out.println("Prime numbers up to " + num + " are:");
// Loop through numbers from 2 to the input number
for (int i = 2; i <= num; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}

// Close the scanner to avoid resource leak


scanner.close();
}

// Method to check if a number is prime


public static boolean isPrime(int n) {
// Handle special cases
if (n <= 1) {
return false;
}
if (n == 2) {
return true; // 2 is a prime number
}

// Check divisibility from 2 up to the square root of n


for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {

Page No. 6
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

return false; // Not a prime number


}
}

return true; // It's a prime number


}
}

Output:

Enter a number: 20
Prime numbers up to 20 are:
2 3 5 7 11 13 17 19

5. Write a Java program to create a Box class with properties like length, breadth,
width, and volume. Display the volume of 2 different boxes by using objects.

PROGRAM:
class Box {
// Properties of the Box
double length;
double breadth;

Page No. 7
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

double width;

// Constructor to initialize the box properties


public Box(double length, double breadth, double width) {
this.length = length;
this.breadth = breadth;
this.width = width;
}

// Method to calculate the volume of the box


public double calculateVolume() {
return length * breadth * width;
}

// Method to display the box details


public void displayVolume() {
System.out.println("Volume of the box is: " + calculateVolume() + " cubic units");
}
}

public class BoxVolumeCalculator {


public static void main(String[] args) {
// Creating two box objects with different dimensions
Box box1 = new Box(3.0, 4.0, 5.0); // Box 1 with length = 3, breadth = 4, width = 5
Box box2 = new Box(6.0, 7.0, 8.0); // Box 2 with length = 6, breadth = 7, width = 8

// Display the volume of both boxes


System.out.println("Box 1:");
box1.displayVolume(); // Display the volume of box 1

System.out.println("\nBox 2:");
box2.displayVolume(); // Display the volume of box 2
}
}

Output:

Box 1:
Volume of the box is: 60.0 cubic units

Box 2:

Page No. 8
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Volume of the box is: 336.0 cubic units

6. Write a Java program that demonstrates constructor overloading.

PROGRAM:

class Rectangle {

// Properties of the Rectangle class


double length;

Page No. 9
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

double breadth;

// Default constructor (no parameters)


public Rectangle() {
length = 1.0; // Default length
breadth = 1.0; // Default breadth
System.out.println("Default constructor called");
}

// Parameterized constructor with one argument


public Rectangle(double side) {
length = side; // Both sides of the square are equal
breadth = side;
System.out.println("Constructor with one parameter called");
}

// Parameterized constructor with two arguments


public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
System.out.println("Constructor with two parameters called");
}

// Method to calculate area of the rectangle


public double calculateArea() {
return length * breadth;
}

Page No. 10
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

// Method to display the rectangle dimensions and area


public void displayDetails() {
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
System.out.println("Area: " + calculateArea());
}
}

public class ConstructorOverloadingExample {


public static void main(String[] args) {
// Create objects using different constructors
System.out.println("Creating Rectangle 1:");
Rectangle rect1 = new Rectangle(); // Default constructor

System.out.println("\nCreating Rectangle 2:");


Rectangle rect2 = new Rectangle(5.0); // Constructor with one argument (square)

System.out.println("\nCreating Rectangle 3:");


Rectangle rect3 = new Rectangle(4.0, 6.0); // Constructor with two arguments (rectangle)

// Display details of each rectangle


System.out.println("\nDetails of Rectangle 1:");
rect1.displayDetails();

System.out.println("\nDetails of Rectangle 2:");


rect2.displayDetails();

System.out.println("\nDetails of Rectangle 3:");

Page No. 11
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

rect3.displayDetails();
}
}
Output:
Creating Rectangle 1:
Default constructor called

Creating Rectangle 2:
Constructor with one parameter called

Creating Rectangle 3:
Constructor with two parameters called

Details of Rectangle 1:
Length: 1.0
Breadth: 1.0
Area: 1.0

Details of Rectangle 2:
Length: 5.0
Breadth: 5.0
Area: 25.0

Details of Rectangle 3:
Length: 4.0
Breadth: 6.0
Area: 24.0

Page No. 12
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

7. Write a Java program to implement the use of inner classes.

PROGRAM:
class OuterClass {

// Instance variable of the outer class


private String outerMessage = "Hello from OuterClass!";

// Regular inner class (non-static inner class)


class InnerClass {
// Method of the inner class
public void displayMessage() {
// Accessing the outer class's private variable
System.out.println(outerMessage);
}
}

Page No. 13
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

// Static nested class


static class StaticNestedClass {
// Method of the static nested class
public void displayMessage() {
System.out.println("Hello from StaticNestedClass!");
}
}

// Method in the outer class to create and return the inner class object
public void createInnerClassObject() {
InnerClass inner = new InnerClass();
inner.displayMessage();
}
}

public class InnerClassExample {


public static void main(String[] args) {
// Creating an object of the outer class
OuterClass outer = new OuterClass();

// Creating an object of the inner class and calling its method


OuterClass.InnerClass inner = outer.new InnerClass();
inner.displayMessage(); // This will print "Hello from OuterClass!"

// Calling the method in the outer class to demonstrate the inner class usage
outer.createInnerClassObject(); // This will also print "Hello from OuterClass!"

// Creating an object of the static nested class and calling its method
OuterClass.StaticNestedClass staticNested = new OuterClass.StaticNestedClass();
staticNested.displayMessage(); // This will print "Hello from StaticNestedClass!"
}
}

Output:

Hello from OuterClass!


Hello from OuterClass!
Hello from StaticNestedClass!

Page No. 14
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Lab Cycle-2

1. Write a Java program that demonstrates the following:


i. Method overloading
ii. Method overriding.

Method overloading
PROGRAM:
public class MethodOverloadingDemo {

// Method to calculate the area of a rectangle


public double calculateArea(double length, double width) {
return length * width;
}

// Overloaded method to calculate the area of a square

Page No. 15
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

public double calculateArea(double side) {


return side * side;
}

// Overloaded method to calculate the area of a circle


public double calculateArea(double radius, boolean isCircle) {
if (isCircle) {
return Math.PI * radius * radius;
} else {
throw new IllegalArgumentException("Invalid use of the method. Use proper
parameters.");
}
}

public static void main(String[] args) {


MethodOverloadingDemo demo = new MethodOverloadingDemo();

// Calculate the area of a rectangle


double rectangleArea = demo.calculateArea(5.0, 10.0);
System.out.println("Area of the rectangle: " + rectangleArea);

// Calculate the area of a square


double squareArea = demo.calculateArea(4.0);
System.out.println("Area of the square: " + squareArea);

// Calculate the area of a circle


double circleArea = demo.calculateArea(7.0, true);
System.out.println("Area of the circle: " + circleArea);
}
}
Output:
Area of the rectangle: 50.0
Area of the square: 16.0
Area of the circle: 153.93804002589985

Method overriding
PROGRAM:
class Animal {
// Method to be overridden
public void makeSound() {

Page No. 16
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

System.out.println("Some generic animal sound");


}
}

class Dog extends Animal {


// Overriding the makeSound method
@Override
public void makeSound() {
System.out.println("Woof! Woof!");
}
}

class Cat extends Animal {


// Overriding the makeSound method
@Override
public void makeSound() {
System.out.println("Meow! Meow!");
}
}

public class MethodOverridingDemo {


public static void main(String[] args) {
// Creating objects of different subclasses
Animal genericAnimal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();

// Calling the overridden methods


System.out.println("Generic Animal Sound:");
genericAnimal.makeSound();

System.out.println("Dog Sound:");
dog.makeSound();

System.out.println("Cat Sound:");
cat.makeSound();
}
}

Output:
Generic Animal Sound:

Page No. 17
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Some generic animal sound


Dog Sound:
Woof! Woof!
Cat Sound:
Meow! Meow!

2. A program to create an abstract class named ‘Shape’ that contains two integers
and an empty method named printArea( ), providing three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each
one of the classes contains only the method printArea( ) that prints the area of the
given shape.

PROGRAM:

abstract class Shape


{
abstract void printArea();
}
class Triangle extends Shape
{
void printArea()
{
int base,height;
float area;

Page No. 18
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

try
{
System.out.println("Enter base and height of a triangle");
DataInputStream in=new DataInputStream(System.in);
base=Integer.parseInt(in.readLine());
height=Integer.parseInt(in.readLine());
area=(float)(0.5*base*height);
System.out.println("The area of triangle is "+area);
}
catch(Exception e){}
}
}

class Rect extends Shape


{
void printArea()
{
int len;
int brd;
float area;
try
{
System.out.println("Enter length and breadth of a rectangle");
DataInputStream in=new DataInputStream(System.in);
len=Integer.parseInt(in.readLine());
brd=Integer.parseInt(in.readLine());
area=(float)(len*brd);
System.out.println("The area of rectangle is "+area);
}
catch(Exception e){}
}

Page No. 19
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

class Circle extends Shape {


void printArea()
{
int radius;
float area;
try
{
System.out.println("Enter radius of a circle");
DataInputStream in=new DataInputStream(System.in);
radius=Integer.parseInt(in.readLine());
area=(float)(3.14*radius*radius);
System.out.println("The area of circle is "+area);
}
catch(Exception e){}
}
}
class AbstractDemo
{
public static void main(String args[])
{
Shape s;
Rect r=new Rect();
Triangle t=new Triangle();
Circle c=new Circle();
s=r;
s.printArea();
s=t;
s.printArea();
s=c;
s.printArea();
}
}

Output:

Page No. 20
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Area of Rectangle: 200


Area of Triangle: 75.0
Area of Circle: 153.93804002589985

3. Write a Java program that implements multiple inheritance.

interface Printable {
void print();
}

interface Showable {
void show();
}

class MultipleInheritanceDemo implements Printable, Showable {


@Override
public void print() {
System.out.println("This is the print method from the Printable interface.");
}

@Override
public void show() {
System.out.println("This is the show method from the Showable interface.");
}

public static void main(String[] args) {

Page No. 21
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

MultipleInheritanceDemo demo = new MultipleInheritanceDemo();

// Calling methods from both interfaces


demo.print();
demo.show();
}
}

Output:
This is the print method from the Printable interface.
This is the show method from the Showable interface.

4. Program that implements a multi-threaded application that has three threads. First thread
generates random integer every 1 sec, if the value is even- second thread computes the
square of the number and prints. If the value is odd, the third thread will print the value of
cube of the number.

PROGRAM:
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{

Page No. 22
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread
{
public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
} else
{
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

Page No. 23
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

public class JavaProgram5


{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}

Output:
D:\JP>java JavaProgram5
Main Thread and Generated Number is 10
New Thread 10 is EVEN and Square of 10 is: 100
--------------------------------------
Main Thread and Generated Number is 14
New Thread 14 is EVEN and Square of 14 is: 196
--------------------------------------
Main Thread and Generated Number is 83
New Thread 83 is ODD and Cube of 83 is: 571787
--------------------------------------
Main Thread and Generated Number is 1
New Thread 1 is ODD and Cube of 1 is: 1
--------------------------------------
Main Thread and Generated Number is 20
New Thread 20 is EVEN and Square of 20 is: 400
--------------------------------------

Page No. 24
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

5. A java program that implements the producer – consumer problem using the concept
of Inter thread communication.

PROGRAM:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");

Page No. 25
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
try
{
while(true) {
Thread.sleep(30);
q.put(i++);
}
}
catch(Exception e)
{}

}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
try
{
while(true) {
Thread.sleep(30);
q.get();
}}
catch(Exception e)

Page No. 26
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

{}

}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Output:

Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Put: 6
Got: 6
Put: 7
Got: 7

Page No. 27
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

6. Write a Java program that handles all mouse events and shows the event name at
the center of the window when a mouse event is fired. (Use Adapter classes).

PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventDemo extends JFrame {


private String eventName = ""; // Stores the current mouse event name

public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Add a custom JPanel to handle painting the event name


EventPanel panel = new EventPanel();
add(panel);

// Add a MouseAdapter to handle mouse events


panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
panel.repaint();
}

@Override

Page No. 28
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

public void mousePressed(MouseEvent e) {


eventName = "Mouse Pressed";
panel.repaint();
}

@Override
public void mouseReleased(MouseEvent e) {
eventName = "Mouse Released";
panel.repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
eventName = "Mouse Entered";
panel.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
eventName = "Mouse Exited";
panel.repaint();
}
});
}
// Custom JPanel to draw the event name
class EventPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.setColor(Color.BLACK);
// Draw the event name at the center of the panel
FontMetrics metrics = g.getFontMetrics();
int x = (getWidth() - metrics.stringWidth(eventName)) / 2;
int y = getHeight() / 2;
g.drawString(eventName, x, y);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new MouseEventDemo().setVisible(true);
});
}

Page No. 29
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

OUTPUT:
Mouse Clicked
Mouse Pressed
Mouse Released
Mouse Entered
Mouse Exited

Lab Cycle-3

1. Write a Java program that creates a user interface to perform integer divisions. The
user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and
Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or
Num2 are not integers, the program would throw a Number Format Exception. If
Num2 is Zero, the program would throw an Arithmetic Exception. Display the excep-
tion in a message dialog box.

PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DivisionUI {


public static void main(String[] args) {
JFrame frame = new JFrame("Integer Division");
JLabel label1 = new JLabel("Num1:");
JLabel label2 = new JLabel("Num2:");
JLabel label3 = new JLabel("Result:");
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JTextField resultField = new JTextField(10);
JButton divideButton = new JButton("Divide");

resultField.setEditable(false);
frame.setLayout(new FlowLayout());
frame.add(label1);
frame.add(num1Field);
frame.add(label2);
frame.add(num2Field);

Page No. 30
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

frame.add(divideButton);
frame.add(label3);
frame.add(resultField);

divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 / num2;
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Please enter valid integers!",
"Error", JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
JOptionPane.showMessageDialog(frame, "Division by zero is not
allowed!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});

frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output 1:
Num1: 10
Num2: 2
Result: 5

Output 2:
Num1: abc
Num2: 5
Message Dialog: Please enter valid integers!

Page No. 31
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

2. Write a Java program that works as a simple calculator. Use a GridLayout to


arrange buttons for the digits and for the +, -, *, % operations. Add a text field
to display the result. Handle any possible exceptions like divide by zero.

PROGRAM:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="Calculator" width=300 height=300>
</applet>
*/

public class Calculator extends Applet


implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);

Page No. 32
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
mod=new Button("%");
clear=new Button("clear");
EQ=new Button("=");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
char ch=str.charAt(0);

Page No. 33
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("+"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("-"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("*"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("/"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("%"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("="))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')

Page No. 34
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}

Output:

Page No. 35
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

3.Write a Java program to connect to database and display Employee details


(eid,ename,address and phone no).

PROGRAM:
// Java Program to Insert Details in a Table using JDBC
// Connections class

// Importing all SQL classes


import java.sql.*;

public class connection {

// object of Connection class


// initially assigned NULL
Connection con = null;

public static Connection connectDB()

try {

// Step 2 is involved among 7 in Connection


// class i.e Load and register drivers

// 2(a) Loading drivers using forName() method


// name of database here is mysql
Class.forName("com.mysql.jdbc.Driver");

// 2(b) Registering drivers using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hotelman ",
"root", "1234");
// For DB here (custom sets)
// root is the username, and
// 1234 is the password

Page No. 36
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

// returning the object of Connection class


// to be used in main class (Example2)
return con;
}

// Catch block to handle the exceptions


catch (SQLException | ClassNotFoundException e) {

// Print the exceptions


System.out.println(e);

return null;
}
}
}

// Java Program to Insert Details in a Table using JDBC


// Main class

// Step 1: Importing DB classes


// DB is SQL here
import java.sql.*;

// Main/App class of above Connection class


public class GFG {

// MAin driver method


public static void main(String[] args)
{
// Step 2: Showing above Connection class i.e
// loading and registering drivers

// Initially assigning NULL parameters


// to object of Connection class
Connection con = null;
PreparedStatement ps = null;

// Step 3: Establish the connection


con = connection.connectDB();

// Try block to check if exception/s occurs

Page No. 37
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

try {

// Step 4: Create a statement


String sql = "insert into cuslogin
values('geeksforgeeks','gfg','[email protected]','flat 1','1239087474',10)";

// Step 5: Execute the query


ps = con.prepareStatement(sql);

// Step 6: Process the results


ps.execute();
}

// Optional but recommended


// Step 7: Close the connection

// Catch block to handle the exception/s


catch (Exception e) {

// Print the exception


System.out.println(e);
}
}
}

Output:

Page No. 38
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

4. Write a Java program to list all the files in a directory including the files
present in all its subdirectories.

PROGRAM:

import java.io.File;
public class files
{
public static void list(String dir) {
File file = null;
File[] paths;
try {
// create new file object
file = new File(dir);
// array of files and directory
paths = file.listFiles();
// for each name in the path array
for(File path:paths) {
// prints filename and directory name
System.out.println(path.getAbsolutePath());
if(path.isDirectory())
{
list(path.getAbsolutePath());
}
}
}catch(Exception e) {
// if any error occurs
e.printStackTrace();
}

Page No. 39
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

}
public static void main(String args[])
{
list("/home/user/swap");

}
}

Output:

/home/user/swap/g
/home/user/swap/lo
/home/user/swap/swap1
/home/user/swap/swap1/l
/home/user/swap/swap1/h

5. A program to create, delete and display the elements in a doubly linked list.

Page No. 40
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

PROGRAM:

import java.util.*;
import java.io.*;
public class LinkedListDemo
{
private static int NULL;
public static void main(String[] args) throws IOException{
// create a LinkedList
LinkedList<String> list = new LinkedList<String>();
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Scanner sin=new Scanner(System.in);
System.out.println("enter no of Strings");
int n=sin.nextInt();
System.out.println("enter Strings");
for(int i=1;i<=n;i++)
{
str=br.readLine();
list.add(str);}
System.out.println("LinkedList:" + list);
//deleting from list
System.out.println("enter the element to be deleted");

String g= sin.next();
int pos=list.indexOf(g);
if(pos==-1)
System.out.println("search element not found,deletion is not possible");
else
list.remove(g);
// print the list after deletion
System.out.println("LinkedList:" + list);

}
}

Output:

enter no of Strings

Page No. 41
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

3
enter Strings
rama
seetha
ravana
LinkedList:[rama, seetha, ravana]
enter the element to be deleted
ravana
LinkedList:[rama, seetha]

6.A java program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (\t). It
takes a name or phone number as input and prints the corresponding other value from the
hash table (hint: use hash tables).
Page No. 42
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

VIVA QUESTIONS

PROGRAM

import java.util.*;
import java.io.*;
public class PhoneDictionary
{
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("D:\\jp\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();

String[] arrayList;
String a;
System.out.println("Welcome TO G. Narayanamma Institute of Technology and Science
");
System.out.println("Student Phone numbers are");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("Welcome TO G.Narayanamma Institute of Technology and
Science");

Page No. 43
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

System.out.println("MENU");
System.out.println("1.Search by Name");
System.out.println("2.Search by Mobile");
System.out.println("3.Exit");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("Enter Your Option (1,2,3): ");
opt = s.next();
switch (opt)
{
case "1":
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
} else {
System.out.println("Not Found");
}
break;
case "2":
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile))
{

Page No. 44
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

for (Map.Entry e : ht.entrySet())


{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
break;
case "3":
opt = "3";
System.out.println("Menu Successfully Exited");
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}}}

INPUT: loads names and phone numbers from the text file named ph.txt:

Page No. 45
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

OUTPUT:
D:\JP>java PhoneDictionary

Student Phone numbers are


P.RaghuNandan:8977332085
P.Ronith:9052277577
Y.Srinish:9849039239
Y.Snikitha:9849098490
P.Rishikesh:9848098480
1.Search by Name
2.Search by Mobile
3.Exit
Enter Your Option( 1,2,3):
1
Enter Name
P.RaghuNandan
Mobile is 8977332085
Enter Your Option( 1,2,3):
2
Enter mobile
9849098490
Name is Y.Snikitha
Enter Your Option 1,2,3
3 Menu Successfully Exited

Viva Questions

1. What do you know about Java?

Page No. 46
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Java is a high-level programming language originally developed by Sun Microsystems


and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.

2. What are the supported platforms by Java Programming Language?


Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS,
etc.

3. List any five features of Java?


Some features include Object Oriented, Platform Independent, Robust, Interpreted,
Multi-threaded

4. Why is Java Architectural Neutral?


It’s compiler generates an architecture-neutral object file format, which makes the
compiled code to be executable on many processors, with the presence of Java runtime
system.

5. How Java enabled High Performance?


Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is
a program that turns Java bytecode, which is a program that contains instructions that
must be interpreted into instructions that can be sent directly to the processor.

6. Why Java is considered dynamic?


It is designed to adapt to an evolving environment. Java programs can carry extensive
amount of run-time information that can be used to verify and resolve accesses to
objects on run-time.

7. What is Java Virtual Machine and how it is considered in context of Java’s plat-
form independent feature?

Page No. 47
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

When Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.

8. List two Java IDE’s?


Netbeans, Eclipse, etc.

9. List some Java keywords(unlike C, C++ keywords)?


Some Java keywords are import, super, finally, etc.

10. What do you mean by Object?


Object is a runtime entity and it’s state is stored in fields and behavior is shown via
methods. Methods operate on an object's internal state and serve as the primary
mechanism for object-to-object communication.

11. Define class?


A class is a blue print from which individual objects are created. A class can contain
fields and methods to describe the behavior of an object.

12. What kind of variables a class can consist of?


A class consist of Local variable, instance variables and class variables.

13. What is a Local Variable?


Variables defined inside methods, constructors or blocks are called local variables. The
variable will be declared and initialized within the method and it will be destroyed
when the method has completed.

14. What is a Instance Variable?


Instance variables are variables within a class but outside any method. These variables
are instantiated when the class is loaded.

Page No. 48
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

15. What is a Class Variable?


These are variables declared with in a class, outside any method, with the static
keyword.

16. What is Singleton class?


Singleton class control object creation, limiting the number to one but allowing the
flexibility to create more objects if the situation changes.

17. What do you mean by Constructor?


Constructor gets invoked when a new object is created. Every class has a constructor. If
we do not explicitly write a constructor for a class the java compiler builds a default
constructor for that class.

18. List the three steps for creating an Object for a class?
An Object is first declared, then instantiated and then it is initialized.

19. What is the default value of byte datatype in Java?


Default value of byte datatype is 0.

20. What is the default value of float and double datatype in Java?
Default value of float and double datatype in different as compared to C/C++. For float
its 0.0f and for double it’s 0.0d

21. When a byte datatype is used?


This data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int.

22. What is a static variable?


Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.

Page No. 49
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

23. What do you mean by Access Modifier?


Java provides access modifiers to set access levels for classes, variables, methods and
constructors. A member has package or default accessibility when no accessibility
modifier is specified.

24. What is protected access modifier?


Variables, methods and constructors which are declared protected in a superclass can
be accessed only by the subclasses in other package or any class within the package of
the protected members' class.

25. When parseInt() method can be used?


This method is used to get the primitive data type of a certain String.

26. What is finalize() method?


It is possible to define a method that will be called just before an object's final
destruction by the garbage collector. This method is called finalize( ), and it can be
used to ensure that an object terminates cleanly.

27. What is an Exception?


An exception is a problem that arises during the execution of a program. Exceptions
are caught by handlers positioned along the thread's method invocation stack.

28. What do you mean by Checked Exceptions?


It is an exception that is typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be found, an
exception occurs. These exceptions cannot simply be ignored at the time of compilation.

29. Explain Runtime Exceptions?


It is an exception that occurs that probably could have been avoided by the programmer.
As opposed to checked exceptions, runtime exceptions are ignored at the time of
compliation.

Page No. 50
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

30. When throws keyword is used?


If a method does not handle a checked exception, the method must declare it using the
throws keyword. The throws keyword appears at the end of a method's signature.

31. When throw keyword is used?


An exception can be thrown, either a newly instantiated one or an exception that you
just caught, by using throw keyword.

32. How finally used under Exception Handling?


The finally keyword is used to create a block of code that follows a try block. A finally
block of code always executes, whether or not an exception has occurred.

33. What things should be kept in mind while creating your own exceptions in
Java?
While creating your own exception −
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
 You want to write a runtime exception, you need to extend the RuntimeExcep-
tion class.

34. Define Inheritance?


It is the process where one object acquires the properties of another. With the use of
inheritance the information is made manageable in a hierarchical order.

35. When super keyword is used?


If the method overrides one of its superclass's methods, overridden method can be
invoked through the use of the keyword super. It can be also used to refer to a hidden
field.
36. What is Polymorphism?

Page No. 51
G. NARAYANAMMA INSTITUTE OF TECHNOLOGY & SCIENCE
(Autonomous) (For Women)
DEPARTMENT OF CSE(AI & ML)
II B. Tech II Sem. 2024-25
Object Oriented Programming Through Java Lab

Polymorphism is the ability of an object to take on many forms. The most common use
of polymorphism in OOP occurs when a parent class reference is used to refer to a child
class object.
37. What is Abstraction?
It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity
and also improves the maintainability of the system.
38. What is Abstract class?
These classes cannot be instantiated and are either partially implemented or not at all
implemented. This class contains one or more abstract methods which are simply
method declarations without a body.
39. When Abstract methods are used?
If you want a class to contain a particular method but you want the actual implementa-
tion of that method to be determined by child classes, you can declare the method in
the parent class as abstract.
40. What is Encapsulation?
It is the technique of making the fields in a class private and providing access to the
fields via public methods. If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields within the class. Therefore
encapsulation is also referred to as data hiding.

Page No. 52

You might also like