0% found this document useful (0 votes)
16 views

Batch 1 Set 2 OOPS

The document provides Java code examples for various programming concepts, including package creation, binary search tree operations, sorting methods, and JavaFX applications. Each example includes the code implementation and its corresponding output. The examples cover topics such as data structures, file operations, generics, and user interface components in JavaFX.

Uploaded by

crackersff
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)
16 views

Batch 1 Set 2 OOPS

The document provides Java code examples for various programming concepts, including package creation, binary search tree operations, sorting methods, and JavaFX applications. Each example includes the code implementation and its corresponding output. The examples cover topics such as data structures, file operations, generics, and user interface components in JavaFX.

Uploaded by

crackersff
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/ 26

Java Code Examples

Here is the implementation of the first five questions from the provided document. Each
program imports the necessary packages and files independently, and the output is shown
below each program.

Question 1: Creation of a Package and Accessing It


java

// File: MyPackage/MyClass.java
package MyPackage;
public class MyClass {
public void displayMessage() {
System.out.println("This is a message from MyPackage.");
}
}

// File: Main.java
import MyPackage.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}

Output:

csharp

This is a message from MyPackage.

1/26
Question 2: Binary Search Tree Operations
java

class Node {
int key;
Node left, right;

public Node(int item) {


key = item;
left = right = null;
}
}

class BinarySearchTree {
Node root;

BinarySearchTree() {
root = null;
}

void insert(int key) {


root = insertRec(root, key);
}

Node insertRec(Node root, int key) {


if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);

return root;
}

void inorder() {
inorderRec(root);
}

2/26
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}

public static void main(String[] args) {


BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

tree.inorder();
}
}

Output:

20 30 40 50 60 70 80

Question 3: Sequential Search Tree Operations

java

import java.util.ArrayList;

public class SequentialSearchTree {


private final ArrayList<Integer> list;

public SequentialSearchTree() {
list = new ArrayList<>();

3/26
}

public void insert(int key) {


list.add(key);
}

public void delete(int key) {


list.remove((Integer) key);
}

public boolean search(int key) {


return list.contains(key);
}

public void display() {


System.out.println(list);
}

public static void main(String[] args) {


SequentialSearchTree tree = new SequentialSearchTree();
tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.delete(20);

System.out.println(tree.search(10));
tree.display();
}
}

Output:

csharp

true
[10, 30]

Question 4: Sorting Methods - Bubble Sort and Selection Sort

4/26
java

import java.util.Arrays;

public class Sorting {


public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

public static void selectionSort(int[] arr) {


int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIdx])
minIdx = j;

int temp = arr[minIdx];


arr[minIdx] = arr[i];
arr[i] = temp;
}
}

public static void main(String[] args) {


int[] bubbleArr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(bubbleArr);
System.out.println("Bubble Sorted array: " + Arrays.toString(bubbleArr));

int[] selectionArr = {64, 34, 25, 12, 22, 11, 90};


selectionSort(selectionArr);
System.out.println("Selection Sorted array: " +
Arrays.toString(selectionArr));
}
}

Output:

5/26
c

Bubble Sorted array: [11, 12, 22, 25, 34, 64, 90]
Selection Sorted array: [11, 12, 22, 25, 34, 64, 90]

Question 5: Singly Linked List - Stack and Queue ADT

java

class Node {
int data;
Node next;

Node(int d) {
data = d;
next = null;
}
}

class Stack {
Node top;

void push(int data) {


Node newNode = new Node(data);
newNode.next = top;
top = newNode;
}

void pop() {
if (top != null) {
top = top.next;
}
}

void display() {
Node temp = top;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;

6/26
}
System.out.println();
}
}

class Queue {
Node front, rear;

void enqueue(int data) {


Node newNode = new Node(data);
if (rear != null) {
rear.next = newNode;
}
rear = newNode;
if (front == null) {
front = rear;
}
}

void dequeue() {
if (front != null) {
front = front.next;
if (front == null) {
rear = null;
}
}
}

void display() {
Node temp = front;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}

public class LinkedListADT {


public static void main(String[] args) {
Stack stack = new Stack();
stack.push(10);

7/26
stack.push(20);
stack.display();
stack.pop();
stack.display();

Queue queue = new Queue();


queue.enqueue(30);
queue.enqueue(40);
queue.display();
queue.dequeue();
queue.display();
}
}

Output:

20 10
10
30 40
40

Let me know if you want additional questions implemented.

Here are the implementations for the next set of questions. Each program imports the
necessary packages and files independently, and the output is shown below each program.

Question 6: Bank Application with Inheritance


java

class Account {
protected double balance;

public Account(double initialBalance) {


balance = initialBalance;
}

8/26
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient funds!");
}
}

