0% found this document useful (0 votes)
10 views15 pages

Java Programming Lab Manual: Algorithms & GUI

The document is a Java Programming Lab Manual detailing various experiments focused on algorithms, data structures, inheritance, exception handling, multithreading, file operations, generics, JavaFX GUI development, and a mini project. Each experiment includes objectives, program code, and sample outputs demonstrating the concepts. The manual serves as a practical guide for learning and implementing core Java programming skills.

Uploaded by

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

Java Programming Lab Manual: Algorithms & GUI

The document is a Java Programming Lab Manual detailing various experiments focused on algorithms, data structures, inheritance, exception handling, multithreading, file operations, generics, JavaFX GUI development, and a mini project. Each experiment includes objectives, program code, and sample outputs demonstrating the concepts. The manual serves as a practical guide for learning and implementing core Java programming skills.

Uploaded by

vinoth1001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming Lab Manual with

Code and Output


Experiment 1: Search and Sort Algorithms
Objective: Solve problems using Sequential Search, Binary Search, Selection Sort, and
Insertion Sort algorithms.

Program Code:

// Sequential Search
public class SequentialSearch {
public static int search(int[] arr, int key) {
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) return i;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int key = 30;
int result = search(arr, key);
[Link]("Element found at index: " + result);
}
}

Sample Output:
Element found at index: 2
Experiment 2: Stacks and Queues
Objective: Implement Stack and Queue data structures using classes and objects.

Program Code:

import [Link];

class Stack {
LinkedList<Integer> list = new LinkedList<>();
void push(int x) { [Link](x); }
int pop() { return [Link](); }
}

class Queue {
LinkedList<Integer> list = new LinkedList<>();
void enqueue(int x) { [Link](x); }
int dequeue() { return [Link](); }
}

public class Test {


public static void main(String[] args) {
Stack stack = new Stack();
[Link](10); [Link](20);
[Link]("Popped from stack: " + [Link]());

Queue queue = new Queue();


[Link](10); [Link](20);
[Link]("Dequeued from queue: " + [Link]());
}
}

Sample Output:
Popped from stack: 20
Dequeued from queue: 10
Experiment 3: Employee Payroll System using Inheritance
Objective: Develop a Java application to generate pay slips for employees using inheritance
and salary components.

Program Code:

class Employee {
String empName, empId, address, mailId;
long mobileNo;
Employee(String name, String id, String addr, String mail, long mobile) {
empName = name; empId = id; address = addr; mailId = mail; mobileNo = mobile;
}
}

class Programmer extends Employee {


double bp;
Programmer(String name, String id, String addr, String mail, long mobile, double bp) {
super(name, id, addr, mail, mobile);
[Link] = bp;
}
void generatePaySlip() {
double da = 0.97 * bp;
double hra = 0.10 * bp;
double pf = 0.12 * bp;
double club = 0.001 * bp;
double gross = bp + da + hra;
double net = gross - pf - club;
[Link]("Gross Salary: " + gross + ", Net Salary: " + net);
}
}

public class Main {


public static void main(String[] args) {
Programmer p = new Programmer("John", "E001", "City", "john@[Link]",
9876543210L, 50000);
[Link]();
}
}

Sample Output:
Gross Salary: 106000.0, Net Salary: 100399.0
Experiment 4: Abstract Class and Area Calculation
Objective: Create an abstract class 'Shape' and implement subclasses Rectangle, Triangle,
and Circle to calculate area.

Program Code:

abstract class Shape {


int a, b;
abstract void printArea();
}

class Rectangle extends Shape {


Rectangle(int x, int y) { a = x; b = y; }
void printArea() {
[Link]("Rectangle Area: " + (a * b));
}
}

class Triangle extends Shape {


Triangle(int x, int y) { a = x; b = y; }
void printArea() {
[Link]("Triangle Area: " + (0.5 * a * b));
}
}

class Circle extends Shape {


Circle(int r) { a = r; }
void printArea() {
[Link]("Circle Area: " + (3.14 * a * a));
}
}

public class Main {


public static void main(String[] args) {
Shape s1 = new Rectangle(10, 20);
Shape s2 = new Triangle(10, 15);
Shape s3 = new Circle(7);
[Link]();
[Link]();
[Link]();
}
}

Sample Output:
Rectangle Area: 200
Triangle Area: 75.0
Circle Area: 153.86
Experiment 5: Interface Implementation of Shape
Objective: Solve the area calculation problem using an interface instead of an abstract class.

Program Code:

interface Shape {
void printArea();
}

