PROGRAM :- 1
Write a program in java to print your details (Name, Rollno, Class,
Sem, Collage Name). And create the JAR file of this program with
both output i.e. .java and .Jar.
SOURCE CODE
Step 1: Write the Java Program
public class Ques on1 {
public sta c void main(String[] args) {
String name = " Sonu kumar";
int rollNo = 227013;
String className = "B.Tech CSE";
int sem = 5;
String collegeName = "St. Andrews Ins tute of Technology and Management";
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Class: " + className);
System.out.println("Semester: " + sem);
System.out.println("College Name: " + collegeName);
}
}
Outputs:
.java Output:
.jar Output:
PROGRAM :- 2
Create a java program to implement stack and queue concept.
SOURCE CODE
import java.u l.ArrayList;
import java.u l.Scanner;
// Stack Implementa on
class Stack<T> {
private ArrayList<T> arrayStack = new ArrayList<>();
// Push element onto stack
public void push(T value) {
arrayStack.add(value);
System.out.println("Pushed: " + value);
}
// Pop element from stack
public T pop() {
if (arrayStack.isEmpty()) {
System.out.println("Stack is empty!");
return null;
}
return arrayStack.remove(arrayStack.size() - 1);
}
// Peek at the top element
public T peek() {
if (arrayStack.isEmpty()) {
System.out.println("Stack is empty!");
return null;
}
return arrayStack.get(arrayStack.size() - 1);
}
// Check if stack is empty
public boolean isEmpty() {
return arrayStack.isEmpty();
}
// Print stack
public void printStack() {
System.out.println("Stack: " + arrayStack);
}
}
// Queue Implementa on
class Queue<T> {
private ArrayList<T> arrayQueue = new ArrayList<>();
// Enqueue element into queue
public void enqueue(T value) {
arrayQueue.add(value);
System.out.println("Enqueued: " + value);
}
// Dequeue element from queue
public T dequeue() {
if (arrayQueue.isEmpty()) {
System.out.println("Queue is empty!");
return null;
}
return arrayQueue.remove(0);
}
// Peek at the front element
public T peek() {
if (arrayQueue.isEmpty()) {
System.out.println("Queue is empty!");
return null;
}
return arrayQueue.get(0);
}
// Check if queue is empty
public boolean isEmpty() {
return arrayQueue.isEmpty();
}
// Print queue
public void printQueue() {
System.out.println("Queue: " + arrayQueue);
}
}
// Main class to test Stack and Queue
public class Ques on2 {
public sta c void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Choose 1 for Stack or 2 for Queue : ");
int n = sc.nextInt();
if (n == 1) {
// Stack Demo
Stack<Integer> stack = new Stack<>();
System.out.println(
"Enter \n" +
"1 for Push \n" +
"2 for Pop \n" +
"3 for Peek \n" +
"4 for Empty Check \n" +
"5 for Print Stack \n" +
"6 for exit");
int numSt;
do{
numSt = sc.nextInt();
switch (numSt) {
case 1: System.out.print("Enter a number to push in Stack : ");
int num1 = sc.nextInt();
stack.push(num1);
break;
case 2: System.out.println("Popped from stack: " + stack.pop());
break;
case 3: System.out.println("Peek element from stack: " + stack.peek());
break;
case 4: System.out.println("Stack is empty or not: " + stack.isEmpty());
break;
case 5: System.out.println("Prin ng the stack: ");
stack.printStack();
break;
case 6: System.out.println("Exi ng...");
break;
default: System.out.println("Invalid choice !! Please select a valid op on!");
break;
}
}while (numSt!=6);
}
else{
// Queue Demo
Queue<Integer> queue = new Queue<>();
System.out.println(
"Enter \n" +
"1 for Enqueue \n" +
"2 for Dequeue \n" +
"3 for Peek \n" +
"4 for Empty Check \n" +
"5 for Print Queue \n" +
"6 for Exit"
);
int numQu;
do {
numQu = sc.nextInt();
switch (numQu) {
case 1:
System.out.print("Enter a number to enqueue in Queue: ");
int num1 = sc.nextInt();
queue.enqueue(num1);
break;
case 2:
System.out.println("Dequeued from queue: " + queue.dequeue());
break;
case 3:
System.out.println("Front element of queue: " + queue.peek());
break;
case 4:
System.out.println("Queue is empty or not: " + queue.isEmpty());
break;
case 5:
System.out.println("Prin ng the queue: ");
queue.printQueue();
break;
case 6:
System.out.println("Exi ng...");
break;
default:
System.out.println("Invalid choice !! Please select a valid op on!");
break;
}
} while (numQu != 6);
}
sc.close();
}
}
Output:
PROGRAM :- 3
Write a java package to show dynamic polymorphism and
interfaces.
SOURCE CODE
package polymorphismdemo;
interface AnimalAc ons {
void makeSound(); // Abstract method for sound
void move(); // Abstract method for movement
}
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal implements AnimalAc ons {
@Override
public void makeSound() {
System.out.println("The dog barks: Woof Woof!");
}
@Override
public void move() {
System.out.println("The dog runs on four legs.");
}
@Override
public void eat() {
System.out.println("The dog eats bones.");
}
}
// Cat class extending Animal and implemen ng AnimalAc ons
class Cat extends Animal implements AnimalAc ons {
@Override
public void makeSound() {
System.out.println("The cat meows: Meow Meow!");
}
@Override
public void move() {
System.out.println("The cat jumps and walks gracefully.");
}
@Override
public void eat() {
System.out.println("The cat eats fish.");
}
}
// Main class to demonstrate dynamic polymorphism and interfaces
public class TestPolymorphism {
public sta c void main(String[] args) {
Animal myAnimal1 = new Dog();
myAnimal1.eat(); // Calls Dog's eat method (Dynamic Polymorphism)
// Using Animal reference to point to Cat object
Animal myAnimal2 = new Cat();
myAnimal2.eat(); // Calls Cat's eat method (Dynamic Polymorphism)
// Using AnimalAc ons reference for Dog
AnimalAc ons myDog = new Dog();
myDog.makeSound();
myDog.move();
// Using AnimalAc ons reference for Cat
AnimalAc ons myCat = new Cat();
myCat.makeSound();
myCat.move();
}
}
Output:
PROGRAM :- 4
Write a program to implement the concept of String and String
Buffer.
SOURCE CODE
public class StringExample {
public sta c void main(String[] args) {
String str = "Hello";
System.out.println("Original String: " + str);
str += " World";
System.out.println("Modified String: " + str);
String str2 = str + "!";
System.out.println("Further Modified String: " + str2);
StringBuffer stringBuffer = new StringBuffer("Hello");
System.out.println("\nOriginal StringBuffer: " + stringBuffer);
stringBuffer.append(" World");
System.out.println("Modified StringBuffer: " + stringBuffer);
stringBuffer.append("!");
System.out.println("Further Modified StringBuffer: " + stringBuffer);
}
}
Output:
PROGRAM :- 5
Write a program in java to implement the concept of Excep on
Handling with Five Keywords:-
TRY,CATCH,FINALLY,THROW AND THROWS.
SOURCE CODE
import java.u l.Scanner;
class InvalidAgeExcep on extends Excep on {
public InvalidAgeExcep on(String message) {
super(message); // Pass the message to the Excep on class
}
}
public class CustomExcep on {
public sta c void validateAge(int age) throws InvalidAgeExcep on {
if (age < 0 || age > 150) {
throw new InvalidAgeExcep on("Age must be between 0 and 150."); // Demonstrates "throw"
keyword
} else {
System.out.println("Valid age: " + age);
}
}
public sta c void main(String[] args) {
System.out.print("Enter the Age : ");
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
try { // Demonstrates "try" keyword
System.out.println("Star ng age valida on...");
validateAge(age); // Passing invalid age, triggers excep on
} catch (InvalidAgeExcep on e) { // Demonstrates "catch" keyword
System.out.println("Excep on caught: " + e.getMessage());
} finally { // Demonstrates "finally" keyword
System.out.println("Age valida on process completed.");
}
}
}
Output:
PROGRAM :- 6
Write a java program to show the concept of mul threading.
SOURCE CODE
class ThreadExample extends Thread {
private String threadName;
ThreadExample(String name) {
threadName = name;
}
public void run() {
try {
for(int i = 1; i <= 5; i++) {
System.out.println(threadName + ": " + i);
// Let the thread sleep for a while
Thread.sleep(1000);
}
} catch (InterruptedExcep on e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " exi ng.");
}
}
public class Main {
public sta c void main(String[] args) {
ThreadExample thread1 = new ThreadExample("Thread-1");
ThreadExample thread2 = new ThreadExample("Thread-2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedExcep on e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exi ng.");
}
}
Output:
PROGRAM :- 7
Write a program in java to create package in java.
Step 1: First, create a package with some classes:
File: mypackage/Ques on7.java
public class Ques on7 {
public Ques on7() {
}
public sta c void main(String[] var0) {
Gree ng var1 = new Gree ng();
var1.displayMessage();
}
}
Step 2: Now, create another class in the same package:
File: mypackage/ TestPackage.java
class Gree ng {
public void displayMessage() {
System.out.println("Hello from the mypackage!");
}
public void farewellMessage() {
System.out.println("Goodbye from the mypackage!");
}
}
public class TestPackage {
public sta c void main(String[] args) {
// Create an object of the Gree ng class
Gree ng gree ng = new Gree ng();
// Call the first method
gree ng.displayMessage();
// Call the second method
gree ng.farewellMessage();
}
}
Output:
PROGRAM :- 8
Write a program in Java to create a Calculator using AWT.
import java.awt.*;
import java.awt.event.*;
public class CalculatorAWT extends Frame implements Ac onListener {
// Define components
TextField input1, input2, result;
Bu on add, subtract, mul ply, divide;
CalculatorAWT() {
// Set up the frame
setTitle("Simple Calculator");
setSize(300, 200);
setLayout(new GridLayout(5, 2));
// Ini alize components
input1 = new TextField();
input2 = new TextField();
result = new TextField();
result.setEditable(false); // Result field is not editable
add = new Bu on("Add");
subtract = new Bu on("Subtract");
mul ply = new Bu on("Mul ply");
divide = new Bu on("Divide");
// Add components to the frame
add(new Label("First Number:"));
add(input1);
add(new Label("Second Number:"));
add(input2);
add(new Label("Result:"));
add(result);
add(add);
add(subtract);
add(mul ply);
add(divide);
// Add ac on listeners
add.addAc onListener(this);
subtract.addAc onListener(this);
mul ply.addAc onListener(this);
divide.addAc onListener(this);
// Close window on clicking the close bu on
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
setVisible(true);
}
public void ac onPerformed(Ac onEvent e) {
double num1 = Double.parseDouble(input1.getText());
double num2 = Double.parseDouble(input2.getText());
double res = 0;
// Perform the appropriate opera on
if (e.getSource() == add) {
res = num1 + num2;
} else if (e.getSource() == subtract) {
res = num1 - num2;
} else if (e.getSource() == mul ply) {
res = num1 * num2;
} else if (e.getSource() == divide) {
res = num1 / num2;
}
// Display the result
result.setText(String.valueOf(res));
}
public sta c void main(String[] args) {
new CalculatorAWT();
}
}
Output:
PROGRAM :- 9
Create an editor like MS-word using swings.
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MSWordEditor {
public sta c void main(String[] args) {
SwingU li es.invokeLater(Editor::new);
}
}
class Editor extends JFrame implements Ac onListener {
// Components
private JTextArea textArea;
private JMenuItem newFile, openFile, saveFile, exitFile;
private JMenuItem cutEdit, copyEdit, pasteEdit;
private JFileChooser fileChooser;
public Editor() {
// Frame setup
setTitle("MS Word Editor");
setSize(800, 600);
setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Text Area
textArea = new JTextArea();
add(new JScrollPane(textArea), BorderLayout.CENTER);
// File chooser
fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
// Menu bar
JMenuBar menuBar = new JMenuBar();
// File menu
JMenu fileMenu = new JMenu("File");
newFile = new JMenuItem("New");
openFile = new JMenuItem("Open");
saveFile = new JMenuItem("Save");
exitFile = new JMenuItem("Exit");
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.add(exitFile);
newFile.addAc onListener(this);
openFile.addAc onListener(this);
saveFile.addAc onListener(this);
exitFile.addAc onListener(this);
menuBar.add(fileMenu);
// Edit menu
JMenu editMenu = new JMenu("Edit");
cutEdit = new JMenuItem("Cut");
copyEdit = new JMenuItem("Copy");
pasteEdit = new JMenuItem("Paste");
editMenu.add(cutEdit);
editMenu.add(copyEdit);
editMenu.add(pasteEdit);
cutEdit.addAc onListener(this);
copyEdit.addAc onListener(this);
pasteEdit.addAc onListener(this);
menuBar.add(editMenu);
// Set menu bar
setJMenuBar(menuBar);
// Display frame
setVisible(true);
}
@Override
public void ac onPerformed(Ac onEvent e) {
if (e.getSource() == newFile) {
textArea.setText(""); // Clear text area
} else if (e.getSource() == openFile) {
int op on = fileChooser.showOpenDialog(this);
if (op on == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
textArea.read(reader, null); // Read file contents into the text area
} catch (IOExcep on ex) {
JOp onPane.showMessageDialog(this, "Error opening file!", "Error",
JOp onPane.ERROR_MESSAGE);
}
}
} else if (e.getSource() == saveFile) {
int op on = fileChooser.showSaveDialog(this);
if (op on == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
textArea.write(writer); // Save text area contents to file
} catch (IOExcep on ex) {
JOp onPane.showMessageDialog(this, "Error saving file!", "Error",
JOp onPane.ERROR_MESSAGE);
}
}
} else if (e.getSource() == exitFile) {
System.exit(0); // Exit applica on
} else if (e.getSource() == cutEdit) {
textArea.cut(); // Cut text
} else if (e.getSource() == copyEdit) {
textArea.copy(); // Copy text
} else if (e.getSource() == pasteEdit) {
textArea.paste(); // Paste text
}
}
}
Output:
PROGRAM :- 10
Write a java program to show the concept of Collec ons.
import java.u l.*;
public class Collec onsExample {
public sta c void main(String[] args) {
// Example of ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");
System.out.println("ArrayList Elements:");
for (String fruit : arrayList) {
System.out.println(fruit);
}
// Example of HashSet
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple"); // This will not be added as Set does not allow duplicates
System.out.println("\nHashSet Elements:");
for (String fruit : hashSet) {
System.out.println(fruit);
}
// Example of HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Orange");
System.out.println("\nHashMap Elements:");
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Output: