Sequential Search: return mid; // Target found at index
mid
Program
} else if (arr[mid] < target) {
public class SequentialSearch {
low = mid + 1;
} else {
public static int sequentialSearch(int[] arr,
high = mid - 1;
int target) {
}
for (int i = 0; i < arr.length; i++) {
}
if (arr[i] == target) {
return i; // Target found at index i
return -1; // Target not found
}
}
}
return -1; // Target not found
public static void main(String[] args) {
}
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 7;
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int result = binarySearch(array, target);
int target = 7;
if (result != -1) {
int result = sequentialSearch(array,
System.out.println("Target found at
target);
index: " + result);
} else {
if (result != -1) {
System.out.println("Target not found in
System.out.println("Target found at
the array.");
index: " + result);
}
} else {
}
System.out.println("Target not found in
}
the array.");
} Selection Sort:
}
Code
}
public class SelectionSort {
public static void selectionSort(int[] arr) {
Binary Search: int n = arr.length;
Program
for (int i = 0; i < n - 1; i++) {
public class BinarySearch {
int minIndex = i;
public static int binarySearch(int[] arr, int
for (int j = i + 1; j < n; j++) {
target) {
if (arr[j] < arr[minIndex]) {
int low = 0;
minIndex = j;
int high = arr.length - 1;
}
}
while (low <= high) {
int mid = low + (high - low) / 2;
// Swap the found minimum element
with the element at index i
if (arr[mid] == target) {
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
Stack Implementation:
}
} Code:
class Stack {
public static void main(String[] args) { private int maxSize;
int[] array = {64, 25, 12, 22, 11}; private int[] stackArray;
selectionSort(array); private int top;
System.out.println("Sorted array:"); public Stack(int size) {
for (int value : array) { maxSize = size;
System.out.print(value + " "); stackArray = new int[maxSize];
} top = -1;
} }
}
Insertion Sort: public void push(int value) {
if (top < maxSize - 1) {
Code stackArray[++top] = value;
public class InsertionSort { System.out.println("Pushed " + value +
" to the stack.");
public static void insertionSort(int[] arr) { } else {
int n = arr.length; System.out.println("Stack is full. Cannot
push " + value + ".");
for (int i = 1; i < n; i++) { }
int key = arr[i]; }
int j = i - 1;
public int pop() {
// Move elements of arr[0..i-1] that are if (top >= 0) {
greater than key to one position ahead of int poppedValue = stackArray[top--];
their current position System.out.println("Popped " +
while (j >= 0 && arr[j] > key) { poppedValue + " from the stack.");
arr[j + 1] = arr[j]; return poppedValue;
j = j - 1; } else {
} System.out.println("Stack is empty.
arr[j + 1] = key; Cannot pop.");
} return -1; // Return a special value to
} indicate an empty stack
}
public static void main(String[] args) { }
int[] array = {12, 11, 13, 5, 6};
insertionSort(array); public boolean isEmpty() {
return top == -1;
System.out.println("Sorted array:"); }
for (int value : array) { }
System.out.print(value + " ");
} public class StackExample {
} public static void main(String[] args) {
} Stack stack = new Stack(5);
stack.push(1); System.out.println("Dequeued " +
stack.push(2); dequeuedValue + " from the queue.");
stack.push(3); return dequeuedValue;
} else {
System.out.println("Is stack empty? " + System.out.println("Queue is empty.
stack.isEmpty()); Cannot dequeue.");
return -1; // Return a special value to
stack.pop(); indicate an empty queue
stack.pop(); }
stack.pop(); }
stack.pop();
public boolean isEmpty() {
System.out.println("Is stack empty? " + return front > rear;
stack.isEmpty()); }
} }
}
Queue Implementation: public class QueueExample {
public static void main(String[] args) {
Code Queue queue = new Queue(5);
class Queue {
private int maxSize; queue.enqueue(1);
private int[] queueArray; queue.enqueue(2);
private int front; queue.enqueue(3);
private int rear;
System.out.println("Is queue empty? " +
public Queue(int size) { queue.isEmpty());
maxSize = size;
queueArray = new int[maxSize]; queue.dequeue();
front = 0; queue.dequeue();
rear = -1; queue.dequeue();
} queue.dequeue();
public void enqueue(int value) { System.out.println("Is queue empty? " +
if (rear < maxSize - 1) { queue.isEmpty());
queueArray[++rear] = value; }
System.out.println("Enqueued " + value }
+ " to the queue.");
} else { Develop a java application with an
System.out.println("Queue is full. Employee class with Emp_name, Emp_id,
Cannot enqueue " + value + "."); Address, Mail_id, Mobile no as members.
Inherit the classes, Programmer, Assistant
}
Professor, Associate Professor and
} Professor from employee class. Add Basic
Pay (BP) as the member of all the
public int dequeue() { inherited classes with 97% of BP as DA,
if (!isEmpty()) { 10 % of BP as HRA, 12% of BP as PF,
int dequeuedValue = 0.1% of BP for staff club funds. Generate
queueArray[front++]; pay slips for the employees with their
gross and net salary.
System.out.println("Mail ID: " + mailId);
Code: System.out.println("Mobile No: " +
class Employee { mobileNo);
protected String empName; System.out.println("Basic Pay: " +
protected int empId; basicPay);
protected String address; System.out.println("DA: " + da);
protected String mailId; System.out.println("HRA: " + hra);
protected String mobileNo; System.out.println("PF: " + pf);
System.out.println("Staff Club Funds: " +
public Employee(String empName, int clubFunds);
empId, String address, String mailId, String System.out.println("Gross Salary: " +
mobileNo) { grossSalary);
this.empName = empName; System.out.println("Net Salary: " +
this.empId = empId; netSalary);
this.address = address; System.out.println();
this.mailId = mailId; }
this.mobileNo = mobileNo; }
}
} // Similar implementations for
AssistantProfessor, AssociateProfessor, and
class Programmer extends Employee { Professor classes
private double basicPay;
public class SalaryApplication {
public Programmer(String empName, int public static void main(String[] args) {
empId, String address, String mailId, String Programmer programmer = new
mobileNo, double basicPay) { Programmer("John Doe", 101, "123 Main St",
super(empName, empId, address, mailId, "
[email protected]", "1234567890", 50000);
mobileNo); programmer.generatePaySlip();
this.basicPay = basicPay;
} // Create instances of other employee
types and generate pay slips as needed
public void generatePaySlip() { }
double da = 0.97 * basicPay; }
double hra = 0.10 * basicPay;
double pf = 0.12 * basicPay; Write a Java Program to create an
double clubFunds = 0.001 * basicPay; abstract class named Shape that contains
two integers and an empty method named
printArea(). Provide three classes named
double grossSalary = basicPay + da + hra;
Rectangle, Triangle and Circle such that
double netSalary = grossSalary - pf - each one of the classes extends the class
clubFunds; Shape. Each one of the classes contains
only the method printArea( ) that prints the
System.out.println("Pay Slip for area of the given shape.
Programmer");
System.out.println("Employee Name: " + abstract class Shape {
empName); protected int side1;
System.out.println("Employee ID: " + protected int side2;
empId);
System.out.println("Address: " + address); public Shape(int side1, int side2) {
this.side1 = side1;
this.side2 = side2; public class ShapeTest {
} public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5,
// Abstract method to be implemented by 8);
subclasses rectangle.printArea();
public abstract void printArea();
} Triangle triangle = new Triangle(4, 6);
triangle.printArea();
class Rectangle extends Shape {
public Rectangle(int length, int width) { Circle circle = new Circle(3);
super(length, width); circle.printArea();
} }
}
@Override
public void printArea() { Solve the above problem using an
int area = side1 * side2; interface.
System.out.println("Area of Rectangle: " + interface Shape {
area); void printArea();
} }
}
class Rectangle implements Shape {
class Triangle extends Shape { private int length;
public Triangle(int base, int height) { private int width;
super(base, height);
} public Rectangle(int length, int width) {
this.length = length;
@Override this.width = width;
public void printArea() { }
double area = 0.5 * side1 * side2;
System.out.println("Area of Triangle: " + @Override
area); public void printArea() {
} int area = length * width;
} System.out.println("Area of Rectangle: " +
area);
class Circle extends Shape { }
public Circle(int radius) { }
super(radius, 0); // For a circle, side1
represents the radius, and side2 is not needed class Triangle implements Shape {
} private int base;
private int height;
@Override
public void printArea() { public Triangle(int base, int height) {
double area = Math.PI * side1 * side1; this.base = base;
System.out.println("Area of Circle: " + this.height = height;
area); }
}
} @Override
public void printArea() { void printArea() throws
double area = 0.5 * base * height; InvalidShapeException;
System.out.println("Area of Triangle: " + }
area);
} class Rectangle implements Shape {
} private int length;
private int width;
class Circle implements Shape {
private int radius; public Rectangle(int length, int width) {
this.length = length;
public Circle(int radius) { this.width = width;
this.radius = radius; }
}
@Override
@Override public void printArea() throws
public void printArea() { InvalidShapeException {
double area = Math.PI * radius * radius; if (length <= 0 || width <= 0) {
System.out.println("Area of Circle: " + throw new
area); InvalidShapeException("Invalid dimensions for
} Rectangle. Length and width must be
} positive.");
}
public class ShapeTest {
public static void main(String[] args) { int area = length * width;
Rectangle rectangle = new Rectangle(5, System.out.println("Area of Rectangle: " +
8); area);
rectangle.printArea(); }
}
Triangle triangle = new Triangle(4, 6);
triangle.printArea(); class Triangle implements Shape {
private int base;
Circle circle = new Circle(3); private int height;
circle.printArea();
} public Triangle(int base, int height) {
} this.base = base;
this.height = height;
Implement exception handling and }
creation of user defined exceptions.
@Override
class InvalidShapeException extends public void printArea() throws
Exception { InvalidShapeException {
public InvalidShapeException(String if (base <= 0 || height <= 0) {
message) { throw new
super(message); InvalidShapeException("Invalid dimensions for
} Triangle. Base and height must be positive.");
} }
interface Shape { double area = 0.5 * base * height;
System.out.println("Area of Triangle: " + }
area); }
} }
}
Write a java program that implements a
class Circle implements Shape { multi-threaded application that has three
private int radius; threads. First thread generates a random
integer every 1 second and if the value is
even, the second thread computes the
public Circle(int radius) { square of the number and prints. If the
this.radius = radius; value is odd, the third thread will print the
} value of the cube of the number.
@Override import java.util.Random;
public void printArea() throws
InvalidShapeException { class SharedResource {
if (radius <= 0) { private int value;
throw new private boolean isValueGenerated;
InvalidShapeException("Invalid dimension for
Circle. Radius must be positive."); public synchronized void setValue(int value)
} {
while (isValueGenerated) {
double area = Math.PI * radius * radius; try {
System.out.println("Area of Circle: " + wait(); // Wait for the value to be
area); processed by the other threads
} } catch (InterruptedException e) {
} Thread.currentThread().interrupt();
}
public class ShapeTest { }
public static void main(String[] args) { this.value = value;
try { isValueGenerated = true;
Rectangle rectangle = new Rectangle(5, notifyAll(); // Notify waiting threads that
8); the value is ready
rectangle.printArea(); }
Triangle triangle = new Triangle(4, 6); public synchronized int getValue() {
triangle.printArea(); while (!isValueGenerated) {
try {
Circle circle = new Circle(3); wait(); // Wait for the value to be
circle.printArea(); generated by the first thread
} catch (InterruptedException e) {
// Uncomment the lines below to test Thread.currentThread().interrupt();
the user-defined exception }
// Rectangle invalidRectangle = new }
Rectangle(-2, 10); isValueGenerated = false;
// invalidRectangle.printArea(); notifyAll(); // Notify waiting threads that
} catch (InvalidShapeException e) { the value has been consumed
System.out.println("Exception: " + return value;
e.getMessage()); }
} System.out.println("Square of " +
value + ": " + (value * value));
class NumberGeneratorThread extends }
Thread { }
private SharedResource sharedResource; }
}
public
NumberGeneratorThread(SharedResource class CubeThread extends Thread {
sharedResource) { private SharedResource sharedResource;
this.sharedResource = sharedResource;
} public CubeThread(SharedResource
sharedResource) {
@Override this.sharedResource = sharedResource;
public void run() { }
Random random = new Random();
while (true) { @Override
int randomNumber = public void run() {
random.nextInt(100); // Generating random while (true) {
integers between 0 and 99 int value = sharedResource.getValue();
System.out.println("Generated if (value % 2 != 0) {
number: " + randomNumber); System.out.println("Cube of " + value
+ ": " + (value * value * value));
sharedResource.setValue(randomNumber); }
}
try { }
Thread.sleep(1000); // Sleep for 1 }
second
} catch (InterruptedException e) { public class MultiThreadedApplication {
Thread.currentThread().interrupt(); public static void main(String[] args) {
} SharedResource sharedResource = new
} SharedResource();
}
} NumberGeneratorThread
generatorThread = new
class SquareThread extends Thread { NumberGeneratorThread(sharedResource);
private SharedResource sharedResource; SquareThread squareThread = new
SquareThread(sharedResource);
public SquareThread(SharedResource CubeThread cubeThread = new
sharedResource) { CubeThread(sharedResource);
this.sharedResource = sharedResource;
} generatorThread.start();
squareThread.start();
@Override cubeThread.start();
public void run() { }
while (true) { }
int value = sharedResource.getValue();
if (value % 2 == 0) { Write a program to perform file operations.
import java.io.IOException; try {
import java.nio.file.Files; Path path = Paths.get(filePath);
import java.nio.file.Path; Files.write(path, content.getBytes(),
import java.nio.file.Paths; StandardOpenOption.WRITE);
import java.nio.file.StandardOpenOption; System.out.println("Data written to
import java.util.List; file: " + path);
} catch (IOException e) {
public class FileOperations { e.printStackTrace();
}
public static void main(String[] args) { }
// Specify the file path
String filePath = "example.txt"; private static void readFromFile(String
filePath) {
// Create a file try {
createFile(filePath); Path path = Paths.get(filePath);
List<String> lines =
// Write data to the file Files.readAllLines(path);
writeToFile(filePath, "Hello, this is a System.out.println("Data read from
sample text."); file: " + path);
for (String line : lines) {
// Read data from the file System.out.println(line);
readFromFile(filePath); }
} catch (IOException e) {
// Append additional data to the file e.printStackTrace();
appendToFile(filePath, "\nAppending }
more text."); }
// Read data from the file after appending private static void appendToFile(String
readFromFile(filePath); filePath, String content) {
try {
// Delete the file Path path = Paths.get(filePath);
deleteFile(filePath); Files.write(path, content.getBytes(),
} StandardOpenOption.APPEND);
System.out.println("Data appended to
private static void createFile(String filePath) file: " + path);
{ } catch (IOException e) {
try { e.printStackTrace();
Path path = Paths.get(filePath); }
Files.createFile(path); }
System.out.println("File created: " +
path); private static void deleteFile(String filePath)
} catch (IOException e) { {
e.printStackTrace(); try {
} Path path = Paths.get(filePath);
} Files.deleteIfExists(path);
System.out.println("File deleted: " +
private static void writeToFile(String path);
filePath, String content) { } catch (IOException e) {
e.printStackTrace();
} import javafx.application.Application;
} import javafx.scene.Scene;
} import javafx.scene.control.Button;
import javafx.scene.control.Label;
Develop applications to demonstrate the import javafx.scene.control.TextField;
features of generics classes. import javafx.scene.layout.HBox;
import javafx.stage.Stage;
class Box<T> {
private T value; public class JavaFXControlsExample extends
Application {
public Box(T value) {
this.value = value; @Override
} public void start(Stage primaryStage) {
// Create controls
public T getValue() { Label nameLabel = new Label("Name:");
return value; TextField nameTextField = new
} TextField();
Button submitButton = new
public void setValue(T value) { Button("Submit");
this.value = value;
} // Create layout (HBox)
HBox hbox = new HBox(10); // 10 pixels
public void displayBoxType() { spacing
System.out.println("Type of the box: " + hbox.getChildren().addAll(nameLabel,
value.getClass().getName()); nameTextField, submitButton);
}
} // Create scene
Scene scene = new Scene(hbox, 300,
public class GenericBoxExample { 150);
public static void main(String[] args) {
// Creating a Box of Integer // Set stage properties
Box<Integer> intBox = new Box<>(10); primaryStage.setTitle("JavaFX Controls
intBox.displayBoxType(); Example");
System.out.println("Box Value: " + primaryStage.setScene(scene);
intBox.getValue());
// Show the stage
// Creating a Box of String primaryStage.show();
Box<String> stringBox = new }
Box<>("Hello, Generics!");
stringBox.displayBoxType(); public static void main(String[] args) {
System.out.println("Box Value: " + launch(args);
stringBox.getValue()); }
} }
}
Develop a mini project for any application
Develop applications using JavaFX using Java concepts.
controls, layouts and menus. .
// Create scene
import javafx.application.Application; Scene scene = new Scene(vbox, 300, 400);
import javafx.scene.Scene;
import javafx.scene.control.*; // Set stage properties
import javafx.scene.layout.VBox; primaryStage.setTitle("To-Do List App");
import javafx.stage.Stage; primaryStage.setScene(scene);
import java.io.*; // Show the stage
import java.util.ArrayList; primaryStage.show();
import java.util.List; }
public class ToDoListApp extends Application { private void addTask() {
String task =
private List<String> tasks; taskInputField.getText().trim();
private ListView<String> taskListView; if (!task.isEmpty()) {
private TextField taskInputField; tasks.add(task);
updateListView();
private static final String FILE_PATH = saveTasksToFile();
"todolist.txt"; taskInputField.clear();
}
@Override }
public void start(Stage primaryStage) {
// Load tasks from file private void removeTask() {
tasks = loadTasksFromFile(); int selectedIndex =
taskListView.getSelectionModel().getSelectedI
// Create UI components ndex();
Label titleLabel = new Label("To-Do List"); if (selectedIndex >= 0) {
taskListView = new ListView<>(); tasks.remove(selectedIndex);
taskListView.getItems().addAll(tasks); updateListView();
saveTasksToFile();
taskInputField = new TextField(); }
Button addButton = new Button("Add }
Task");
Button removeButton = new private void updateListView() {
Button("Remove Task"); taskListView.getItems().setAll(tasks);
}
// Set event handlers
addButton.setOnAction(e -> addTask()); private List<String> loadTasksFromFile() {
removeButton.setOnAction(e -> List<String> loadedTasks = new
removeTask()); ArrayList<>();
try (BufferedReader reader = new
// Create layout (VBox) BufferedReader(new FileReader(FILE_PATH)))
VBox vbox = new VBox(10); // 10 pixels {
spacing String line;
vbox.getChildren().addAll(titleLabel, while ((line = reader.readLine()) != null)
taskListView, taskInputField, addButton, {
removeButton); loadedTasks.add(line);
}
} catch (IOException e) {
// File may not exist yet; it's okay
}
return loadedTasks;
}
private void saveTasksToFile() {
try (BufferedWriter writer = new
BufferedWriter(new FileWriter(FILE_PATH))) {
for (String task : tasks) {
writer.write(task);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}