KEMBAR78
OOPS Lab Manual (Results) | PDF | My Sql | Data Management
0% found this document useful (0 votes)
6 views55 pages

OOPS Lab Manual (Results)

Oops manual

Uploaded by

rajkumarjustus
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)
6 views55 pages

OOPS Lab Manual (Results)

Oops manual

Uploaded by

rajkumarjustus
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/ 55

Ex 1:Sum of Numbers from 1 to 100

Test Cases:

TC1: Sum from 1 to 100 → Expected: 5050


public class SumCalculator
{
public static void main(String[] args)
​ {
​ ​ int sum = 0;
​ ​ for (int i = 1; i <= 100; i++)
{
​ ​ ​ sum += i;
​ ​ }
​ System.out.println("Sum of numbers from 1 to 100 is: " + sum);
}
}

Output:
Sum of numbers from 1 to 100 is: 5050

TC2: Sum from 1 to 50 → Expected: 1275


public class SumCalculator
{
public static void main(String[] args)
​ {
​ ​ int sum = 0;
​ ​ for (int i = 1; i <= 50; i++)
{
​ ​ ​ sum += i;
​ ​ }
​ System.out.println("Sum of numbers from 1 to 50 is: " + sum);
}
}

Output:
Sum of numbers from 1 to 50 is: 1275

TC3: Sum from 1 to 10 → Expected: 55


public class SumCalculator
{
public static void main(String[] args)
​ {
​ ​ int sum = 0;
​ ​ for (int i = 1; i <= 10; i++)
{
​ ​ ​ sum += i;
​ ​ }
​ System.out.println("Sum of numbers from 1 to 10 is: " + sum);
}
}

Output:
Sum of numbers from 1 to 10 is: 55

TC4: Sum from 50 to 100 → Expected: 3825


public class SumCalculator
{
public static void main(String[] args)
​ {
​ ​ int sum = 0;
​ ​ for (int i = 1; i <= 100; i++)
{
​ ​ ​ sum += i;
​ ​ }
​ System.out.println("Sum of numbers from 50 to 100 is: " + sum);
}
}

Output:
Sum of numbers from 50 to 100 is: 3825

TC5: Sum from 1 to 1 → Expected: 1


public class SumCalculator
{
public static void main(String[] args)
​ {
​ ​ int sum = 0;
​ ​ for (int i = 1; i <= 1; i++)
{
​ ​ ​ sum += i;
​ ​ }
​ System.out.println("Sum of numbers from 1 to 1 is: " + sum);
}
}

Output:
Sum of numbers from 1 to 1 is: 1
MCQ’s:

1.b) 5050

2.c) N * (N + 1) / 2

3. b) for

4.c) int

5.b) O(N)

6.c) int

7. b) 100

8.c) +

9.c) 5050 + 0 = 5050 (Actually adds an extra 0, so same result)

10.c) Mathematical formula

Ex2. Program Title: Prime Number Checker

import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
// Step 1: Input number n
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
sc.close();
// Step 2: If n <= 1, it's not prime
if (n <= 1) {
System.out.println("Not Prime");
return;
}
// Step 3 & 4: Check divisibility from 2 to sqrt(n)
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
System.out.println("Not Prime");
return;
}
}
// Step 5: Else, it is a prime number
System.out.println("Prime");
}
}
output:
Enter a number: 2
Prime

Test Cases:
● TC1: Input 2 → Output: Prime
● TC2: Input 15 → Output: Not Prime
● TC3: Input 17 → Output: Prime
● TC4: Input 1 → Output: Not Prime
● TC5: Input 0 → Output: Not Prime

MCQ’s

1.​ c) 7​

2.​ c) 4​

3.​ c) for​

4.​ a) 1​

5.​ b) 1​

6.​ c) boolean​

7.​ b) No​

8.​ a) Prime​

9.​ c) nextInt()​

10.​ c) 2 to sqrt(n)​

Ex3. Program Title: Fibonacci Sequence using Recursion

import java.util.Scanner;
public class FibonacciRec {
public static int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
sc.close();
System.out.println("Fibonacci sequence:");
for (int i = 0; i < n; i++) {
System.out.print(fib(i) + " ");
}
}
}

output:
Enter number of terms: 7
Fibonacci sequence:
0112358

Test Cases:
● TC1: n = 5 → Output: 0 1 1 2 3
● TC2: n = 7 → Output: 0 1 1 2 3 5 8
● TC3: n = 1 → Output: 0
● TC4: n = 0 → Output:
● TC5: n = 10 → Output: 0 1 1 2 3 5 8 13 21 34

MCQs:

1.​ b) A function calling itself​

2.​ b) fib(0) = 0​

3.​ b) 2​

4.​ b) Stack overflow​

5.​ c) Efficiency​

6.​ c) int​

7.​ d) O(2^n)​

8.​ a) 5​

9.​ b) void​

10.​ c) 8

4. Program Title: Class "Car" with Methods

public class Car {


String model;
String color;
// Constructor
public Car(String model, String color) {
this.model = model;
this.color = color;
}
// Start method
public void start() {
System.out.println("Car started");
}
// Stop method
public void stop() {
System.out.println("Car stopped");
}
public static void main(String[] args) {
// TC1: Tesla Red → start()
Car car1 = new Car("Tesla", "Red");
car1.start(); // Output: Car started
}
}
// TC2: BMW Black → start()
Car car1 = new Car("BMW", "Black");
car1.start(); // Output: Car started
// TC3: Empty model → start()
Car car1 = new Car("", "Silver");
car1.start(); // Output: Car started
// TC4: Honda Blue → no method called
Car car1 = new Car("Honda", "Blue");
// No output expected
// TC5: Audi White → stop() only
Car car1 = new Car("Audi", "White");
car1.stop(); // Output: Car stopped

OUTPUT:

Car started
Car started
Car started
Car stopped

MCQ’s:

1.​ c) A blueprint for objects​

2.​ c) class​
3.​ a) new Car()​