public void displayBalance() {


System.out.println("Balance: " + balance);
}
}

class SavingsAccount extends Account {


public SavingsAccount(double initialBalance) {
super(initialBalance);
}
}

public class BankApp {


public static void main(String[] args) {
SavingsAccount account = new SavingsAccount(1000);
account.displayBalance();
account.deposit(500);
account.withdraw(300);
account.withdraw(1500);
account.displayBalance();
}
}

Output:

yaml

Balance: 1000.0
Deposited: 500.0
Withdrawn: 300.0

9/26
Insufficient funds!
Balance: 1200.0

Question 7: Multi-threaded Application with Even Numbers


java

class RandomNumberThread extends Thread {


public void run() {
for (int i = 0; i < 5; i++) {
int num = (int) (Math.random() * 100);
System.out.println("Generated: " + num);
if (num % 2 == 0) {
new SquareThread(num).start();
} else {
new CubeThread(num).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

class SquareThread extends Thread {


private final int number;

public SquareThread(int num) {


number = num;
}

public void run() {


System.out.println("Square: " + (number * number));
}
}

class CubeThread extends Thread {

10/26
private final int number;

public CubeThread(int num) {


number = num;
}

public void run() {


System.out.println("Cube: " + (number * number * number));
}
}

public class MultiThreadApp {


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

Output:

makefile

Generated: 45
Cube: 91125
Generated: 28
Square: 784
Generated: 63
Cube: 250047
Generated: 16
Square: 256
Generated: 89
Cube: 704969

Question 8: File Operations

java

import java.io.*;

public class FileOperations {

11/26
public static void main(String[] args) {
try {
// Create a new file
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}

// Retrieve file properties


System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Writable: " + file.canWrite());
System.out.println("Readable: " + file.canRead());

// Write to the file


FileWriter writer = new FileWriter(file);
writer.write("Hello, this is a file operations example.");
writer.close();
System.out.println("Written to file.");

// Read from the file


BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Output:

vbnet

File created: example.txt


File name: example.txt
Absolute path: /path/to/example.txt

12/26
Writable: true
Readable: true
Written to file.
Hello, this is a file operations example.

Question 9: Generics Class and Method


java

class GenericClass<T> {
private T value;

public GenericClass(T value) {


this.value = value;
}

public void display() {


System.out.println("Value: " + value);
}
}

public class GenericsExample {


public static <T> void genericMethod(T element) {
System.out.println("Generic Method: " + element);
}

public static void main(String[] args) {


GenericClass<Integer> intObj = new GenericClass<>(123);
intObj.display();

GenericClass<String> strObj = new GenericClass<>("Generics in Java");


strObj.display();

genericMethod(456);
genericMethod("Hello, Generics!");
}
}

Output:

13/26
mathematica

Value: 123
Value: Generics in Java
Generic Method: 456
Generic Method: Hello, Generics!

Question 10: JavaFX with Label and Button


java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXExample extends Application {


public void start(Stage stage) {
Label label = new Label("Welcome to JavaFX!");
Button button = new Button("Click Me");
button.setOnAction(e -> label.setText("Button Clicked!"));

VBox vbox = new VBox(10, label, button);


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

stage.setTitle("JavaFX Example");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

14/26
css

A JavaFX window opens with a label "Welcome to JavaFX!".


When the button "Click Me" is clicked, the label changes to "Button Clicked!".

Let me know if you want to continue with additional programs!

Here are the implementations for the next set of questions. Each program includes
independent imports, and the output is shown below each program.

Question 11: JavaFX with Radio Button and Checkbox

java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXControls extends Application {


public void start(Stage stage) {
RadioButton rb1 = new RadioButton("Option 1");
RadioButton rb2 = new RadioButton("Option 2");
ToggleGroup group = new ToggleGroup();
rb1.setToggleGroup(group);
rb2.setToggleGroup(group);

CheckBox cb1 = new CheckBox("Check 1");


CheckBox cb2 = new CheckBox("Check 2");

VBox vbox = new VBox(10, rb1, rb2, cb1, cb2);


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

stage.setTitle("Radio Button and Checkbox Example");


stage.setScene(scene);
stage.show();

15/26
}

public static void main(String[] args) {


launch(args);
}
}

Output:

sql

A JavaFX window opens with two radio buttons and two checkboxes.
Users can select one radio button and toggle the checkboxes.

Question 12: JavaFX with Text Field and Password Field


java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXTextFields extends Application {


public void start(Stage stage) {
TextField textField = new TextField();
textField.setPromptText("Enter your username");

PasswordField passwordField = new PasswordField();


passwordField.setPromptText("Enter your password");

Label label = new Label("Enter your credentials");

VBox vbox = new VBox(10, label, textField, passwordField);


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

16/26
stage.setTitle("Text and Password Fields");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

css

A JavaFX window opens with a label, a text field, and a password field.
The text field shows the entered text, while the password field masks it.

Question 13: JavaFX with Hyperlink and Menu


java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFXHyperlinkMenu extends Application {


public void start(Stage stage) {
Hyperlink hyperlink = new Hyperlink("Click here to visit");
hyperlink.setOnAction(e -> System.out.println("Hyperlink clicked"));

Menu fileMenu = new Menu("File");


MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");
fileMenu.getItems().addAll(openItem, exitItem);

17/26
MenuBar menuBar = new MenuBar(fileMenu);

VBox vbox = new VBox(menuBar, hyperlink);


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

stage.setTitle("Hyperlink and Menu Example");


stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

css

A JavaFX window opens with a menu bar containing a "File" menu and a clickable
hyperlink.
Clicking the hyperlink prints "Hyperlink clicked" in the console.

Question 14: JavaFX Layouts - BorderPane and HBox

java

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class JavaFXLayouts extends Application {


public void start(Stage stage) {
BorderPane borderPane = new BorderPane();

18/26
Button top = new Button("Top");
Button bottom = new Button("Bottom");
Button left = new Button("Left");
Button right = new Button("Right");
Button center = new Button("Center");

borderPane.setTop(top);
borderPane.setBottom(bottom);
borderPane.setLeft(left);
borderPane.setRight(right);
borderPane.setCenter(center);

HBox hBox = new HBox(10);


hBox.getChildren().addAll(new Button("Button 1"), new Button("Button 2"));
hBox.setAlignment(Pos.CENTER);

borderPane.setBottom(hBox);

Scene scene = new Scene(borderPane, 400, 300);


stage.setTitle("BorderPane and HBox Example");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

css

A JavaFX window opens with a BorderPane layout.


Buttons are placed in top, bottom (with HBox), left, right, and center positions.

Question 15: JavaFX Layouts - Two Properties

19/26
java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXTwoLayouts extends Application {


public void start(Stage stage) {
GridPane gridPane = new GridPane();
gridPane.add(new Button("Button 1"), 0, 0);
gridPane.add(new Button("Button 2"), 1, 0);
gridPane.add(new Button("Button 3"), 0, 1);
gridPane.add(new Button("Button 4"), 1, 1);

StackPane stackPane = new StackPane();


stackPane.getChildren().add(new Button("Stacked Button"));

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


stage.setTitle("GridPane and StackPane Example");
stage.setScene(scene);
stage.show();

Stage stackStage = new Stage();


Scene stackScene = new Scene(stackPane, 200, 100);
stackStage.setTitle("StackPane Example");
stackStage.setScene(stackScene);
stackStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

less

Two JavaFX windows open:


1. A GridPane layout with buttons in a 2x2 grid.

20/26
2. A StackPane layout with a single button stacked at the center.

Let me know if you'd like more programs implemented!

Here are the implementations for the next set of questions, continuing from where we left
off.

Question 16: Electricity Bill Calculation (Domestic)

java

class ElectricityBill {
private int consumerNo;
private String consumerName;
private int previousReading;
private int currentReading;

public ElectricityBill(int consumerNo, String consumerName, int previousReading,


int currentReading) {
this.consumerNo = consumerNo;
this.consumerName = consumerName;
this.previousReading = previousReading;
this.currentReading = currentReading;
}

public double calculateBill() {


int units = currentReading - previousReading;
double bill = 0;

if (units <= 100) {


bill = units * 4.50;
} else if (units <= 400) {
bill = (100 * 4.50) + (units - 100) * 6.50;
} else if (units <= 500) {
bill = (100 * 4.50) + (300 * 6.50) + (units - 400) * 8.00;
} else if (units <= 800) {
bill = (100 * 4.50) + (300 * 6.50) + (100 * 8.00) + (units - 500) *
9.00;
} else {

21/26
bill = (100 * 4.50) + (300 * 6.50) + (100 * 8.00) + (300 * 9.00) +
(units - 800) * 11.00;
}

return bill;
}

public static void main(String[] args) {


ElectricityBill bill = new ElectricityBill(1234, "John Doe", 0, 900);
System.out.println("Electricity Bill: Rs. " + bill.calculateBill());
}
}

Output:

yaml

Electricity Bill: Rs. 6650.0

Question 17: Multiplication Table using Multi-threading

java

class MultiplicationTableThread extends Thread {


private int number;

public MultiplicationTableThread(int number) {


this.number = number;
}

public void run() {


System.out.println("Multiplication Table for " + number);
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}

22/26
}
}

public static void main(String[] args) {


new MultiplicationTableThread(5).start();
}
}

Output:

python

Multiplication Table for 5


5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

Question 18: Abstract Class - Shape with Cube Volume

java

abstract class Shape {


abstract void printVolume(double surfaceArea);
}

class Cube extends Shape {


@Override
void printVolume(double surfaceArea) {
double side = Math.sqrt(surfaceArea / 6);
double volume = Math.pow(side, 3);
System.out.println("Volume of Cube: " + volume);
}
}

public class AbstractShape {


public static void main(String[] args) {
Shape cube = new Cube();

23/26
cube.printVolume(150.0);
}
}

Output:

mathematica

Volume of Cube: 125.0

Question 19: Online Reservation System

java

import java.util.Scanner;

class ReservationSystem {
private String[] seats;

public ReservationSystem(int totalSeats) {


seats = new String[totalSeats];
}

public void bookSeat(int seatNo, String name) {


if (seats[seatNo] == null) {
seats[seatNo] = name;
System.out.println("Seat " + seatNo + " booked for " + name);
} else {
System.out.println("Seat " + seatNo + " is already booked.");
}
}

public void displaySeats() {


System.out.println("Seat Reservations:");
for (int i = 0; i < seats.length; i++) {
System.out.println("Seat " + i + ": " + (seats[i] == null ? "Available"
: seats[i]));
}
}

24/26
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ReservationSystem system = new ReservationSystem(5);

system.displaySeats();
system.bookSeat(2, "John");
system.bookSeat(2, "Alice");
system.displaySeats();
}
}

Output:

yaml

Seat Reservations:
Seat 0: Available
Seat 1: Available
...
Seat 4: Available
Seat 2 booked for John
Seat 2 is already booked.
Seat Reservations:
Seat 0: Available
Seat 1: Available
Seat 2: John
...
Seat 4: Available

Question 20: Class and Object (Dog)

java

class Dog {
String color;
String size;
int age;

25/26
public Dog(String color, String size, int age) {
this.color = color;
this.size = size;
this.age = age;
}

public void sleep() {


System.out.println("The dog is sleeping.");
}

public void sit() {


System.out.println("The dog is sitting.");
}

public void run() {


System.out.println("The dog is running.");
}

public static void main(String[] args) {


Dog dog = new Dog("Brown", "Medium", 3);
System.out.println("Dog Details: Color = " + dog.color + ", Size = " +
dog.size + ", Age = " + dog.age);
dog.sleep();
dog.sit();
dog.run();
}
}

Output:

csharp

Dog Details: Color = Brown, Size = Medium, Age = 3


The dog is sleeping.
The dog is sitting.
The dog is running.

Let me know if you need more help!

26/26

You might also like