Java Lab Manual Pgms 2024 (R22)
Java Lab Manual Pgms 2024 (R22)
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
}
}
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
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
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
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
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
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;
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
PROGRAM:
class Rectangle {
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;
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
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
PROGRAM:
class OuterClass {
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
// Method in the outer class to create and return the inner class object
public void createInnerClassObject() {
InnerClass inner = new InnerClass();
inner.displayMessage();
}
}
// 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:
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
Method overloading
PROGRAM:
public class MethodOverloadingDemo {
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
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("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
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:
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){}
}
}
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
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
interface Printable {
void print();
}
interface Showable {
void show();
}
@Override
public void show() {
System.out.println("This is the show method from the Showable interface.");
}
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
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
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 MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@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
@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.*;
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
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Calculator" width=300 height=300>
</applet>
*/
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);
}
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
PROGRAM:
// Java Program to Insert Details in a Table using JDBC
// Connections class
try {
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
return null;
}
}
}
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 {
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
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
Viva Questions
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
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.
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
18. List the three steps for creating an Object for a class?
An Object is first declared, then instantiated and then it is initialized.
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
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
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
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.
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