4.​ c) Method that initializes object​

5.​ b) private​

6.​ c) 123method​

7.​ a) Car started​

8.​ c) this​

9.​ b) Many​

10.​ c) Does not return a value

5. Program Title: Inheritance with Shape-Circle-Rectangle

Create base class Shape​


✔ This class will be the parent/superclass.​

Add method area() in Shape​


✔ This can be a general method, either with default behavior or marked abstract if you're using
abstraction.​

Create derived classes Circle and Rectangle​


✔ These will extend Shape and inherit its properties and methods.​

Override area() in both​


✔ You write specific formulas:​

●​ Circle → π × r × r​

●​ Rectangle → length × width​

Instantiate objects and call respective methods​


✔ Create Circle and Rectangle objects and call area() to test polymorphic behavior.

Shape.java
package Inheritance;
public class Shape {
public double area() {
System.out.println("Default area");
return 0;
}
}

Circle.java

package Inheritance;
public class Circle extends Shape {
double radius;
public Circle(double r) {
radius = r;
}
@Override
public double area() {
return 3.14 * radius * radius;
}
}

Rectangle.java

package Inheritance;
public class Rectangle extends Shape {
double length, width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
@Override
public double area() {
return length * width;
}
}

InheritanceTest.java

package Inheritance;
public class InheritanceTest {
public static void main(String[] args) {
Shape circle1 = new Circle(5);
System.out.println("TC1 - Circle Area: " + circle1.area());
Shape rect1 = new Rectangle(10, 5);
System.out.println("TC2 - Rectangle Area: " + rect1.area());
Shape shape = new Shape();
System.out.println("TC3 - Shape Area: " + shape.area());
Shape circle2 = new Circle(0);
System.out.println("TC4 - Zero Radius Circle Area: " + circle2.area());
Shape rect2 = new Rectangle(10, 0);
System.out.println("TC5 - Rectangle Area with width 0: " + rect2.area());
}
}

output:

TC1 - Circle Area: 78.5


TC2 - Rectangle Area: 50.0
Default area
TC3 - Shape Area: 0.0
TC4 - Zero Radius Circle Area: 0.0
TC5 - Rectangle Area with width 0: 0.0

MCQs:

1.​ b) One class acquiring another​

2.​ c) extends​

3.​ b) Redefining method in subclass​

4.​ a) Parent class​

5.​ b) No​

6.​ b) Object​

7.​ c) 0​

8.​ c) Shape​

9.​ c) Indicates method overrides parent method​

10.​ c) Hybrid
Ex 6. Program Title: Interface for Banking System

1.Define Interface: BankingService.java

package BankingApp;
public interface BankingService {
void deposit(double amount);
void withdraw(double amount);
void showBalance();
}

2.Implement Account Class: Account.java

package BankingApp;
public class Account implements BankingService {
private double balance = 0;
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited ₹" + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}
@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew ₹" + amount);
} else {
System.out.println("Insufficient funds.");
}
}
@Override
public void showBalance() {
System.out.println("Current Balance: ₹" + balance);
}
}

3.Implement Transaction Logger: Transaction.java

package BankingApp;
public class Transaction {
public void log(String action, double amount) {
System.out.println("Transaction Log: " + action + " ₹" + amount);
}
}

4.Test & Show Polymorphism: BankTest.java

package BankingApp;
public class BankTest {
public static void main(String[] args) {
// Polymorphic reference
BankingService account = new Account();
Transaction txn = new Transaction();
// TC1: Deposit ₹1000 → Balance = ₹1000
System.out.println("TC1: Deposit ₹1000");
account.deposit(1000);
account.showBalance();
// TC2: Withdraw ₹500 → Balance = ₹500
System.out.println("\nTC2: Withdraw ₹500");
account.withdraw(500);
account.showBalance();
// TC3: Withdraw ₹1500 → Insufficient funds
System.out.println("\nTC3: Withdraw ₹1500");
account.withdraw(1500);
// TC4: Deposit negative amount → Invalid
System.out.println("\nTC4: Deposit -200");
account.deposit(-200);
// TC5: Log transactions
System.out.println("\nTC5: Log transaction");
txn.log("Deposit", 1000);
txn.log("Withdraw", 500);
}
}

output:
TC1: Deposit ₹1000
Deposited ₹1000.0
Current Balance: ₹1000.0
TC2: Withdraw ₹500
Withdrew ₹500.0
Current Balance: ₹500.0
TC3: Withdraw ₹1500
Insufficient funds.
TC4: Deposit -200
Invalid deposit amount.
TC5: Log transaction
Transaction Log: Deposit ₹1000.0
Transaction Log: Withdraw ₹500.0

MCQs:
1.​ c) Collection of abstract methods​

2.​ a) interface​

3.​ b) No​

4.​ c) implements​

5.​ c) They are public and abstract​

6.​ b) Yes​

7.​ c) Invalid input message​

8.​ b) One method, many forms​

9.​ c) Final variables​

10.​ b) Call a method​

Ex 7. Program Title: Exception Handling for Division by Zero

DivisionByZeroHandler.java

