Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
47 views22 pages

Lab Programs

The document outlines a series of Java programming lab exercises for a B.Sc. in Data Science course, focusing on object-oriented programming principles. It includes detailed instructions for creating various applications such as a car rental management system, traffic light simulation, banking system, student grading system, and more. Each exercise provides code examples, expected outputs, and instructions for running the programs.

Uploaded by

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

Lab Programs

The document outlines a series of Java programming lab exercises for a B.Sc. in Data Science course, focusing on object-oriented programming principles. It includes detailed instructions for creating various applications such as a car rental management system, traffic light simulation, banking system, student grading system, and more. Each exercise provides code examples, expected outputs, and instructions for running the programs.

Uploaded by

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

Department CT & DS Programme B.Sc.

DS

Object Oriented Programming using


Course Title Course Code 25DSU01A
Java
Google
Class & Section I DS B brhzdy6m
Classroom Code

LAB PROGRAMS

✅ Steps to Run a Java Program

1. Write Your Java Code

Create a .java file using any text editor (e.g., Notepad).

Example: HelloWorld.java

2. Open Command Prompt

Navigate to the folder where your .java file is saved.


Use the cd command to change directories.

Example : cd C:\Users\YourName\Documents\JavaPrograms

3. Compile the Java File

Use the javac command to compile your code:

Example : javac HelloWorld.java

4. Run the Compiled Java Program

Use the java command (without the .class extension):

Example: java HelloWorld


1. Design a Java program for car rental management using OOP
principles. Define a Car class with attributes like model, rental price,
and availability. Use encapsulation and implement methods to rent,
return, and view car details dynamically.

File name: Main.java