class Rectangle implements Shape {


int length, breadth;
Rectangle(int l, int b) { length = l; breadth = b; }
public void printArea() {
[Link]("Rectangle Area: " + (length * breadth));
}
}

class Triangle implements Shape {


int base, height;
Triangle(int b, int h) { base = b; height = h; }
public void printArea() {
[Link]("Triangle Area: " + (0.5 * base * height));
}
}

class Circle implements Shape {


int radius;
Circle(int r) { radius = r; }
public void printArea() {
[Link]("Circle Area: " + (3.14 * radius * radius));
}
}

public class Main {


public static void main(String[] args) {
Shape s1 = new Rectangle(10, 5);
Shape s2 = new Triangle(8, 6);
Shape s3 = new Circle(7);
[Link]();
[Link]();
[Link]();
}
}

Sample Output:
Rectangle Area: 50
Triangle Area: 24.0
Circle Area: 153.86
Experiment 6: Exception Handling
Objective: Demonstrate exception handling in Java and creation of user-defined exceptions.

Program Code:

class MyException extends Exception {


MyException(String message) {
super(message);
}
}

public class Main {


static void validate(int age) throws MyException {
if(age < 18)
throw new MyException("Age is less than 18");
else
[Link]("Age is valid");
}

public static void main(String[] args) {


try {
validate(15);
} catch (MyException e) {
[Link]("Caught Exception: " + [Link]());
}
}
}

Sample Output:
Caught Exception: Age is less than 18
Experiment 7: Multithreading with Conditional Logic
Objective: Implement a multi-threaded application that generates random numbers and
computes square or cube based on parity.

Program Code:

import [Link];

class NumberGenerator extends Thread {


public void run() {
Random rand = new Random();
for(int i = 0; i < 5; i++) {
int num = [Link](100);
[Link]("Generated Number: " + num);
if(num % 2 == 0)
new Square(num).start();
else
new Cube(num).start();
try {
[Link](1000);
} catch(Exception e) {}
}
}
}

class Square extends Thread {


int x;
Square(int x) { this.x = x; }
public void run() {
[Link]("Square of " + x + ": " + (x * x));
}
}

class Cube extends Thread {


int x;
Cube(int x) { this.x = x; }
public void run() {
[Link]("Cube of " + x + ": " + (x * x * x));
}
}