import java.util.Scanner;
public class DivisionByZeroHandler {
public static void safeDivide(int numerator, int denominator) {
try {
int result = numerator / denominator;
System.out.println("Output: " + result);
} catch (ArithmeticException e) {
System.out.println("Output: Exception handled");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("TC1: 10 / 2 → ");
safeDivide(10, 2);
System.out.print("TC2: 20 / 0 → ");
safeDivide(20, 0);
System.out.print("TC3: -5 / 5 → ");
safeDivide(-5, 5);
System.out.print("TC4: 0 / 3 → ");
safeDivide(0, 3);
System.out.print("TC5: 100 / -10 → ");
safeDivide(100, -10);
scanner.close();
}
}

Output:

TC1: 10 / 2 → Output: 5
TC2: 20 / 0 → Output: Exception handled
TC3: -5 / 5 → Output: -1
TC4: 0 / 3 → Output: 0
TC5: 100 / -10 → Output: -10

MCQ’s

1.​ d​

2.​ c​

3.​ c​

4.​ b​

5.​ c​

6.​ b​

7.​ c​

8.​ b​

9.​ b​

10.​ b​

8. Program Title: Multi-threaded Race Simulation

1.​ Click on File → New → Java Project​

2.​ Project Name: RaceSimulationProject​

3.​ Click Finish​


Create a New Package (optional, but recommended)

1.​ Right-click on the src folder → New → Package​

2.​ Package name: multithreading​

3.​ Click Finish

Create the Racer Class

1.​ Right-click on the package multithreading → New → Class​

2.​ Name: Racer​

3.​ Uncheck public static void main​

Racer.java

package multithreading;
public class Racer extends Thread {
private String name;
private int steps;
private long sleepMillis;
public Racer(String name, int steps, long sleepMillis) {
this.name = name;
this.steps = steps;
this.sleepMillis = sleepMillis;
}
@Override
public void run() {
for (int i = 1; i <= steps; i++) {
System.out.printf("%s: Step %d/%d%n", name, i, steps);
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
System.out.println(name + " was interrupted.");
return;
}
}
System.out.println(name + " has finished!");
}
}
RaceSimulation.java

package multithreading;
public class RaceSimulation {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== TC1: Two threads start together ===");
Racer r1 = new Racer("Runner-A", 5, 500);
Racer r2 = new Racer("Runner-B", 5, 500);
r1.start();
r2.start();
r1.join(); r2.join();
System.out.println("\n=== TC2: Different sleep times (B faster) ===");
r1 = new Racer("Runner-A", 5, 700);
r2 = new Racer("Runner-B", 5, 300);
r1.start();
r2.start();
r1.join(); r2.join();
System.out.println("\n=== TC3: Race between A and B (non-deterministic)
===");
r1 = new Racer("Runner-A", 5, 400);
r2 = new Racer("Runner-B", 5, 450);
r1.start();
r2.start();
r1.join(); r2.join();
System.out.println("\n=== TC4: Three-thread race ===");
Racer r3 = new Racer("Runner-C", 5, 500);
r1 = new Racer("Runner-A", 5, 500);
r2 = new Racer("Runner-B", 5, 500);
r1.start();
r2.start();
r3.start();
r1.join(); r2.join(); r3.join();
System.out.println("\n=== TC5: Same sleep times, interleaved output
===");
r1 = new Racer("Runner-A", 5, 500);
r2 = new Racer("Runner-B", 5, 500);
r1.start();
r2.start();
r1.join(); r2.join();
}
}
Output:

=== TC1: Two threads start together ===


Runner-A: Step 1/5
Runner-B: Step 1/5
Runner-A: Step 2/5
Runner-B: Step 2/5
Runner-B: Step 3/5
Runner-A: Step 3/5
Runner-A: Step 4/5
Runner-B: Step 4/5
Runner-A: Step 5/5
Runner-B: Step 5/5
Runner-A has finished!
Runner-B has finished!
=== TC2: Different sleep times (B faster) ===
Runner-B: Step 1/5
Runner-A: Step 1/5
Runner-B: Step 2/5
Runner-B: Step 3/5
Runner-A: Step 2/5
Runner-B: Step 4/5
Runner-B: Step 5/5
Runner-A: Step 3/5
Runner-B has finished!
Runner-A: Step 4/5
Runner-A: Step 5/5
Runner-A has finished!
=== TC3: Race between A and B (non-deterministic) ===
Runner-A: Step 1/5
Runner-B: Step 1/5
Runner-A: Step 2/5
Runner-B: Step 2/5
Runner-A: Step 3/5
Runner-B: Step 3/5
Runner-A: Step 4/5
Runner-B: Step 4/5
Runner-A: Step 5/5
Runner-B: Step 5/5
Runner-A has finished!
Runner-B has finished!
=== TC4: Three-thread race ===
Runner-A: Step 1/5
Runner-B: Step 1/5
Runner-C: Step 1/5
Runner-C: Step 2/5
Runner-B: Step 2/5
Runner-A: Step 2/5
Runner-C: Step 3/5
Runner-B: Step 3/5
Runner-A: Step 3/5
Runner-A: Step 4/5
Runner-C: Step 4/5
Runner-B: Step 4/5
Runner-C: Step 5/5
Runner-B: Step 5/5
Runner-A: Step 5/5
Runner-A has finished!
Runner-B has finished!
Runner-C has finished!
=== TC5: Same sleep times, interleaved output ===
Runner-B: Step 1/5
Runner-A: Step 1/5
Runner-B: Step 2/5
Runner-A: Step 2/5
Runner-A: Step 3/5
Runner-B: Step 3/5
Runner-A: Step 4/5
Runner-B: Step 4/5
Runner-B: Step 5/5
Runner-A: Step 5/5
Runner-B has finished!
Runner-A has finished!

MCQ’s

1.​ b) start()​

2.​ c) Concurrent execution​

3.​ d) Both a and c​

4.​ b) Pauses thread​

5.​ c) run()​

6.​ b) Throws exception​

7.​ b) Runnable​

8.​ b) Yes​

9.​ c) Concurrency​
10.​ d) Varies​

Program 9: Generic Binary Tree with DFS and BFS Traversals

1. TreeNode.java
package tree;
public class TreeNode<T extends Comparable<T>> {
T data;
TreeNode<T> left, right;
public TreeNode(T data) {
this.data = data;
this.left = null;
this.right = null;
}
}

2. BinaryTree.java