class Car {

private String model;

private double price;

private boolean available = true;

Car(String m, double p) {

model = m;

price = p;

void rent() {

if (available) {

available = false;

System.out.println(model + " rented for $" + price);

} else {

System.out.println(model + " not available");

public class Main {

public static void main(String[] args) {

Car c = new Car("Swift", 40);


c.rent();

c.rent(); // try renting again

OUTPUT

Swift rented for $40.0

Swift not available

2. Develop a Java program that simulates a traffic light system. Based


on the light color entered ("red", "yellow", or "green"), display the
appropriate action (e.g., "Stop", "Get Ready", "Go").

File name: TrafficLight.java

import java.util.Scanner;

public class TrafficLight {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter light color (red/yellow/green): ");

String color = sc.nextLine().toLowerCase();

if (color.equals("red"))

System.out.println("Stop");

else if (color.equals("yellow"))

System.out.println("Get Ready");

else if (color.equals("green"))

System.out.println("Go");

else
System.out.println("Invalid color");

sc.close();

}}

OUPUT

Enter light color (red/yellow/green): green

Go

3. Implement a Java banking system using method overloading for


deposit types (cash, check, online) and method overriding for
withdrawal processes in different account types. Demonstrate
polymorphism by processing transactions dynamically.

File name: Main.java

class Account {

void deposit(double amt) {

System.out.println("Cash deposit: $" + amt);

void deposit(String mode, double amt) {

System.out.println(mode + " deposit: $" + amt);

void withdraw(double amt) {

System.out.println("Withdraw: $" + amt);

class Saving extends Account {

void withdraw(double amt) {


System.out.println("Saving withdraw: $" + amt);

class Current extends Account {

void withdraw(double amt) {

System.out.println("Current withdraw: $" + amt);

public class Main {

public static void main(String[] args) {

Account a = new Saving();

a.deposit(100);

a.deposit("Online", 200);

a.withdraw(50);

a = new Current();

a.withdraw(70);

OUTPUT

Cash deposit: $100.0

Online deposit: $200.0

Saving withdraw: $50.0

Current withdraw: $70.0


4. Build a student grading system using arrays. Use a 1D array for
marks of a single student and a 2D array for multiple students.
Calculate total and average marks per student and identify the
highest marks in each subject.

File name: Grading.java

public class Grading {

public static void main(String[] args) {

int[][] marks = {

{80, 75, 90},

{60, 85, 70},

{78, 88, 95}

};

for (int i = 0; i < marks.length; i++) {

int sum = 0;

for (int j = 0; j < marks[i].length; j++) sum += marks[i][j];

System.out.println("Student " + (i+1) + " Total: " + sum + ", Avg: " +
sum / 3);

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

int max = 0;

for (int i = 0; i < marks.length; i++)

if (marks[i][j] > max) max = marks[i][j];

System.out.println("Highest in Subject " + (j+1) + ": " + max);

}
OUTPUT

Student 1 Total: 245, Avg: 81

Student 2 Total: 215, Avg: 71

Student 3 Total: 261, Avg: 87

Highest in Subject 1: 80

Highest in Subject 2: 88

Highest in Subject 3: 95

5. Create a Java payment processing system using interfaces. Define a


Payment interface and implement it in classes like Credit Card
Payment, PayPal Payment, and Bank Transfer Payment. Use
polymorphism to handle payment types based on user input.

File name: Main.java

import java.util.Scanner;

interface Payment {

void pay(double amt);

class Credit implements Payment {

public void pay(double amt)

System.out.println("Paid $" + amt + " by Credit");

}}

class PayPal implements Payment {

public void pay(double amt)

{
System.out.println("Paid $" + amt + " by PayPal");

}}

class Bank implements Payment {

public void pay(double amt)

System.out.println("Paid $" + amt + " by Bank");

}}

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Type (credit/paypal/bank): ");

String t = sc.next();

System.out.print("Amount: ");

double a = sc.nextDouble();

sc.close();

Payment p = t.equals("credit") ? new Credit() :

t.equals("paypal") ? new PayPal() :

new Bank();

p.pay(a);

}}

OUTPUT

Type (credit/paypal/bank): paypal


Amount: 50

Paid $50.0 by PayPal

6. Simulate a food delivery system using Java multithreading. Create


threads representing delivery agents that pick, process, and deliver
orders concurrently. Demonstrate improved efficiency through
parallel order handling.

File name: Main.java

class Agent extends Thread {

String order;

Agent(String order) {

this.order = order;

public void run() {

System.out.println("Picking " + order);

try {

Thread.sleep(500);

catch (Exception e) { }

System.out.println("Processing " + order);

try {

Thread.sleep(500);

catch (Exception e) {}

System.out.println("Delivered " + order);


}}

public class Main {

public static void main(String[] args) {

new Agent("Pizza").start();

new Agent("Burger").start();

}}

OUTPUT

Picking Pizza

Picking Burger

Processing Pizza

Processing Burger

Delivered Pizza

Delivered Burger

7. Build a Java-based flight booking system with exception handling.


Prevent overbooking by managing attempts to book more seats than
available. Ensure stability and smooth operation during booking and
cancellation.

File name: Main.java

class Flight {

int seats = 5;

void book(int n) {

if (n > seats) System.out.println("Not enough seats");

else {

seats -= n;
System.out.println("Booked " + n + ", left " + seats);

void cancel(int n) {

seats += n;

System.out.println("Canceled " + n + ", available " + seats);

public class Main {

public static void main(String[] args) {

Flight f = new Flight();

f.book(3);

f.book(4);

f.cancel(2);

f.book(3);

}}

OUTPUT

Booked 3, left 2

Not enough seats

Canceled 2, available 4

Booked 3, left 1

8. Develop a Java Applet to simulate a traffic signal system. The applet


visually displays traffic light transitions (Red, Yellow, Green) using
an interactive GUI. Signal changes are triggered by a button click,
demonstrating dynamic updates via graphical methods.

Save Java Applet Code (TrafficSignal.java)

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class TrafficSignal extends Applet implements ActionListener {

int state = 0;

Button btn = new Button("Change");

public void init() {

add(btn);

btn.addActionListener(this);

public void paint(Graphics g) {

Color[] colors = {Color.RED, Color.YELLOW, Color.GREEN};

g.setColor(colors[state]);

g.fillOval(100, 100, 100, 100);

public void actionPerformed(ActionEvent e) {

state = (state + 1) % 3;

repaint();

}
HTML File

Save HTML Code (TrafficSignal.html)

<html>

<body>

<applet code="TrafficSignal.class" width="300" height="300"></applet>

</body>

</html>

How to Run (Command Prompt)

 javac TrafficSignal.java
 appletviewer TrafficSignal.html

Output:

 One circle shown at a time.


 Click "Change" button to switch:
Red → Yellow → Green → Red...

9. Create a Java program using Random Access File to store and access
student records (Roll No., Name, Marks). The program writes three
records, reads a specific record by seeking its position, updates one
record, and prints all records for verification.

File name: StudentRecords.java

import java.io.*;

public class StudentRecords {

static final int RECORD_SIZE = 18; // 4 + 10 + 4 bytes

public static void main(String[] args) throws IOException {

RandomAccessFile file = new RandomAccessFile("data.dat", "rw");


// Write 3 records

write(file, 0, 1, "Ann", 80);

write(file, 1, 2, "Ben", 75);

write(file, 2, 3, "Cal", 90);

// Read 2nd record

file.seek(1 * RECORD_SIZE);

System.out.println("Read 2nd: " + read(file));

// Update 1st record marks

file.seek(0 * RECORD_SIZE + 14);

file.writeInt(85);

// Display all

System.out.println("\nAll records:");

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

file.seek(i * RECORD_SIZE);

System.out.println(read(file));

file.close();

static void write(RandomAccessFile f, int i, int roll, String name, int marks)
throws IOException {

f.seek(i * RECORD_SIZE);

f.writeInt(roll);

StringBuilder sb = new StringBuilder(name);

sb.setLength(10); // pad/truncate

f.writeBytes(sb.toString());
f.writeInt(marks);

static String read(RandomAccessFile f) throws IOException {

int roll = f.readInt();

byte[] b = new byte[10];

f.readFully(b);

String name = new String(b).trim();

int marks = f.readInt();

return "Roll: " + roll + ", Name: " + name + ", Marks: " + marks;

OUTPUT

Read 2nd: Roll: 2, Name: Ben, Marks: 75

All records:

Roll: 1, Name: Ann, Marks: 85

Roll: 2, Name: Ben, Marks: 75

Roll: 3, Name: Cal, Marks: 90

10. Build a Java program that simulates the reversal of a string using a
stack. This mirrors how many text-processing tools manage
character manipulation and undo operations. For example, reversing
the string "Hello World" should result in "dlroW olleH".

File name: StringReversal.java

import java.util.Stack;
public class StringReversal {

public static String reverse(String input) {

Stack<Character> stack = new Stack<>();

for (char ch : input.toCharArray()) {

stack.push(ch);

StringBuilder reversed = new StringBuilder();

while (!stack.isEmpty()) {

reversed.append(stack.pop());

return reversed.toString();

public static void main(String[] args) {

String str = "Hello World";

System.out.println("Original: " + str);

System.out.println("Reversed: " + reverse(str));

Output:

Original: Hello World


Reversed: dlroW olleH

11. Write a Java program that simulates a task scheduling system. Each
task has a specific duration, and tasks are executed in the order they
arrive (First In, First Out). Use a queue to model the task queue

File name: TaskScheduler.java


import java.util.*;

public class TaskScheduler {

static class Task {

String name;

int duration;

Task(String n, int d) {

name = n; duration = d;

public String toString() {

return name + " [" + duration + "s]";

public static void main(String[] args) {

Queue<Task> queue = new ArrayDeque<>();

queue.offer(new Task("Clean", 4));

queue.offer(new Task("Write", 3));

queue.offer(new Task("Compile", 2));

while (!queue.isEmpty()) {

Task t = queue.poll();

System.out.println("Running: " + t);

}
OUTPUT

Running: Clean [4s]

Running: Write [3s]

Running: Compile [2s]

12. Develop a Java program to create a simple music playlist using a


linked list. Allow the user to add songs to the beginning, middle, or
end of the playlist and display the entire playlist.

File name: MusicPlaylist.java

import java.util.*;

public class MusicPlaylist {

public static void main(String[] args) {

LinkedList<String> playlist = new LinkedList<>();

playlist.addFirst("Shape of You");

playlist.add(1, "Blinding Lights");

playlist.addLast("Someone Like You");

for (int i = 0; i < playlist.size(); i++)

System.out.println((i + 1) + ". " + playlist.get(i));

Output:

1. Shape of You
2. Blinding Lights
3. Someone Like You
13. Write a Java program to implement a binary search that allows users
to search for a product in a sorted list of products based on their
product IDs. If the product is found, display its details.

Save this code in a file named: ProductSearchSimple.java

import java.util.Scanner;

public class ProductSearchSimple {

public static void main(String[] args) {

int[] ids = {101, 203, 305, 407};

String[] names = {"Laptop", "Phone", "Tablet", "Monitor"};

double[] prices = {800, 500, 300, 150};

Scanner sc = new Scanner(System.in);

System.out.print("Enter product ID: ");

int key = sc.nextInt();

int index = -1;

int low = 0, high = ids.length - 1;

while (low <= high) {

int mid = (low + high) / 2;

if (ids[mid] == key) {

index = mid;

break;

else if (ids[mid] < key) {

low = mid + 1;

else {
high = mid - 1;

if (index != -1) {

System.out.println("Product Found:");

System.out.println("ID: " + ids[index]);

System.out.println("Name: " + names[index]);

System.out.println("Price: $" + prices[index]);

} else {

System.out.println("Product not found.");

sc.close();

OUTPUT:

Enter product ID: 203

Product Found:

ID: 203

Name: Phone

Price: $500.0

14. Create a Java program that sorts an array of student grades (out of
100) in ascending order using insertion sort and displays the sorted
grades.

Save the program in a file named: SortGrades.java


public class SortGrades {

public static void main(String[] args) {

int[] grades = {88, 75, 93, 67, 85};

// Insertion sort algorithm

for (int i = 1; i < grades.length; i++) {

int key = grades[i];

int j = i - 1;

while (j >= 0 && grades[j] > key) {

grades[j + 1] = grades[j];

j--;

grades[j + 1] = key;

// Display sorted grades

System.out.print("Sorted grades: ");

for (int g : grades)

System.out.print(g + " ");

}}

OUTPUT

Sorted grades: 67 75 85 88 93

15. Create a Java program that sorts an array of student test scores
descending order using bubble sort to display the top-performing students

Save the program in a file named: StudentScores.java

public class StudentScores {


public static void main(String[] args) {

int[] scores = {85, 92, 78, 90, 88};

for (int i = 0; i < scores.length - 1; i++) {

for (int j = 0; j < scores.length - 1 - i; j++) {

if (scores[j] < scores[j + 1]) {

int temp = scores[j];

scores[j] = scores[j + 1];

scores[j + 1] = temp;

System.out.println("Top score: " + scores[0]);

OUTPUT

Top score: 92

You might also like