Eroju Java Anadu Repu Bava Antadu
Eroju Java Anadu Repu Bava Antadu
a. Try debug step by step with java program to find prime numbers between 1 to n.
public class PrimeNumbers {
public static void main(String[] args)
{ int n = 50;
System.out.println("Prime numbers between 1 and " + n + ":");
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.print(i + " ");}}}
private static boolean isPrime(int num) {
if (num < 2)
return false;
for (int i = 2; i <= Math.sqrt(num); i++)
{ if (num % i == 0)
return false;}
return true;}}
OUTPUT :
Prime numbers between 1 and 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 4
b. Write a Java program that prints all real solutions to the quadratic equation
ax2+bx+c. Read in a, b, c and use the quadratic formula.
import java.util.Scanner;
public class QE {
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter coefficient a: ");
double a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
double b = scanner.nextDouble();
System.out.print("Enter coefficient c: ");
double c = scanner.nextDouble();
double discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("Real solutions:");
1
System.out.println("Root 1: " + root1);
System.out.println("Root 2: " + root2);
} else {
System.out.println("The quadratic equation has no real solutions."); }
scanner.close();}}
OUTPUT :
Enter coefficient a: 1
Enter coefficient b: 5
Enter coefficient c: 6
Real solutions:
Root 1: -2.0
Root 2: -3.0
c. Write a Java program to multiply two given matrices.
public class Matrix{
public static void main(String args[])
{ int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){ c[i]
[j]=0;
for(int k=0;k<3;k++)
c[i][j]+=a[i][k]*b[k][j];
System.out.print(c[i][j]+" "); }
System.out.println(); }}}
OUTPUT :
6 6 6
12 12 12
WEEK-2:
a. Write Java program on use of inheritance, preventing inheritance using final,
abstract classes.
class Animal {
String name;
Animal(String name)
{ this.name = name; }
void eat() {
2
System.out.println(name + " is eating.");}}
class Dog extends Animal {
Dog(String name)
{ super(name); }
void bark() {
System.out.println(name + " is barking.");}}
final class Fish {
String name;
Fish(String name)
{ this.name = name;}
void swim() {
System.out.println(name + " is swimming.");}}
abstract class Bird {
String name;
Bird(String name)
{ this.name = name;}
abstract void fly();}
class Sparrow extends Bird
{ Sparrow(String name) {
super(name);}
void fly() {
System.out.println(name + " is flying.");}}
public class InheritanceDemo {
public static void main(String[] args)
{ Dog myDog = new Dog("Buddy");
myDog.eat();
myDog.bark();
Fish myFish = new Fish("Nemo");
myFish.swim();
Sparrow mySparrow = new Sparrow("Tweetie");
mySparrow.fly();
}}
OUTPUT :
Buddy is eating.
Buddy is barking.
Nemo is swimming.
3
Tweetie is flying.
b. Write Java program on dynamic binding, differentiating method overloading and
overriding.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");}}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");}
void fetch() {
System.out.println("Dog is fetching");}
void fetch(String name){
System.out.println("Dog is fetching "+name);}}
public class PolymorphismDemo {
public static void main(String[] args)
{ Dog myDog = new Dog();
myDog.makeSound();
myDog.fetch();
myDog.fetch("frisbee");
Animal an = new Animal();
an.makeSound();}}
OUTPUT :
Dog barks
Dog is fetching
Dog is fetching frisbee
Animal makes a sound
c. Develop a java application to implement currency converter (Dollar to INR. EURO
to INR, Yen) using Interfaces
import java.util.Scanner;
interface CurrencyConverter {
double convertToINR(double amount);}
class DollarConverter implements CurrencyConverter
{ public double convertToINR(double amount) {
return amount * 75;}}
class EuroConverter implements CurrencyConverter {
4
public double convertToINR(double amount)
{ return amount * 85;}}
class YenConverter implements CurrencyConverter {
public double convertToINR(double amount)
{ return amount * 0.70}}
public class CurrencyConverterApp {
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.println("Select currency to convert to INR:");
System.out.println("1. Dollar (USD)");
System.out.println("2. Euro (EUR)");
System.out.println("3. Yen (JPY)");
int choice = scanner.nextInt();
System.out.print("Enter the amount: ");
double amount = scanner.nextDouble();
CurrencyConverter converter = null;
switch (choice) {
case 1:converter = new DollarConverter();break;
case 2:converter = new EuroConverter();break;
case 3:converter = new YenConverter();break;
default:System.out.println("Invalid choice");
System.exit(0);}
double inrAmount = converter.convertToINR(amount);
System.out.println("Converted amount to INR: " + inrAmount);
scanner.close();}}
OUTPUT :
Select currency to convert to INR:
1. Dollar (USD)
2. Euro (EUR)
3. Yen (JPY)
1
Enter the amount: 123
Converted amount to INR: 9225.0
5
WEEK-3 :
a. Write a Java program to create a package named "com.mycompany.math" that contains
a class named "Calculator" with methods to add, subtract, multiply and divide two
numbers. Write a test program to use this package.
package com.mycompany.math;
public class Calculator {
public static int add(int a, int b)
{ return a + b;}
public static int subtract(int a, int b)
{ return a - b;}
public static int multiply(int a, int b)
{ return a * b; }
public static double divide(int a, int b)
{ return a/b;}}
import com.mycompany.math.Calculator;
public class TestCalculator {
public static void main(String[] args)
{ int num1 = 10;
int num2 = 5;
System.out.println("Addition: " + Calculator.add(num1, num2));
System.out.println("Subtraction: " + Calculator.subtract(num1, num2));
System.out.println("Multiplication: " + Calculator.multiply(num1, num2));
System.out.println("Division: " + Calculator.divide(num1, num2));
}}
b. Create a package named "com.mycompany.util" that contains a class named
"StringUtils" with a method named "reverseString" that takes a string as input
and returns the reverse of the input string. Write a test program to use this
package. package com.mycompany.util;
public class StringUtils {
public static String reverseString(String input) {
if (input == null) {
throw new IllegalArgumentException("Input string cannot be
null");} StringBuilder reversed = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
reversed.append(input.charAt(i));}
return reversed.toString();
6
}}
import com.mycompany.util.StringUtils;
public class TestStringUtils {
public static void main(String[] args) {
String originalString = "Hello, World!";
System.out.println("Original String: " + originalString);
String reversedString = StringUtils.reverseString(originalString);
System.out.println("Reversed String: " + reversedString);
}}
WEEK-4 :
a. Write a Java program to implement user defined exception handling.
class NegativeNumberException extends Exception {
public NegativeNumberException(String message) {
super(message);}}
class Calculator {
public static int square(int number) throws NegativeNumberException
{ if (number < 0) {
throw new NegativeNumberException("Negative numbers are not allowed");}
return number * number;}}
public class ExceptionHandlingDemo {
public static void main(String[] args)
{ Calculator calculator = new
Calculator(); try {
int result1 = calculator.square(-5);
System.out.println("Square of 5: " + result1);
} catch (NegativeNumberException e) {
System.out.println("Exception caught: " + e.getMessage());}}}
OUTPUT:
Exception caught: Negative numbers are not allowed
b. Write a Java program to throw an exception “Insufficient Funds” while withdrawing
the amount in the user account.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);}}
class BankAccount {
private double balance;
7
public BankAccount(double initialBalance)
{ this.balance = initialBalance; }
public void withdraw(double amount) throws InsufficientFundsException
{ if (amount > balance) {
throw new InsufficientFundsException("Insufficient Funds: Cannot withdraw "
+ amount + ", available balance is " + balance); }
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}}
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
try {
account.withdraw(1200);
} catch (InsufficientFundsException e) {
System.out.println("Exception caught: " + e.getMessage());
}}}
OUTPUT :
Exception caught: Insufficient Funds: Cannot withdraw 1200.0, available balance is
1000.0
c. Write a Java program to implement Try-with Resources, Multi-catch Exceptions, and
Exception Propagation Concepts?
public class ExceptionHandling{
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30;
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e) {
System.out.println("Parent Exception occurs"); }
}}
8
WEEK-5:
a. Write a java program to split a given text file into n parts. Name each part as
the
name of the original file followed by .part where n is the sequence number of the
part file.
import java.io.*;
import java.util.Scanner;
public class Split {
public static void main(String args[]) {
try{
String inputfile = "test.txt";
double nol = 5.0;
9
fw.close(); }
br.close(); }
catch (Exception e) {
System.err.println("Error: " + e.getMessage()); }
} }
import java.io.File;
import java.util.Scanner;
class FileP{
public static void main(String args[ ])
{ Scanner obj=new Scanner(System.in);
String fname=obj.next();
File f1 = new File(fname);
System.out.println("File Name: " + f1.getName());
f1.setWritable(false);
System.out.println(f1.exists() ? "File exists" : "File does not exist");
System.out.println(f1.canWrite() ? "File is writeable" : "File is not writeable");
System.out.println(f1.canRead() ? "File is readable" : "File is not readable");
String fileName = f1.toString();
int index = fileName.lastIndexOf('.');
if(index > 0){
String type = fileName.substring(index + 1);
System.out.println("File type is " + type);}
else
System.out.println("File doesn't have type");
System.out.println("File size: " + f1.length() + " Bytes");
}}
OUTPUT :
Lines in the file: 26
No. of files to be generated :6
b. Write a Java program that reads a file name from the user, displays information
about whether the File exists, whether the file is readable, or writable. The type of
File and the length of the file in bytes.
import java.io.File;
import java.util.Scanner;
public class FileInfoDemo {
public static void main(String[] args) {
10
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
if (file.exists()) {
System.out.println("File exists.");
if (file.isFile()) {
System.out.println("File type: Regular file.");
if (file.canRead()) {
System.out.println("File is readable.");
} else {
System.out.println("File is not readable.");}
if (file.canWrite()) {
System.out.println("File is writable.");
} else {
System.out.println("File is not writable.");}
System.out.println("File length: " + file.length() + " bytes.");
} else {
System.out.println("File type: Directory.");}
} else {
System.out.println("File does not exist.");}
scanner.close();
}}
OUTPUT:
Enter the file name: File1.txt
File exists.
File type: Regular file.
File is readable.
File is writable.
File length: 150 bytes.
WEEK-6:
a. Write a Java program on Random Access File class to perform different read and
write operations.
import java.io.*;
public class RAFDemo {
public static void main(String[] args) {
11
String fileName = "random_access_file_example.txt";
writeDataToFile(fileName);
readDataFromFile(fileName); }
private static void writeDataToFile(String fileName) {
try (RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw"))
{ randomAccessFile.writeUTF("Hello, RandomAccessFile!");
randomAccessFile.writeInt(42);
randomAccessFile.writeDouble(3.14);
System.out.println("Data written to the file successfully.");
} catch (IOException e) {
e.printStackTrace();}}
private static void readDataFromFile(String fileName) {
try (RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "r")) {
randomAccessFile.seek(0);
String message = randomAccessFile.readUTF();
int intValue = randomAccessFile.readInt();
double doubleValue = randomAccessFile.readDouble();
System.out.println("Data read from the file:");
System.out.println("Message: " + message);
System.out.println("Integer Value: " + intValue);
System.out.println("Double Value: " + doubleValue);
} catch (IOException e) {
e.printStackTrace();}
}}
OUTPUT :
Data written to the file successfully.
Data read from the file:
Message: Hello, RandomAccessFile!
Integer Value: 42
Double Value: 3.14
b. Create a class called Employee with properties name(String), dateofbirth
(java.util.Date), department(String), designation(String) and Salary(double).Create
respective getter and setter methods and constructors (no-argument constructor and
parameterized constructor) for the same. Create an object of the Employee class and
save this object in a file called “data” using serialization. Later using
deserialization read this object and prints the properties of this object.
import java.io.*;
import java.util.Date;
12
class Employee implements Serializable
{ private String name;
private Date dateOfBirth;
private String department;
private String designation;
private double salary;
public Employee() { }
public Employee(String name, Date dateOfBirth, String department, String
designation, double salary) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.department = department;
this.designation = designation;
this.salary = salary; }
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
public Date getDateOfBirth()
{ return dateOfBirth;}
public void setDateOfBirth(Date dateOfBirth)
{ this.dateOfBirth = dateOfBirth; }
public String getDepartment()
{ return department; }
public void setDepartment(String department)
{ this.department = department; }
public String getDesignation()
{ return designation; }
public void setDesignation(String designation)
{ this.designation = designation; }
public double getSalary()
{ return salary; }
public void setSalary(double salary)
{ this.salary = salary; }
public String toString() {
13
return "Employee [name=" + name + ", dateOfBirth="+dateOfBirth+"department="
+ department + ", designation=" + designation + ", salary=" + salary + "]"; }}
public class Serial {
public static void main(String[] args) {
Employee employee = new Employee("John Doe", new Date(), "IT", "Software
Engineer", 75000.00);
serializeEmployee(employee);
Employee deserializedEmployee = deserializeEmployee();
if (deserializedEmployee != null) {
System.out.println("Deserialized Employee Details:");
System.out.println(deserializedEmployee); } }
private static void serializeEmployee(Employee employee) {
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("data.ser"))) {
oos.writeObject(employee);
System.out.println("Employee object has been serialized and saved to
'data' file.");
} catch (IOException e) {
e.printStackTrace();}}
private static Employee deserializeEmployee()
{ Employee employee = null;
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("data.ser"))) {
employee = (Employee) ois.readObject();
System.out.println("Employee object has been deserialized from 'data'
file.");
} catch (IOException | ClassNotFoundException e)
{ e.printStackTrace(); }
return employee; }}
OUTPUT:-
Employee object has been serialized and saved to 'data' file.
Employee object has been deserialized from 'data' file.
Deserialized Employee Details:
Employee [name=John Doe, dateOfBirth=Tue Dec 26 14:10:28 IST 2023, department=IT,
designation=Software Engineer, salary=75000.0]
14
WEEK–7:
a. Create a generic class called Box that can hold any type of object. Implement the
following methods: 1) void set(T obj): sets the object stored in the box 2) T
get(): retrieves the object stored in the box 3) boolean isEmpty(): returns true if
the box is empty, false otherwise
public class Box<T>
{ private T
content;
public void set(T obj)
{ content = obj;}
public T get()
{ return content;}
public boolean isEmpty()
{ return content == null;}
public static void main(String[] args)
{ Box<Integer> integerBox = new Box<>();
integerBox.set(42);
System.out.println("Box contains: " + integerBox.get());
System.out.println("Is the box empty? " + integerBox.isEmpty());
Box<String> stringBox = new Box<>();
stringBox.set("Hello, Generics!");
System.out.println("Box contains: " + stringBox.get());
System.out.println("Is the box empty? " + stringBox.isEmpty());
}}
OUTPUT :
Box contains: 42
Is the box empty? false
Box contains: Hello, Generics!
Is the box empty? False
b. Implement a generic Stack class that can hold any type of object. Implement the
following methods: 1) void push(T obj): pushes an object onto the top of the stack,2)
T pop(): removes and returns the object at the top of the stack 3) booleanisEmpty():
returns true if the stack is empty, false otherwise.
import java.util.ArrayList;
import java.util.List;
public class Stacks<T> {
private List<T> elements;
public Stacks() {
this.elements = new ArrayList<>();}
15
public void push(T obj) {
elements.add(obj); }
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty"); }
return elements.remove(elements.size() - 1);}
public boolean isEmpty() {
return elements.isEmpty(); }
public static void main(String[] args) {
Stacks<Integer> integerStack = new Stacks<>();
integerStack.push(1);
integerStack.push(2);
integerStack.push(3);
System.out.println("Popped: " + integerStack.pop());
System.out.println("Popped: " + integerStack.pop());
System.out.println("Is the stack empty? " + integerStack.isEmpty());
Stacks<String> stringStack = new Stacks<>();
stringStack.push("One");
stringStack.push("Two");
stringStack.push("Three");
System.out.println("Popped: " + stringStack.pop());
System.out.println("Popped: " + stringStack.pop());
System.out.println("Is the stack empty? " + stringStack.isEmpty());
}}
OUTPUT :
Popped: 3
Popped: 2
Is the stack empty? false
Popped: Three
Popped: Two
Is the stack empty? False
16
WEEK 8:
a. Write a Java program to implement Autoboxing and Unboxing?
public class AutoboxingUnboxingExample {
public static void main(String[] args) {
Integer integerValue = 1
int intValue = integerValue
System.out.println("Original primitive value: " + intValue);
System.out.println("Autoboxed value: " + integerValue);
}
}
Original primitive value: 10
Autoboxed value: 10
b. Write a Java program to implement Built-In Java Annotations?
import java.lang.annotation.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "Default Value";
public class AnnotationExample {
@MyAnnotation(value = "Custom Value")
public void myAnnotatedMethod() {
System.out.println("Executing annotated method");
}
public static void main(String[] args) throws NoSuchMethodException
{ AnnotationExample example = new AnnotationExample();
example.myAnnotatedMethod();
MyAnnotation annotation = AnnotationExample.class
.getMethod("myAnnotatedMethod")
.getAnnotation(MyAnnotation.class);
System.out.println("Annotation Value: " + annotation.value());
}
}
17
WEEK 9:
a. Write a Java program that creates three threads. First thread displays —Good
Morning every one second, the second thread displays —Hello every two seconds
and the third thread displays —Welcome every three seconds.
public class GreetingThreads {
public static void main(String[] args) {
Runnable ob1 = new GreetingRunner("Good Morning", 1000);
Runnable ob2 = new GreetingRunner("Hello", 2000);
Runnable ob3 = new GreetingRunner("Welcome", 3000);
Thread morningThread = new Thread(ob1);
Thread helloThread = new Thread(ob2);
Thread welcomeThread = new Thread(ob3);
morningThread.start();
helloThread.start();
welcomeThread.start();}}
class GreetingRunner implements Runnable
{ private final String message;
private final int interval;
public GreetingRunner(String message, int interval)
{ this.message = message;
this.interval = interval;
run(); }
@Override
public void run()
{ int c = 1;
while (c<=5) {
System.out.println(message + “ ”);
c++;
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
} } }}
OUTPUT:-
18
Good Morning Good Morning Good Morning Good Morning Good Morning Hello Hello Hello
Hello Hello Welcome Welcome Welcome Welcome Welcome Good Morning Welcome Hello Good
Morning Good Morning Hello Welcome Good Morning Hello Good Morning Welcome Hello
Hello Welcome Welcome
b. Write a Java program that correctly implements producer consumer problem
using the concept of inter thread communication.
public class PCT {
public static void main(String[] args)
{ SharedBuffer buffer = new
SharedBuffer();
Thread producerThread = new Thread(new Producer(buffer));
Thread consumerThread = new Thread(new Consumer(buffer));
producerThread.start();
consumerThread.start();
}}
class SharedBuffer {
private int contents;
private boolean available = false;
public synchronized int get() {
while (!available)
{ try {
wait();
} catch (InterruptedException e) { }
}
available = false;
notifyAll();
return contents;}
public synchronized void put(int value) {
while (available) {
try {
wait();
} catch (InterruptedException e) { }}
contents = value;
available = true;
notifyAll();
}}
class Producer implements Runnable {
private final SharedBuffer buffer;
19
public Producer(SharedBuffer buffer)
{ this.buffer = buffer; }
@Override
public void run() {
for (int i = 0; i < 10; i++) {
buffer.put(i);
System.out.print("Producer put: " + i + " ");
try {
Thread.sleep((int) (1000));
} catch (InterruptedException e) { }} }}
class Consumer implements Runnable {
private final SharedBuffer buffer;
public Consumer(SharedBuffer buffer)
{ this.buffer = buffer; }
@Override
public void run() {
for (int i = 0; i < 10; i++)
{ int value =
buffer.get();
System.out.print("Consumer got: " + value + " ");
try {
Thread.sleep((int) (1000));
} catch (InterruptedException e) { }}}}
OUTPUT:-
Producer put: 0 Consumer got: 0 Producer put: 1 Consumer got: 1 Consumer got: 2
Producer put: 2 Producer put: 3 Consumer got: 3 Producer put: 4 Consumer got: 4
Producer put: 5 Consumer got: 5 Producer put: 6 Consumer got: 6 Producer put: 7
Consumer got: 7 Producer put: 8 Consumer got: 8 Consumer got: 9 Producer put: 9
c. Create a Email registration Form using Java AWT. The UI should have fields such as
name, address, sex, age, email, contact number, etc.,
import java.awt.*;
import java.awt.event.*;
public class ERF extends Frame {
Label nameLabel, addressLabel, sexLabel, ageLabel, emailLabel, contactLabel;
TextField nameText, addressText, ageText, emailText, contactText;
CheckboxGroup sexGroup;
Checkbox maleCheckbox, femaleCheckbox, otherCheckbox;
Button submitButton;
20
public ERF() {
nameLabel = new Label("Name:");
addressLabel = new Label("Address:");
sexLabel = new Label("Sex:");
ageLabel = new Label("Age:");
emailLabel = new Label("Email:");
contactLabel = new Label("Contact Number:");
nameText = new TextField(20);
addressText = new TextField(20);
ageText = new TextField(20);
emailText = new TextField(20);
contactText = new TextField(20);
sexGroup = new CheckboxGroup();
maleCheckbox = new Checkbox("Male", sexGroup, false);
femaleCheckbox = new Checkbox("Female", sexGroup, false);
otherCheckbox = new Checkbox("Other", sexGroup, false);
submitButton = new Button("Submit");
setLayout(new FlowLayout());
add(nameLabel);
add(nameText);
add(addressLabel);
add(addressText);
add(sexLabel);
add(maleCheckbox);
add(femaleCheckbox);
add(otherCheckbox);
add(ageLabel);
add(ageText);
add(emailLabel);
add(emailText);
add(contactLabel);
add(contactText);
add(submitButton);
setTitle("Email Registration Form");
setSize(250, 400);
setVisible(true);
21
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}});
}
public static void main(String[] args)
{ new ERF();
}}
OUTPUT:-
d. Demonstrate various Layout Managers in Java AWT. Display the output in card
layout wheareas each card exhibits different layout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LayoutDemo extends JFrame implements ActionListener {
private CardLayout cardLayout;
private JPanel cardPanel;
public LayoutDemo() {
setTitle("Layout Manager Demonstration");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardLayout = new CardLayout();
22
cardPanel = new JPanel(cardLayout);
cardPanel.add(createFlowLayoutPanel(), "FlowLayout");
cardPanel.add(createBorderLayoutPanel(), "BorderLayout");
cardPanel.add(createGridLayoutPanel(), "GridLayout");
cardPanel.add(createBoxLayoutPanel(), "BoxLayout");
JPanel controlPanel = new JPanel();
String[] layouts = {"FlowLayout", "BorderLayout", "GridLayout", "BoxLayout"};
for (String layout : layouts) {
JButton button = new JButton(layout);
button.addActionListener(this);
controlPanel.add(button); }
add(cardPanel, BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);
setVisible(true); }
private JPanel createFlowLayoutPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
return panel; }
private JPanel createBorderLayoutPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JButton("North"), BorderLayout.NORTH);
panel.add(new JButton("South"), BorderLayout.SOUTH);
panel.add(new JButton("East"), BorderLayout.EAST);
panel.add(new JButton("West"), BorderLayout.WEST);
panel.add(new JButton("Center"), BorderLayout.CENTER);
return panel; }
private JPanel createGridLayoutPanel() {
23
JPanel panel = new JPanel(new GridLayout(3, 2));
for (int i = 1; i <= 6; i++) {
panel.add(new JButton("Button " + i)); }
return panel; }
private JPanel createBoxLayoutPanel()
{ JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
return panel; }
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, e.getActionCommand());}
public static void main(String[] args) {
new LayoutDemo(); }}
OUTPUT:-
24
WEEK 10:
a. Write a Java program to create a Vector and add some elements to it. Then get
the element at a specific index and print it.
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Element 1");
vector.add("Element 2");
vector.add("Element 3");
int indexToRetrieve = 1;
if (indexToRetrieve >= 0 && indexToRetrieve < vector.size())
{ String elementAtIndex = vector.get(indexToRetrieve);
System.out.println("Element at index " + indexToRetrieve + ": " +
elementAtIndex);
} else {
System.out.println("Invalid index: " + indexToRetrieve);
}}}
Output:-
Element at index 1: Element 2
b. Write a Java program to create a BitSet and set some bits in it. Then perform some
bitwise operations on the BitSet and print the result.
import java.util.BitSet;
25
public class BitSetDemo {
public static void main(String[] args) {
BitSet bitSet1 = new BitSet();
BitSet bitSet2 = new BitSet();
bitSet1.set(0);
bitSet1.set(2);
bitSet1.set(4);
bitSet2.set(1);
bitSet2.set(2);
bitSet2.set(3);
BitSet resultAND = new BitSet();
resultAND = (BitSet) bitSet1.clone(
resultAND.and(bitSet2);
System.out.println("Bitwise AND Result: " + resultAND);
BitSet resultOR = new BitSet();
resultOR = (BitSet) bitSet1.clone(
resultOR.or(bitSet2);
System.out.println("Bitwise OR Result: " + resultOR);
BitSet resultXOR = new BitSet();
resultXOR = (BitSet) bitSet1.clone(
resultXOR.xor(bitSet2);
System.out.println("Bitwise XOR Result: " + resultXOR);
}}
Output:-
Bitwise AND Result: {2}
Bitwise OR Result: {0, 1, 2, 3, 4}
Bitwise XOR Result: {0, 1, 3, 4}
c. Write a Java program to read the time intervals (HH:MM) and to compare system
time if the system Time between your time intervals print correct time and exit else
try again to repute the same thing. By using String Tokenizer class.
WEEK 11:
a. Write a Java program to demonstrate the working of different collection classes.
[Use package structure to store multiple classes].
Code
26
package CollectionDemoPackage;
public class CollectionDemoMain {
public static void main(String[] args) {
ArrayListDemo arrayListDemo = new ArrayListDemo();
arrayListDemo.demoArrayList();
HashSetDemo hashSetDemo = new HashSetDemo();
hashSetDemo.demoHashSet();
HashMapDemo hashMapDemo = new HashMapDemo();
hashMapDemo.demoHashMap();}
package CollectionDemoPackage;
import java.util.ArrayList;
public class ArrayListDemo {
public void demoArrayList() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Element 1");
arrayList.add("Element 2");
arrayList.add("Element 3");
System.out.println("ArrayList Elements: " + arrayList);
}
package CollectionDemoPackage;
import java.util.HashSet;
public class HashSetDemo {
public void demoHashSet() {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Item 1");
hashSet.add("Item 2");
hashSet.add("Item 3");
System.out.println("HashSet Elements: " + hashSet);
}
package CollectionDemoPackage;
import java.util.HashMap;
public class HashMapDemo {
public void demoHashMap() {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Value 1");
hashMap.put(2, "Value 2");
27
hashMap.put(3, "Value 3");
System.out.println("HashMap Elements: " + hashMap);
}}
Output:-
ArrayList Elements: [Element 1, Element 2, Element 3]
HashSet Elements: [Item 1, Item 2, Item 3]
HashMap Elements: {1=Value 1, 2=Value 2, 3=Value 3}
b. Write a Java program to create a TreeMap and add some elements to it. Then get the
value associated with a specific key and print it.
Code:
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Apple", 10);
treeMap.put("Banana", 5);
treeMap.put("Orange", 8);
treeMap.put("Grapes", 15);
ue associated with a specific key
String keyToSearch = "Banana";
Integer value = treeMap.get(keyToSearch);
if (value != null) {
System.out.println("The value associated with key '" + keyToSearch + "'
is: " + value);
} else {
System.out.println("Key '" + keyToSearch + "' not found in the
TreeMap.");
}}}
Output:-
The value associated with key 'Banana' is: 5
c. Write a Java program to create a PriorityQueue and add some elements to it. Then
remove the highest priority element from the PriorityQueue and print the remaining
elements.
Program:
import java.util.*;
class PriorityQueueDemo {
public static void main(String args[])
28
{
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();
pQueue.add(10);
pQueue.add(20);
pQeue.add(15);
System.out.println(pQueue.peek());
System.out.println(pQueue.poll());
System.out.println(pQueue.peek());
}}
Output:
10
10
15
WEEK 12:
a. Develop a Java application to establish a JDBC connection, create a table
student with properties name, register number, mark 1, mark2, mark3. Insert the
values into the table by using the java and display the information of the students
at the front end.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class StudentDatabaseApp {
private static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,
PASSWORD);
Statement statement = connection.createStatement();
29
createStudentTable(statement);
insertStudentData(connection);
displayStudentInformation(statement);
statement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}}
private static void createStudentTable(Statement statement) throws SQLException {
String createTableQuery = "CREATE TABLE IF NOT EXISTS student ("
+ "id INT AUTO_INCREMENT PRIMARY KEY,"
+ "name VARCHAR(50) NOT NULL,"
+ "register_number VARCHAR(20) NOT NULL,"
+ "mark1 INT,"
+ "mark2 INT,"
+ "mark3 INT"
+ ")";
statement.executeUpdate(createTableQuery);
}
private static void insertStudentData(Connection connection) throws SQLException
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter student details:");
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Register Number: ");
String registerNumber = scanner.nextLine();
System.out.print("Mark 1: ");
int mark1 = scanner.nextInt();
System.out.print("Mark 2: ");
int mark2 = scanner.nextInt();
System.out.print("Mark 3: ");
int mark3 = scanner.nextInt();
String insertQuery = "INSERT INTO student (name, register_number, mark1,
mark2, mark3) VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement preparedStatement =
connection.prepareStatement(insertQuery)) {
30
preparedStatement.setString(1, name);
preparedStatement.setString(2, registerNumber);
preparedStatement.setInt(3, mark1);
preparedStatement.setInt(4, mark2);
preparedStatement.setInt(5, mark3);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Student data inserted successfully!");
} else {
System.out.println("Failed to insert student data.");
}}}
private static void displayStudentInformation(Statement statement) throws
SQLException { String selectQuery = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(selectQuery);
System.out.println("\nStudent Information:");
System.out.println("ID\tName\tRegister Number\tMark 1\tMark 2\tMark 3");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String registerNumber = resultSet.getString("register_number");
int mark1 = resultSet.getInt("mark1");
int mark2 = resultSet.getInt("mark2");
int mark3 = resultSet.getInt("mark3");
System.out.println(id + "\t" + name + "\t" + registerNumber + "\t\t" + mark1 + "\t" +
mark2 + "\t" + mark3);
}}}
b. Write a program to perform CRUD operations on the student table in a database
using JDBC
31