package tree;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree<T extends Comparable<T>> {
private TreeNode<T> root;
// Insert method
public void insert(T data) {
root = insertRec(root, data);
}
private TreeNode<T> insertRec(TreeNode<T> node, T data) {
if (node == null) return new TreeNode<>(data);
if (data.compareTo(node.data) < 0)
node.left = insertRec(node.left, data);
else
node.right = insertRec(node.right, data);
return node;
}
// DFS: In-Order
public void inOrder() {
inOrderRec(root);
System.out.println();
}
private void inOrderRec(TreeNode<T> node) {
if (node != null) {
inOrderRec(node.left);
System.out.print(node.data + " ");
inOrderRec(node.right);
}
}
// DFS: Pre-Order
public void preOrder() {
preOrderRec(root);
System.out.println();
}
private void preOrderRec(TreeNode<T> node) {
if (node != null) {
System.out.print(node.data + " ");
preOrderRec(node.left);
preOrderRec(node.right);
}
}
// DFS: Post-Order
public void postOrder() {
postOrderRec(root);
System.out.println();
}
private void postOrderRec(TreeNode<T> node) {
if (node != null) {
postOrderRec(node.left);
postOrderRec(node.right);
System.out.print(node.data + " ");
}
}
// BFS: Level Order
public void levelOrder() {
if (root == null) return;
Queue<TreeNode<T>> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode<T> node = queue.poll();
System.out.print(node.data + " ");
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
System.out.println();
}
}

3. BinaryTreeTest.java
package tree;
public class BinaryTreeTest {
public static void main(String[] args) {
BinaryTree<Integer> tree = new BinaryTree<>();
// Test Case 1: Insert 10, 5, 20
tree.insert(10);
tree.insert(5);
tree.insert(20);
System.out.print("Level Order (BFS): ");
tree.levelOrder(); // Expected: 10 5 20
System.out.print("In-Order (DFS): ");
tree.inOrder(); // Expected: 5 10 20
System.out.print("Pre-Order (DFS): ");
tree.preOrder(); // Expected: 10 5 20
System.out.print("Post-Order (DFS): ");
tree.postOrder(); // Expected: 5 20 10
}
}

Output:

Level Order (BFS): 10 5 20


In-Order (DFS): 5 10 20
Pre-Order (DFS): 10 5 20
Post-Order (DFS): 5 20 10

MCQ’s:

1.​ b​

2.​ c​

3.​ b​

4.​ b​

5.​ a​

6.​ a​
7.​ d​

8.​ c​

9.​ a​

10.​ b

10. Program Title: Client-Server Connection using Sockets

// Save as Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String serverAddress = "localhost"; // or use IP address
int port = 12345;
try (Socket socket = new Socket(serverAddress, port)) {
System.out.println("Connected to server.");
// Send message
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello from client!");
// Receive reply
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String reply = in.readLine();
System.out.println("Server replies: " + reply);
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage());
}
}
}

// Save as Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started. Waiting for client...");
while (true) {
Socket socket = serverSocket.accept(); // Waits for client
System.out.println("Client connected.");
// Input from client
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);
// Output to client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Server received: " + clientMessage);
// Close connection
socket.close();
System.out.println("Connection closed.\n");
}
} catch (IOException e) {
System.out.println("Server error: " + e.getMessage());
}
}
}

Output:

TC1: Server online, client connects → Output: Connection successful

Server started on port 1234


Waiting for client...

Connected to server.
Server replies: Server received: Hello from client!

Right-click inside the console window ➝ click "Terminate and Remove Launch".

TC2: Server not running → Output: Connection refused(Run the client program first)

Client error: Connection refused: connect


—---------------------------------------------------------------------------------------------------------------------------------

TC3: Client sends message → Server receives correctly(Run Server.java then run Client.java)

Client.java

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String serverAddress = "localhost"; // or use IP address
int port = 12345;
try (Socket socket = new Socket(serverAddress, port)) {
System.out.println("Connected to server.");
// Send message
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello from client!");
// Receive reply
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String reply = in.readLine();
System.out.println("Server replies: " + reply);
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage());
}
}
}

Server.java

import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server started. Waiting for client...");
while (true) {
Socket socket = serverSocket.accept(); // Waits for client
System.out.println("Client connected.");
// Input from client
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);
// Output to client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Server received: " + clientMessage);
// Close connection
socket.close();
System.out.println("Connection closed.\n");
}
} catch (IOException e) {
System.out.println("Server error: " + e.getMessage());
}
}
}

output:

Client.java

Connected to server. Type message and press Enter.


Welcome
Server.java

Server started. Waiting for client...


Client connected.
Client says: Welcome

Conclusion:

Typed "Welcome" in client Server printed "Client says: Server received the message
Welcome" correctly

—-------------------------------------------------------------------------------------------------------------------------------

TC4: Server sends back reply → Client displays reply

Client.java

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // to read
server reply
System.out.println("Connected to server. Type message:");
String msg;
while (!(msg = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(msg);
String reply = in.readLine(); // read server reply
System.out.println(reply);
}
out.println("exit");
socket.close();
System.out.println("Client exited.");
}
}
Server.java

import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
System.out.println("Server started. Waiting for client...");
Socket clientSocket = server.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // enable auto-flush
String msg;
while ((msg = in.readLine()) != null) {
System.out.println("Client says: " + msg);
out.println("Server reply: Received your message -> " + msg); // send reply to client
if (msg.equalsIgnoreCase("exit")) break;
}
clientSocket.close();
server.close();
System.out.println("Server stopped.");
}
}

Output:

Server started. Waiting for client...

Connected to server. Type message:


Hello
Server reply: Received your message -> Hello

—---------------------------------------------------------------------------------------------------------------------
TC5: Multiple clients → Server handles sequentially

Client.java

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Connected to server. Type message:");
String msg;
while (!(msg = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(msg);
System.out.println(in.readLine());
}
out.println("exit");
socket.close();
System.out.println("Client exited.");
}
}

Server.java

import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
System.out.println("Server started. Waiting for clients...");
while (true) {
Socket clientSocket = server.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String msg;
while ((msg = in.readLine()) != null) {
System.out.println("Client says: " + msg);
out.println("Server reply: Received -> " + msg);
if (msg.equalsIgnoreCase("exit")) break;
}
clientSocket.close();
System.out.println("Client disconnected.\n");
}
}
}