public class Main {


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

Sample Output:
Generated Number: 7
Cube of 7: 343
Generated Number: 4
Square of 4: 16...
Experiment 8: File Operations
Objective: Write a Java program to perform file operations like read, write, and append.

Program Code:

import [Link].*;

public class FileOperation {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("[Link]", true);
[Link]("Hello, File Handling in Java\n");
[Link]();

BufferedReader reader = new BufferedReader(new FileReader("[Link]"));


String line;
while((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch(IOException e) {
[Link]("An error occurred.");
}
}
}

Sample Output:
Hello, File Handling in Java
Experiment 9: Generics in Java
Objective: Develop applications using generic classes to demonstrate type safety and
reusability.

Program Code:

class GenericClass<T> {
T obj;
GenericClass(T obj) { [Link] = obj; }
public void display() {
[Link]("Value: " + obj);
}
}

public class Main {


public static void main(String[] args) {
GenericClass<Integer> intObj = new GenericClass<>(123);
GenericClass<String> strObj = new GenericClass<>("Hello");
[Link]();
[Link]();
}
}

Sample Output:
Value: 123
Value: Hello
Experiment 10: JavaFX GUI Development
Objective: Create GUI applications using JavaFX controls, layouts, and menus.

Program Code:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class JavaFXApp extends Application {


public void start(Stage primaryStage) {
Button btn = new Button("Click Me!");
[Link](e -> [Link]("Button Clicked!"));

StackPane root = new StackPane();


[Link]().add(btn);

Scene scene = new Scene(root, 300, 200);


[Link]("JavaFX Example");
[Link](scene);
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}

Sample Output:
JavaFX GUI appears with button. Console prints 'Button Clicked!' on click.
Experiment 11: Mini Project
Objective: Develop a mini project using core Java concepts to solve a real-world problem.

Program Code:

// Mini project example: Simple Student Management System


import [Link].*;

class Student {
String name;
int id;
Student(String name, int id) {
[Link] = name;
[Link] = id;
}
}

public class StudentSystem {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Student> list = new ArrayList<>();
[Link](new Student("Alice", 1));
[Link](new Student("Bob", 2));

for(Student s : list) {
[Link]("ID: " + [Link] + ", Name: " + [Link]);
}
}
}

Sample Output:
ID: 1, Name: Alice
ID: 2, Name: Bob

Common questions

Powered by AI

The primary differences between using an interface and an abstract class for defining shapes in Java can be observed in the distinct experiment setups provided. In the experiment using an abstract class, `Shape` serves as the base class with concrete subclasses like `Rectangle`, `Triangle`, and `Circle`, each overriding the `printArea` method to provide a specific area calculation . Conversely, the experiment using an interface allows direct implementation by classes like `Rectangle`, `Triangle`, and `Circle` with no shared code structure in a parent class . This signifies a structural shift where inheritance vs implementation choice affects how code reuse and polymorphism are managed.

The use of the `LinkedList` structure in the experiments facilitates efficient implementation of Stack and Queue operations due to its inherent properties of dynamic resizing and node-based architecture. Stacks use `push` and `pop` methods to add and remove elements efficiently, while Queues utilize `enqueue` and `dequeue` methods for ordered processing. Such operations demonstrate Java's flexibility in handling data structures through the collection framework, which abstracts complex memory management and allows for efficient data manipulation reflecting linear queue and stack behaviors intrinsically .

In the multithreading experiment involving number generation and computations, threads like `NumberGenerator`, `Square`, and `Cube` run concurrently, each handling tasks independently. This approach leverages multithreading to perform operations like generating random numbers, determining parity, and computing mathematical functions simultaneously. By doing so, it enhances computational efficiency and better utilizes CPU resources, reducing wait times typically incurred in sequential execution. The experiment illustrates how Java's thread management can improve performance in parallel tasks .

The experiment on generics illustrates type safety and reusability by defining a generic class `GenericClass<T>` that can operate with any object type. This approach avoids the need for type casting and errors at runtime by enforcing type checks during compilation. The instantiation of `GenericClass` with different types, such as `Integer` and `String`, exemplifies reusability, as the same class can handle different data types without code duplication. Thus, generics enhance the flexibility and robustness of code by promoting type parameterization and reducing runtime type errors .

The file operations demonstrate working with Java's I/O streams by using `FileReader` and `FileWriter` for reading from and writing to files, respectively. These classes illustrate direct interaction with file data, showcasing stream usage patterns like opening, reading line-by-line using `BufferedReader`, and writing with appending features. Significantly, they provide a foundation for persistent data handling, a critical aspect of application development that supports functionality like data logging, configuration management, and user data preservation across application sessions .

The Employee Payroll System uses inheritance to extend the `Employee` class into a specific `Programmer` class, demonstrating hierarchical decomposition where a general structure is enhanced with specific details. The `Programmer` class inherits properties like `empName`, `empId`, and methods from `Employee`, thus encapsulating details of an employee while specializing with a method `generatePaySlip` for payroll calculations. This design encapsulates general employee features while allowing additional attributes and methods pertinent to `Programmer`, highlighting how Java balances data hiding and extensibility .

The mini project example of a Simple Student Management System displays the application of core Java concepts such as classes, objects, collections, and user interaction in a real-world scenario. It utilizes `ArrayList` to manage a dynamic list of `Student` objects efficiently, taking advantage of its ability to resize automatically and support iteration for listing students. The project encapsulates data pertinent to a student, applying object-oriented principles to solve practical problems. This enriches functionality with simplicity, providing a scalable solution to a typical administrative task, emphasizing Java's utility in realistic applications .

Exception handling in Java is demonstrated by the creation and use of a custom exception class `MyException`, which inherits from `Exception`. The demonstration involves a method `validate` that throws `MyException` if a condition (age being less than 18) isn't met. This setup shows Java's ability to handle unexpected conditions using user-defined logic rather than relying solely on predefined exceptions. The `try-catch` block usage illustrates how programs can gracefully manage exceptions and maintain control flow, demonstrating a robust error-handling strategy .

The JavaFX GUI development experiment integrates event-driven programming by using a `Button` control and associating an action handler using `setOnAction` to respond to user interactions. This demonstrates event-driven programming principles where specific actions trigger callbacks—in this case, printing 'Button Clicked!' to the console upon button press. The utilization of `StackPane` layout and `Scene` creation further supports GUI encapsulation and customization, showing how JavaFX manages user events within an interactive graphical environment .

The document discusses Selection Sort and Insertion Sort, each with distinct practical efficiencies. Selection Sort, with its O(n^2) complexity, is more suited for small data sets where overhead from algorithm simplicity is negligible. In contrast, Insertion Sort, while also O(n^2), is more adaptive and performs better on partially sorted data. Thus, practical efficiency generally shifts depending on dataset characteristics, size, and existing order. Recognizing these contexts allows for optimized application selection, enhancing performance where algorithm complexity and data state align with operational requirements .

You might also like