JAVA LAB PROGRAMS
1. Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, add a
test class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and code
refactoring like renaming variables, methods, and classes. Try debug step by step with a small program of
about 10 to 15 lines which contains at least one if else condition and a for loop.
//Prime or not Program
import [Link];
import [Link];
//Creating Class
class Sample_Program {
//main method
public static void main(String args[]) {
int i,count=0,n;
//Creating Scanner Object
Scanner sc=new Scanner([Link]);
//get input number from user
[Link]("Enter any number");
n=[Link]();
//logic to check prime or not
for(i=1;i<=n;i++) {
if(n%i==0) {
count++;
}
}
if(count==2)
[Link](n+" is prime");
else
[Link](n+" is not prime");
}
}
2. Write a Java program to create an abstract class named Shape that contains two integers and an empty
method named print Area (). Provide 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 print Area ()
that prints the area of the given shape.
import [Link];
abstract class Shape{
int length, breadth, radius, base, height;
Scanner input = new Scanner([Link]);
abstract void printArea();
}
class Rectangle extends Shape{
void printArea() {
[Link]("Finding the area of rectangle");
[Link]("Enter length and breadth: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of the rectangle is: " + (length * breadth));
}
}
class Triangle extends Shape{
void printArea() {
[Link]("Finding the area of triangle");
[Link]("Enter base and height: ");
base = [Link]();
height = [Link]();
[Link]("The area of the triangle is: " + (0.5 * base * height));
}
}
class Circle extends Shape{
void printArea() {
[Link]("Finding the area of circle");
[Link]("Enter radius: ");
radius = [Link]();
[Link]("The area of the circle is: " + ([Link] * radius * radius));
}
}
public class Main{
public static void main(String[] args) {
Rectangle rect = new Rectangle();
[Link]();
Triangle tri = new Triangle();
[Link]();
Circle circ = new Circle();
[Link]();
}
}
3. Write a Java program that implements Bubble sort algorithm for sorting in descending order and also
shows the number of interchanges occurred for the given set of integers.
import [Link];
public class BubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n, count = 0;
// Reading size of the list
[Link]("Enter the list size: ");
n = [Link]();
// Creating list with elements
int a[] = new int[n];
[Link]("Enter any" + n + "integer number: ");
for (int i = 0; i < n; i++)
a[i] = [Link]();
// Bubble sort logic
int temp = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n - i - 1; j++) {
if (a[j] < a[j + 1]){
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
count++;
}
}
}
//Displaying sorted list
[Link]("list of sorted elements: ");
for(int x:a)
{
[Link](x + " ");
}
[Link]("\nTotal number of Interchanges is" +count);
}
}
4. Write a Java program that implements Quick sort algorithm for sorting a list of names in ascending
order
public class QuickSortOnStrings {
String names[];
int length;
public static void main(String[] args) {
QuickSortOnStrings obj = new QuickSortOnStrings();
String stringList[] = {"Eren","Luffy","Naruto","Abra"};
[Link](stringList);
for(String i : stringList){
[Link](i);
[Link](" ");
}
}
void sort(String array[]){
if(array == null || [Link] == 0){
return;
}
[Link] = array;
[Link] = [Link];
quickSort(0, length-1);
}
void quickSort(int lowerIndex, int higherIndex){
int i = lowerIndex;
int j = higherIndex;
String pivot = [Link][lowerIndex + (higherIndex - lowerIndex)/2];
while (i<=j){
while ([Link][i].compareToIgnoreCase(pivot)<0){
i++;
}
while ([Link][j].compareToIgnoreCase(pivot)>0){
j--;
}
if(i<=j){
exchangeName(i, j);
i++;
j--;
}
}
if(lowerIndex<j){
quickSort(lowerIndex, j);
}
if(i<higherIndex){
quickSort(i, higherIndex);
}
}
void exchangeName(int i, int j){
String temp = [Link][i];
[Link][i] = [Link][j];
[Link][j] = temp;
}
}
5. Write a Java program for the following: Create a doubly linked list of elements. Delete a given element
from the above list. Display the contents of the list after deletion.
import [Link].*;
public class DoubleLinkListDemo {
public static void main(String[] args) {
int i,ch,element,position;
LinkedList<Integer>dblList = new LinkedList<>();
[Link]("1. Insert element at begining");
[Link]("2. Insert element at end");
[Link]("3. Insert element at position");
[Link]("4. Delete a given element");
[Link]("5. Display elements in the list");
[Link]("6. Exit");
Scanner sc = new Scanner([Link]);
do{
[Link]("Choose your choice(1-6): ");
ch = [Link]();
switch(ch){
case 1://To read element from the user
[Link]("Enter an element to insert at begining: ");
element=[Link]();
//To add element to doubly linked list at begining
[Link](element);
[Link]("Successfully Inserted");
break;
case 2://To read element from the user
[Link]("Enter an element to insert at end: ");
element = [Link]();
//To add element to doubly Linked List at end
[Link](element);
[Link]("Successfully Inserted");
break;
case 3://To read element from the user
[Link]("Enter position to insert element: ");
position=[Link]();
//checks if the position is lessthan or equal to list size
if(position <= [Link]()){
//To read element
[Link]("Enter element: ");
element=[Link]();
//to add element to doubly Linked List to given position
[Link](position,element);
[Link]("Successfully Inserted");
}
else{
[Link]("Enter the size between 0 to"+[Link]());
}
break;
case 4://To read element frm the user to remove
[Link]("Enter element to remove: ");
Integer ele_rm;
ele_rm = [Link]();
if([Link](ele_rm)){
[Link](ele_rm);
[Link]("Succesfully Deleted");
Iterator itr = [Link]();
[Link]("Elements after deleting:"+ele_rm);
while([Link]()){
[Link]([Link]()+"<->");
}
[Link]("NULL");
}
else{
[Link]("Element not found");
}
break;
case 5://To display elements in the list
Iterator itr = [Link]();
[Link]("Elements in the list:");
while ([Link]()){
[Link]([Link]()+"<->");
}
[Link]("NULL");
break;
case 6:
[Link]("Program terminated");
break;
default:
[Link]("Invalid choice");
}
}
while (ch!=6);
}
}
6. Write a Java program to list all the files in a directory including the files present in all its subdirectories.
import [Link];
import [Link].*;
public class ListingFiles
{
public static void main(String[] args)
{
String path = null;
Scanner read = new Scanner([Link]);
[Link]("Enter the root directory name: ");
path = [Link]() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists())
{
printLine();
[Link]("Root directory does not exists!");
printLine();
}
else
{
String ch = "y";
while ([Link]("y"))
{
printFiles(path);
[Link]("Do you want to open any sub-directory(Y/N): ");
ch = [Link]().toLowerCase();
if ([Link]("y"))
{
[Link]("Enter the sub-directory name: ");
path = path + "\\\\" + [Link]();
File f_ref_2 = new File(path);
if (!f_ref_2.exists())
{
printLine();
[Link]("The sub-directory does not exists!");
printLine();
int lastIndex = [Link]("\\");
path = [Link](0, lastIndex);
}
}
}
}
[Link]("** Program Closed **");
}
public static void printFiles(String path) {
[Link]("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList)
{
if ([Link]())
[Link]("- " + [Link]());
else
[Link]("> " + [Link]());
}
}
public static void printLine()
{
[Link]("----------------------------------------");
}
}
7. 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 Num 2 is displayed in the Result
field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw
a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception.
Display the exception in a message dialog box.
import [Link].*;
import [Link].*;
import [Link].*;
public class DivisionApp extends JFrame implements ActionListener {
JLabel L1, L2, L3;
JTextField T1, T2, Result;
JButton B1, B2;
public DivisionApp() {
setTitle("Division App");
setLayout(new GridLayout(4, 2, 5, 5)); // 4 rows, 2 columns with spacing
L1 = new JLabel("Enter First Num:");
add(L1);
T1 = new JTextField(10);
add(T1);
L2 = new JLabel("Enter Second Num:");
add(L2);
T2 = new JTextField(10);
add(T2);
L3 = new JLabel("Result:");
add(L3);
Result = new JTextField(10);
[Link](false);
add(Result);
B1 = new JButton("Divide");
[Link](this);
add(B1);
B2 = new JButton("Clear");
[Link](e -> {
[Link]("");
[Link]("");
[Link]("");
});
add(B2);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
if ([Link]().isEmpty() || [Link]().isEmpty()) {
[Link](this, "Please fill both fields.");
return;
}
double value1 = [Link]([Link]());
double value2 = [Link]([Link]());
if (value2 == 0) {
[Link](this, "Cannot divide by zero.");
return;
}
double result = value1 / value2;
[Link]([Link]("%.2f", result));
} catch (NumberFormatException nte) {
[Link](this, "Please enter valid numbers.");
}
}
public static void main(String[] args) {
new DivisionApp();
}
}
8. Write a Java program that implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and 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.
import [Link].*;
// class for Even Number
class EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
[Link]("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
[Link]("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread {
public void run() {
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++) {
n = [Link](20);
[Link]("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new EvenNum(n));
[Link]();
}
else {
Thread thread2 = new Thread(new OddNum(n));
[Link]();
}
// thread wait for 1 second
[Link](1000);
[Link]("------------------------------------");
}
}
catch (Exception ex) {
[Link]([Link]());
}
}
}
// Driver class
public class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
9. Write a Java program that correctly implements the producer – consumer problem using the concept
of inter thread communication
class ItemQueue {
int item;
boolean valueSet = false;
synchronized int getItem() {
while (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
}
[Link]("Consumed: " + item);
valueSet = false;
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
notify();
return item;
}
synchronized void putItem(int item) {
while (valueSet) {
try {
wait();
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
}
[Link] = item;
valueSet = true;
[Link]("Produced: " + item);
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("InterruptedException caught");
}
notify();
}
}
class Producer implements Runnable {
ItemQueue itemQueue;
Producer(ItemQueue itemQueue) {
[Link] = itemQueue;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while (true) {
[Link](i++);
}
}
}
class Consumer implements Runnable {
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue) {
[Link] = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
[Link]();
}
}
}
class ProducerConsumer {
public static void main(String[] args) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);
}
}
10. a) Develop an applet in Java that displays a simple message.
import [Link].*;
import [Link].*;
/*
<applet code="FirstApplet" width=400 height=300></applet>
*/
public class FirstApplet extends Applet {
public void paint(Graphics g) {
[Link]([Link]); // Set text color to blue
Font font = new Font("Arial", [Link], 16); // Define the font
[Link](font); // Set the font
[Link]("This is My First Applet", 60, 110); // Draw the string
}
}
10b) Develop an applet in Java that receives an integer in one text field, and computes its factorial Value
and returns it in another text field, when the button named “Compute” is clicked.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="FactorialApplet" width=500 height=250>
</applet>
*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1, L2;
TextField T1, T2;
Button B1;
public void init() {
L1 = new Label("Enter any Number: ");
add(L1);
T1 = new TextField(10);
add(T1);
L2 = new Label("Factorial of Num: ");
add(L2);
T2 = new TextField(10);
[Link](false); // Result field should not be editable
add(T2);
B1 = new Button("Compute");
add(B1);
[Link](this);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == B1) {
try {
int value = [Link]([Link]());
if (value < 0) {
[Link]("Invalid Input");
} else {
int fact = factorial(value);
[Link]([Link](fact));
}
} catch (NumberFormatException ex) {
[Link]("Invalid Input");
}
}
}
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
11. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the
digits and for the +, -,*, % operations. Add a text field to display the result. Handle any possible
exceptions like divided by zero.
import [Link].*;
import [Link].*;
import [Link];
public class MyCalculator extends Frame implements ActionListener {
double num1, num2, result;
Label lbl1, lbl2, lbl3;
TextField tf1, tf2, tf3;
Button btn1, btn2, btn3, btn4;
MyCalculator() {
lbl1 = new Label("Number 1: ");
[Link](50, 100, 100, 30);
tf1 = new TextField();
[Link](160, 100, 100, 30);
lbl2 = new Label("Number 2: ");
[Link](50, 170, 100, 30);
tf2 = new TextField();
[Link](160, 170, 100, 30);
btn1 = new Button("+");
[Link](50, 250, 40, 40);
btn2 = new Button("-");
[Link](120, 250, 40, 40);
btn3 = new Button("*");
[Link](190, 250, 40, 40);
btn4 = new Button("/");
[Link](260, 250, 40, 40);
lbl3 = new Label("Result : ");
[Link](50, 320, 100, 30);
tf3 = new TextField();
[Link](160, 320, 100, 30);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
add(lbl1);
add(lbl2);
add(lbl3);
add(tf1);
add(tf2);
add(tf3);
add(btn1);
add(btn2);
add(btn3);
add(btn4);
setSize(400, 500);
setLayout(null);
setTitle("Calculator");
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
num1 = [Link]([Link]());
num2 = [Link]([Link]());
if ([Link]() == btn1) {
result = num1 + num2;
[Link]([Link](result));
}
if ([Link]() == btn2) {
result = num1 - num2;
[Link]([Link](result));
}
if ([Link]() == btn3) {
result = num1 * num2;
[Link]([Link](result));
}
if ([Link]() == btn4) {
if (num2 == 0) {
[Link](this, "Cannot divide by zero", "Error",
JOptionPane.ERROR_MESSAGE);
[Link](""); // Clear the result field if there is an error
} else {
result = num1 / num2;
[Link]([Link](result));
}
}
}
public static void main(String args[]) {
MyCalculator calc = new MyCalculator();
}
}
12. Write a Java program that simulates a traffic light. The program lets the users elect one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message with
“Stop” or “Ready” or “Go” should appear above the buttons in selected color. Initially, there is no
message shown.
import [Link].*;
import [Link];
import [Link];
import [Link].*;
class App extends JFrame implements ItemListener {
JFrame actualWindow;
JPanel messageContainer, lightsContainer;
JLabel message;
ButtonGroup btn_group;
JRadioButton rb_red, rb_yellow, rb_green;
// Constructor
App() {
// Set up font
Font myFont = new Font("Verdana", [Link], 30);
// Initialize components
actualWindow = new JFrame("Traffic Lights");
messageContainer = new JPanel();
lightsContainer = new JPanel();
message = new JLabel("Select Light");
btn_group = new ButtonGroup();
rb_red = new JRadioButton("Red");
rb_yellow = new JRadioButton("Yellow");
rb_green = new JRadioButton("Green");
// Set layout for the main window
[Link](new GridLayout(2, 1));
// Configure components
[Link](myFont);
rb_red.setForeground([Link]);
rb_yellow.setForeground([Link]);
rb_green.setForeground([Link]);
// Group radio buttons
btn_group.add(rb_red);
btn_group.add(rb_yellow);
btn_group.add(rb_green);
// Add event listeners to the radio buttons
rb_red.addItemListener(this);
rb_yellow.addItemListener(this);
rb_green.addItemListener(this);
// Add components to containers
[Link](message);
[Link](rb_red);
[Link](rb_yellow);
[Link](rb_green);
// Add containers to the main window
[Link](messageContainer);
[Link](lightsContainer);
// Configure the main window
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
// Handle item state changes
@Override
public void itemStateChanged(ItemEvent ie) {
JRadioButton selected = (JRadioButton) [Link]();
String textOnButton = [Link]();
if ([Link]("Red")) {
[Link]([Link]);
[Link]("STOP");
} else if ([Link]("Yellow")) {
[Link]([Link]);
[Link]("READY");
} else {
[Link]([Link]);
[Link]("GO");
}
}
}
public class TrafficLight {
public static void main(String[] args) {
new App();
}
}
13. 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).
import [Link];
import [Link];
import [Link];
import [Link].*;
class App extends JFrame implements MouseListener {
JFrame actualWindow;
JLabel message;
App() {
Font myFont = new Font("Verdana",[Link], 30);
actualWindow = new JFrame("Mouse Tracking");
message = new JLabel("Mouse Events");
[Link](this);
[Link](myFont);
[Link]([Link]);
[Link](message);
[Link](500, 500);
[Link](true);
}
@Override
public void mouseClicked(MouseEvent arg0) {
[Link]("Mouse Clicked");
}
@Override
public void mouseEntered(MouseEvent arg0) {
[Link]("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent arg0) {
[Link]("Mouse Exited");
}
@Override
public void mousePressed(MouseEvent arg0) {
[Link]("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent arg0) {
[Link]("Mouse Released");
}
}
public class MouseEventsExample {
public static void main(String[] args) {
new App();
}
14. Write 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 are cord are separated by at ab(\t). It takes a name or
phone number as input and prints the corresponding other value from the hash table (hint: use hash
tables).
import [Link].*;
import [Link].*;
public class Hashtbl134 {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("C:\\Users\\user\\Documents\\Java Programs\\
[Link]");
Scanner sc = new Scanner(fs);
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String line;
[Link]("Welcome TO II CSE A");
[Link]("HASH TABLE IS");
[Link](" ------------------------- ");
[Link]("KEY : VALUE");
while ([Link]()) {
line = [Link]().trim();
arrayList = [Link]("\\s+"); // Split by one or more spaces
// Check if the line contains at least two parts (name and phone number)
if ([Link] >= 2) {
[Link](arrayList[0], arrayList[1]);
[Link](arrayList[0] + " : " + arrayList[1]);
} else {
[Link]("Invalid line in [Link]: " + line);
}
}
[Link]("Welcome TO II CSE E");
[Link]("----MENU-----");
[Link]("----1. Search by Name -----");
[Link]("----2. Search by Mobile ----- ");
[Link]("----3. Exit ---- ");
String opt = "";
String name, mobile;
Scanner s = new Scanner([Link]);
while () {
[Link]("Enter Your Option (1, 2, 3): ");
opt = [Link]();
switch (opt) {
case "1": {
[Link]("Enter Name:");
name = [Link]();
if ([Link](name)) {
[Link]("Mobile is " + [Link](name));
} else {
[Link]("Not Found");
}
break;
}
case "2": {
[Link]("Enter Mobile:");
mobile = [Link]();
boolean found = false;
for ([Link]<String, String> e : [Link]()) {
if ([Link]([Link]())) {
[Link]("Name is " + [Link]());
found = true;
break;
}
}
if (!found) {
[Link]("Not Found");
}
break;
}
case "3": {
[Link]("Menu Successfully Exited");
break;
}
default:
[Link]("Choose an option between 1 to 3");
break;
}
}
} catch (Exception ex) {
[Link]("Error: " + [Link]());
}
}
}
15. Suppose that a table named [Link] is stored in a text file. The first line in the file is the header, and
the remaining lines correspond to rows in the table. The elements are separated by commas. Write a java
program to display the table using Labels in Grid Layout.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("./[Link]");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while ([Link]())
{
str = [Link]();
arrayList = [Link](",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
[Link]();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText {
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
[Link]();
}
}