Output:

Server started. Waiting for clients...


Client connected.
Client says: hi hello how are you
Client says: welocme to rit
Client says: 2nd year students

—---------------------------------------------------------------------------------------------------------------------------------
All test cases in one program:

10. Program Title: Client-Server Connection using Sockets

Client.java

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 12345;
try (Socket socket = new Socket(serverAddress, port)) {
System.out.println("TC1: Connected to server.");
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.print("Enter a message: ");
String message = console.readLine();
// TC3: Send message
out.println(message);
// TC4: Receive reply
String reply = in.readLine();
System.out.println("TC4: Server replied → " + reply);
} catch (ConnectException e) {
System.out.println("TC2: Connection refused. Is the server running?");
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage());
}
}
}

Server.java

import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
int port = 12345;
System.out.println("Server starting on port " + port);
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("TC1: Server is online and listening...");
while (true) {
Socket clientSocket = serverSocket.accept(); // TC1
System.out.println("Client connected."); // TC1
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// TC3: Receive message from client
String clientMsg = in.readLine();
System.out.println("TC3: Received from client → " + clientMsg);
// TC4: Send back reply
String reply = "Server reply: " + clientMsg;
out.println(reply);
System.out.println("TC4: Sent to client → " + reply);
clientSocket.close();
System.out.println("Connection closed.\n"); // TC5: Server ready for next client
}
} catch (IOException e) {
System.out.println("Server error: " + e.getMessage());
}
}
}

Output:

Server.java

Server starting on port 12345


TC1: Server is online and listening...
Client connected.
TC3: Received from client → welcome
TC4: Sent to client → Server reply: welcome
Connection closed.

Client.java

TC1: Connected to server.


Enter a message: welcome
TC4: Server replied → Server reply: welcome

MCQ’s:

1.​ c) java.net​

2.​ b) ServerSocket​

3.​ c) accept()​

4.​ a) 0 to 65535​
5.​ a) IOException​

6.​ d) close()​

7.​ a) 127.0.0.1​

8.​ b) Error: Connection refused​

9.​ c) TCP​

10.​ b) InputStream​
—---—----------------------------------------------------------------------------------------------------------------------

11.Program Title: JDBC Connection with MySQL

Mysql

Press Windows + R, type cmd, and press Enter.


C:\Users\HP>cd C:\Program Files\MySQL\MySQL Server 8.0\bin
Enter password:12345
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 8.0.40 MySQL Community Server - GPL

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

SHOW DATABASES;
CREATE DATABASE employees;

USE employees;

CREATE TABLE employees (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_salary DOUBLE
);

INSERT INTO employees (emp_id, emp_name, emp_salary) VALUES


(1, 'Alice', 50000),
(2, 'Bob', 60000),
(3, 'Charlie', 55000);

JDBCTest.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCTest {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employees?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "12345";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected");
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Driver not found");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Connection failed: " + e.getMessage());
}
}
}

Output:
TC1: Connect to DB successfully → Output: Connected
Connected

Alltest.java

import java.sql.*;
public class AllTest{
public static void main(String[] args) {
// Step 1: Load JDBC driver
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Step 1: JDBC Driver Loaded.");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found.");
return;
}
// Connection parameters
String url = "jdbc:mysql://localhost:3306/employees?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "12345";
// TC1: Connect to DB successfully
try (
Connection conn = DriverManager.getConnection(url, user, password); // Step 2
Statement stmt = conn.createStatement(); // Step 3
){
System.out.println("TC1: Connected to database. (Step 2)");
// TC2: Execute SELECT query
String sql = "SELECT * FROM employees";
ResultSet rs = stmt.executeQuery(sql); // Step 4
System.out.println("TC2: SELECT query executed. (Step 4)");
// Step 5: Display result
boolean found = false;
System.out.println("TC2: Displaying results:");
while (rs.next()) {
found = true;
int id = rs.getInt("emp_id");
String name = rs.getString("emp_name");
double salary = rs.getDouble("emp_salary");
System.out.println(id + " | " + name + " | " + salary);
}
if (!found) {
System.out.println("TC4: No results found.");
} else {
System.out.println("TC2: Records displayed. (Step 5)");
}
rs.close();
} catch (SQLException e) {
System.out.println("TC1 or TC2 Failed: " + e.getMessage());
}
// TC3: Invalid credentials
try {
Connection connWrong = DriverManager.getConnection(url, user, "wrongpassword");
System.out.println("TC3: Unexpected success with wrong password!");
connWrong.close();
} catch (SQLException e) {
System.out.println("TC3: Access denied (invalid credentials).");
}
// TC4: Empty query (no matching results)
try (
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
){
ResultSet rs = stmt.executeQuery("SELECT * FROM employees WHERE emp_id = -1");
if (!rs.next()) {
System.out.println("TC4: No results as expected (empty query).");
} else {
System.out.println("TC4: Unexpected data found.");
}
rs.close();
} catch (SQLException e) {
System.out.println("TC4 Failed: " + e.getMessage());
}
// TC5: Malformed SQL
try (
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
){
stmt.executeQuery("SELEC * FORM employees"); // Intentional error
} catch (SQLException e) {
System.out.println("TC5: SQLSyntaxErrorException caught for malformed query.");
}
}
}

Output:
Step 1: JDBC Driver Loaded.
TC1: Connected to database. (Step 2)
TC2: SELECT query executed. (Step 4)
TC2: Displaying results:
1 | Alice | 50000.0
2 | Bob | 60000.0
3 | Charlie | 55000.0
TC2: Records displayed. (Step 5)
TC3: Access denied (invalid credentials).
TC4: No results as expected (empty query).
TC5: SQLSyntaxErrorException caught for malformed query.

—-------------------------------------------------

MCQ’s:

1.​ a) java.sql​

2.​ c) DriverManager​

3.​ c) executeQuery()​
4.​ b) ResultSet​

5.​ a) Moves to next record​

6.​ c) PreparedStatement​

7.​ d) com.mysql.cj.jdbc.Driver​

8.​ a) SQLException​

9.​ b) 3306​

10.​ c) close()​

—----------------------------------------------------------

12. Program Title: Multi-threaded Server using Java RMI

MultiThreadedServerInterface.java

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface MultiThreadedServerInterface extends Remote {


String processRequest(String request) throws RemoteException;
}

—-----------------------------------------------------------------------------------------------

MultiThreadedServerImpl.java

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class MultiThreadedServerImpl extends UnicastRemoteObject implements


MultiThreadedServerInterface {

protected MultiThreadedServerImpl() throws RemoteException {


super();
}

@Override
public String processRequest(String request) throws RemoteException {
String threadName = Thread.currentThread().getName();
System.out.println("Processing request in thread: " + threadName);
return "Processed: " + request + " by thread " + threadName;
}
}
—--------------------------------------------------------------------------------------

MultiThreadedServer.java

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class MultiThreadedServer {


public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099);
System.out.println("Java RMI registry created.");

MultiThreadedServerImpl server = new MultiThreadedServerImpl();

Registry registry = LocateRegistry.getRegistry();


registry.rebind("MultiThreadedServer", server);

System.out.println("Server ready...");
} catch (Exception e) {
System.err.println("Server exception:");
e.printStackTrace();
}
}
}

—-------------------------------------------------------------------------------------------

TestClient.java

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class TestClient {
public static void main(String[] args) {
System.out.println("=== TC1: Start server, connect client → Success ===");
boolean tc1 = testConnection();
System.out.println("TC1 Result: " + (tc1 ? "Success" : "Fail") + "\n");
System.out.println("=== TC2: Client sends request → Server responds ===");
testRequestResponse();
System.out.println();
System.out.println("=== TC3: Multiple clients → Handled via threads ===");
testMultipleClients();
System.out.println();
System.out.println("=== TC4: Server not running → Lookup fails ===");
System.out.println("Please STOP the server and press Enter to continue...");
try { System.in.read(); } catch (Exception ignored) {}
testLookupFailWhenServerDown();
System.out.println();
System.out.println("=== TC5: Invalid method call → RemoteException ===");
testInvalidLookup();
System.out.println();
}
static boolean testConnection() {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
registry.lookup("MultiThreadedServer");
return true;
} catch (Exception e) {
System.err.println("TC1 Exception:");
e.printStackTrace();
return false;
}
}
static void testRequestResponse() {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
MultiThreadedServerInterface stub = (MultiThreadedServerInterface)
registry.lookup("MultiThreadedServer");
String response = stub.processRequest("Hello TC2");
System.out.println("TC2 Server response: " + response);
} catch (Exception e) {
System.err.println("TC2 Exception:");
e.printStackTrace();
}
}
static void testMultipleClients() {
final int clients = 5;
Thread[] threads = new Thread[clients];
for (int i = 0; i < clients; i++) {
final int id = i + 1;
threads[i] = new Thread(() -> {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
MultiThreadedServerInterface stub = (MultiThreadedServerInterface)
registry.lookup("MultiThreadedServer");
String response = stub.processRequest("Request from client " + id);
System.out.println("TC3 Client " + id + " received: " + response);
} catch (Exception e) {
System.err.println("TC3 Client " + id + " Exception:");
e.printStackTrace();
}
});
threads[i].start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
static void testLookupFailWhenServerDown() {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
registry.lookup("MultiThreadedServer"); // Expected to fail if server is down
System.err.println("TC4 Unexpected success: server lookup succeeded when server should be down!");
} catch (Exception e) {
System.out.println("TC4 Expected failure (server not running):");
e.printStackTrace();
}
}
static void testInvalidLookup() {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
registry.lookup("InvalidServerName"); // Expected to throw NotBoundException
System.err.println("TC5 Unexpected success: invalid lookup succeeded!");
} catch (Exception e) {
System.out.println("TC5 Expected failure (invalid lookup):");
e.printStackTrace();
}
}
}

Output:

MultiThreadedServer.java

Java RMI registry created.


Server ready...
Processing request in thread: RMI TCP Connection(4)-172.15.23.124
Processing request in thread: RMI TCP Connection(4)-172.15.23.124
Processing request in thread: RMI TCP Connection(9)-172.15.23.124
Processing request in thread: RMI TCP Connection(10)-172.15.23.124
Processing request in thread: RMI TCP Connection(9)-172.15.23.124
Processing request in thread: RMI TCP Connection(9)-172.15.23.124
TestClient.java

=== TC1: Start server, connect client → Success ===


TC1 Result: Success
=== TC2: Client sends request → Server responds ===
TC2 Server response: Processed: Hello TC2 by thread RMI TCP Connection(4)-172.15.23.124
=== TC3: Multiple clients → Handled via threads ===
TC3 Client 1 received: Processed: Request from client 1 by thread RMI TCP Connection(9)-172.15.23.124
TC3 Client 4 received: Processed: Request from client 4 by thread RMI TCP Connection(9)-172.15.23.124
TC3 Client 3 received: Processed: Request from client 3 by thread RMI TCP Connection(10)-172.15.23.124
TC3 Client 2 received: Processed: Request from client 2 by thread RMI TCP Connection(4)-172.15.23.124
TC3 Client 5 received: Processed: Request from client 5 by thread RMI TCP Connection(9)-172.15.23.124
=== TC4: Server not running → Lookup fails ===
Please STOP the server and press Enter to continue...

Test case 5:

TC5.java

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class TC5 {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
System.out.println("Trying to lookup invalid server name...");
registry.lookup("InvalidServerName"); // This does NOT exist
System.out.println("ERROR: Lookup succeeded unexpectedly!");
} catch (Exception e) {
System.out.println("TC5 Expected failure (invalid lookup):");
e.printStackTrace();
}
}
}

Output:
Trying to lookup invalid server name...
TC5 Expected failure (invalid lookup):
java.rmi.NotBoundException: InvalidServerName
​ at java.rmi/sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:237)
​ at java.rmi/sun.rmi.registry.RegistryImpl_Skel.dispatch(RegistryImpl_Skel.java:133)
​ at java.rmi/sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:470)
​ at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:299)
​ at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
​ at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
​ at java.base/java.security.AccessController.doPrivileged(AccessController.java:714)
​ at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
​ at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:598)
​ at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:844)
​ at
java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:721)
​ at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
​ at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:720)
​ at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
​ at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
​ at java.base/java.lang.Thread.run(Thread.java:1575)
​ at
java.rmi/sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:304)
​ at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:280)
​ at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:382)
​ at java.rmi/sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:123)
​ at TC5.main(TC5.java:9)

MCQ’s:

1.​ b) Remote Method Invocation​

2.​ a) java.rmi​

3.​ b) bind()​

4.​ b) LocateRegistry​

5.​ c) RemoteException​

6.​ c) Extend UnicastRemoteObject​

7.​ c) Remote​

8.​ c) lookup()​

9.​ b) Yes​

10.​ c) rmiregistry​
13. Program Title: GUI for Temperature Conversion

TemperatureConverter.java

import javax.swing.*;
import java.awt.event.*;
public class TemperatureConverter extends JFrame {
private JTextField inputField; // Input field for temperature value
private JButton toCelsiusBtn; // Button to convert to Celsius
private JButton toFahrenheitBtn; // Button to convert to Fahrenheit
private JLabel resultLabel; // Label to show result or error messages
public TemperatureConverter() {
setTitle("Temperature Converter");
setSize(320, 160);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
JLabel inputLabel = new JLabel("Enter Temperature:");
inputLabel.setBounds(10, 10, 130, 25);
add(inputLabel);
inputField = new JTextField();
inputField.setBounds(140, 10, 150, 25);
add(inputField);
toCelsiusBtn = new JButton("Convert to Celsius");
toCelsiusBtn.setBounds(10, 50, 140, 30);
add(toCelsiusBtn);
toFahrenheitBtn = new JButton("Convert to Fahrenheit");
toFahrenheitBtn.setBounds(160, 50, 140, 30);
add(toFahrenheitBtn);
resultLabel = new JLabel("Result: ");
resultLabel.setBounds(10, 90, 290, 25);
add(resultLabel);
// Add button listeners
toCelsiusBtn.addActionListener(e -> convertToCelsius());
toFahrenheitBtn.addActionListener(e -> convertToFahrenheit());
}
// Convert Fahrenheit to Celsius
private void convertToCelsius() {
String input = inputField.getText().trim();
// TC4: Blank input → show error
if (input.isEmpty()) {
resultLabel.setText("Error: Input cannot be blank.");
return;
}
try {
double f = Double.parseDouble(input); // Try to parse input number
// TC1: Input 100°F → Output 37.78°C handled here
double c = (f - 32) * 5 / 9; // Convert F to C
resultLabel.setText(String.format("Result: %.2f °C", c));
} catch (NumberFormatException ex) {
// TC5: Invalid input like "abc"
resultLabel.setText("Invalid input! Please enter a number.");
}
}
// Convert Celsius to Fahrenheit
private void convertToFahrenheit() {
String input = inputField.getText().trim();
// TC4: Blank input → show error
if (input.isEmpty()) {
resultLabel.setText("Error: Input cannot be blank.");
return;
}
try {
double c = Double.parseDouble(input); // Parse input number
// TC2: Input 0°C → Output 32°F handled here
// TC3: Input -40°C → Output -40°F handled here
double f = (c * 9 / 5) + 32; // Convert C to F
resultLabel.setText(String.format("Result: %.2f °F", f));
} catch (NumberFormatException ex) {
// TC5: Invalid input like "abc"
resultLabel.setText("Invalid input! Please enter a number.");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new TemperatureConverter().setVisible(true);
});
}
}

Output:

Test case 1:
Test case 2:

Test Case 3:

Test Case 4:
Test Case 5:

Output:

1.​ a) java.awt​

2.​ b) JButton​

3.​ c) GridLayout​

4.​ c) ActionEvent​

5.​ c) add()​

6.​ c) getText()​

7.​ b) Celsius​

8.​ b) (C × 9/5) + 32​

9.​ c) LayoutManager​

10.​ d) Handled using try-catch​

14. Program Title: JavaFX Media Player

Step 1: Install JavaFX SDK


Download JavaFX SDK from Gluon — choose the version matching your JDK and OS.

Extract the downloaded ZIP to a folder on your system (e.g., C:\javafx-sdk-20).

Step 2: Create a JavaFX Project in Eclipse


Open Eclipse.
Go to File → New → Java Project.

Name it (e.g., JavaFXMediaPlayer).

Click Finish.

Step 3: Add JavaFX libraries to Build Path


Right-click your project → Properties.

Select Java Build Path → Libraries tab.

Click Modulepath → Add External JARs.

Browse to the lib folder inside your extracted JavaFX SDK directory (e.g., C:\javafx-sdk-20\lib).

Select all JAR files in that folder → Click Open → Then Apply and Close.

Step 4: Add VM arguments to run configuration


Go to Run → Run Configurations.

Select your project’s run configuration or create a new one.

In the Arguments tab, in the VM arguments box, paste this (adjust path to your JavaFX SDK lib folder):

bash
Copy
Edit
--module-path "C:\javafx-sdk-20\lib" --add-modules javafx.controls,javafx.media
(Use double quotes if your path contains spaces.)

Step 5: Add your JavaFX media player code


Inside src, create a new class: BasicMediaPlayer.

Paste the complete JavaFX media player code I provided.

Save all files.

Step 6: Run your JavaFX program


Right-click your BasicMediaPlayer.java → Run As → Java Application.

The media player window should appear.

Use Load Media button to pick a media file and test play/pause/stop.
BasicMediaPlayer.java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
public class BasicMediaPlayer extends Application {
private MediaPlayer mediaPlayer;
private Label statusLabel = new Label("No media loaded.");
@Override
public void start(Stage primaryStage) {
// Buttons for control
Button loadButton = new Button("Load Media");
Button playButton = new Button("Play");
Button pauseButton = new Button("Pause");
Button stopButton = new Button("Stop");
// Initially disable play, pause, and stop buttons
playButton.setDisable(true);
pauseButton.setDisable(true);
stopButton.setDisable(true);
// Load media file (used for TC4 and TC5 handling)
loadButton.setOnAction(e -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose Media File");
File file = fileChooser.showOpenDialog(primaryStage);
if (file != null) {
try {
if (mediaPlayer != null) {
mediaPlayer.dispose(); // Clean up old media player
}
// Load media - handles TC5 (MediaException if unsupported format)
Media media = new Media(file.toURI().toString());
mediaPlayer = new MediaPlayer(media);
// Enable control buttons
playButton.setDisable(false);
pauseButton.setDisable(false);
stopButton.setDisable(false);
statusLabel.setText("Media loaded: " + file.getName());
// Media events
mediaPlayer.setOnPlaying(() -> statusLabel.setText("Playing")); // TC1
mediaPlayer.setOnPaused(() -> statusLabel.setText("Paused")); // TC2
mediaPlayer.setOnStopped(() -> statusLabel.setText("Stopped")); // TC3
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.stop();
statusLabel.setText("Playback finished");
});
mediaPlayer.setOnError(() ->
statusLabel.setText("Error: " + mediaPlayer.getError().getMessage())
);
} catch (MediaException ex) {
// TC5: Invalid or unsupported media format
statusLabel.setText("Unsupported media format.");
playButton.setDisable(true);
pauseButton.setDisable(true);
stopButton.setDisable(true);
}
} else {
// TC4: No file selected
statusLabel.setText("No file loaded.");
}
});
// TC1: Play
playButton.setOnAction(e -> {
if (mediaPlayer != null) {
mediaPlayer.play();
} else {
statusLabel.setText("Error: Load a media file first."); // TC4 fallback
}
});
// TC2: Pause
pauseButton.setOnAction(e -> {
if (mediaPlayer != null) {
mediaPlayer.pause();
}
});
// TC3: Stop and reset
stopButton.setOnAction(e -> {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.seek(Duration.ZERO); // Reset to beginning
}
});
// Layout setup
HBox controls = new HBox(10, loadButton, playButton, pauseButton, stopButton);
VBox root = new VBox(10, controls, statusLabel);
root.setStyle("-fx-padding: 20; -fx-alignment: center;");
Scene scene = new Scene(root, 420, 140);
primaryStage.setTitle("JavaFX Media Player");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

TC1: Click Play → Output: Media starts

TC2: Click Pause → Output: Media pauses


TC3: Click Stop → Output: Media stops and resets

TC4: No file loaded → Output: Error message


TC5: Play file in unsupported format → Output: MediaException

MCQ’s:

1.​ b) Media​

2.​ c) MediaPlayer​

3.​ d) All of the above​

4.​ d) All of the above​

5.​ c) play()​

6.​ c) start(Stage)​

7.​ b) Stops media and resets​

8.​ a) MediaException​

9.​ c) Stage​

10.​ b) new Media(path)


15. Program Title: Real-Time Data Visualization in JavaFX

RealTimeChartApp.java

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import java.util.Random;
public class RealTimeChartApp extends Application {
private XYChart.Series<Number, Number> series;
private int xValue = 0;
private Timeline timeline;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Real-time Data Visualization");
// Step 2: Create axes and LineChart
NumberAxis xAxis = new NumberAxis();
xAxis.setLabel("Time (seconds)");
NumberAxis yAxis = new NumberAxis();
yAxis.setLabel("Value");
LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
lineChart.setTitle("Real-time Line Chart");
// Initialize series and add to chart
series = new XYChart.Series<>();
series.setName("Random Data");
lineChart.getData().add(series);
// Buttons to start/stop updates
Button startBtn = new Button("Start");
Button stopBtn = new Button("Stop");
// Step 3 & 4: Simulate data and update chart every second
timeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> addData()));
timeline.setCycleCount(Timeline.INDEFINITE);
startBtn.setOnAction(e -> timeline.play());
stopBtn.setOnAction(e -> timeline.pause());
VBox vbox = new VBox(10, lineChart, startBtn, stopBtn);
Scene scene = new Scene(vbox, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
// TC1: App starts with empty chart (series empty)
}
private void addData() {
// Step 5: Handle non-numeric gracefully by simulating only numeric values here
try {
Random random = new Random();
double yValue = 10 + random.nextDouble() * 90; // Range 10-100
// TC4: Chart scales automatically as NumberAxis does by default
Platform.runLater(() -> series.getData().add(new XYChart.Data<>(xValue++, yValue)));
// Limit points to keep chart readable
if (series.getData().size() > 30) {
Platform.runLater(() -> series.getData().remove(0));
}
} catch (Exception ex) {
System.err.println("Error adding data: " + ex.getMessage());
}
}
public static void main(String[] args) {
launch(args);
}
}
TC1: App starts → Chart displays empty
TC2: Data added every second → Graph updates in real-time
TC3: Stop updates → Graph freezes
TC4: Data out of range → Chart scales accordingly

TC5: Non-numeric input → Handled gracefully

Invalid input detected: Simulated non-numeric input


Invalid input detected: Simulated non-numeric input
Invalid input detected: Simulated non-numeric input
Invalid input detected: Simulated non-numeric input
Invalid input detected: Simulated non-numeric input
MCQ’s:

1.​ c) LineChart​

2.​ b) Chart​

3.​ c) Timeline​

4.​ b) XYChart.Series​

5.​ b) Updates UI from background​

6.​ d) Timeline​

7.​ a) Strings​

8.​ a) setData()​

9.​ d) Can slow down​

10.​ c) BorderPane​

You might also like