KEMBAR78
Vivek Java | PDF | Queue (Abstract Data Type) | String (Computer Science)
0% found this document useful (0 votes)
5 views22 pages

Vivek Java

The document outlines a practical file for a Bachelor of Technology course in Computer Science & Technology at St. Andrews Institute of Technology & Management for the session 2024-2025. It includes various Java programming tasks such as implementing data structures, exception handling, multithreading, and creating GUI applications. Each task is accompanied by source code and expected outputs.

Uploaded by

ankitghamdan106
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)
5 views22 pages

Vivek Java

The document outlines a practical file for a Bachelor of Technology course in Computer Science & Technology at St. Andrews Institute of Technology & Management for the session 2024-2025. It includes various Java programming tasks such as implementing data structures, exception handling, multithreading, and creating GUI applications. Each task is accompanied by source code and expected outputs.

Uploaded by

ankitghamdan106
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/ 22

ST.

ANDREWS INSTITUTE
OF TECHNOLOGY & MANAGEMENT

Gurgaon Delhi (NCR)


Approved by AICTE, Govt. of India, New Delhi affiliated to Maharshi
Dayanand University
‘A’ Grade State University, accredited by NAAC

Session: 2024 – 2025

Bachelor of Technology

Computer Science & Technology

A Practical File

Programming in Java Lab

Subject Code-LC-CSE-327G

Submitted To: Submitted by:


Mr. Parveen Yadav NAME:
(Assistant Professor)
SEM:

ROLL NO.:
St. Andrews Institute of Technology &
Management, Gurugram
Department of……………………………

Practical Lab Evaluation Sheet

Practical Viva- Attenda Over Remarks


nce Practical all
S.No Program Date CO Performed Voce &
(05) File (05) 25
(10) (05) Signature
Write a program in java to print your
details (Name, Rollno, Class, Sem,
1 Collage Name). And create the JAR file CO

2 CO
Create a java program to implement
stack and queue concept.

Write a java package to show dynamic


3 polymorphism and interfaces. CO

Write a program to implement the


4 concept of String and String Buffer. CO

Exception Handling with Five Keywords:-


TRY,
CATCH,FINALLY,THROW AND
5 THROWS. CO

program to show the concept of


6 multithreading CO
program in java to create package in
java
program in java to create package in
7 java CO
program in Java to create a Calculator
8 using AWT. CO

Create an editor like MS-word using


9 swings. CO
java program to show the concept of
10 Collections CO

Approved & Verified by (Faculty Name) (Faculty Sign.


 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 Question1 {
String name = "Vivek";
int rollNo = 227043;
String className = "B.Tech Aiml";
int sem = 5;
String collegeName = "St. Andrews Institute 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:
 PROGRAM 2:
Create a java program to implement stack and queue concept.

SOURCE CODE
import java.util.ArrayList;
import java.util.Scanner;
// Stack Implementation
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 Implementation
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 Question2 {
public static 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("Printing the stack: ");stack.printStack();
break;
case 6: System.out.println("Exiting...");
break;
default: System.out.println("Invalid choice !! Please select a valid option!");
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("Printing the queue: ");
queue.printQueue();
break;
case 6:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice !! Please select a valid option!");
break;
}
} while (numQu != 6);
}
sc.close();
}
}

Output:
 PROGRAM 3:
Write a java package to show dynamic polymorphism and
interfaces.

SOURCE CODE
// Package declaration
package polymorphismdemo;

// Interface defining actions for animals


interface AnimalActions {
void makeSound(); // Abstract method for sound
void move(); // Abstract method for movement
}

// Base class representing a general animal


class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}

// Dog class extending Animal and implementing AnimalActions


class Dog extends Animal implements AnimalActions {
@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(" dog eats bones.");
}
}

// Cat class extending Animal and implementing AnimalActions


class Cat extends Animal implements AnimalActions {
@Override
public void makeSound()
{ System.out.println(" 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 static void main(String[] args) {
// Using Animal reference to point to Dog object
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 AnimalActions reference for Dog


AnimalActions myDog = new Dog();
myDog.makeSound();
myDog.move();

// Using AnimalActions reference for Cat


AnimalActions 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 static void main(String[] args) {
// Using String
String str = "Namste";
System.out.println("Original String: " + str);

// Concatenating using String


str += " Bharat";
System.out.println("Modified String: " + str);

// Since strings are immutable, a new object is created with each concatenation
String str2 = str + "!";
System.out.println("Further Modified String: " + str2);

// Using StringBuffer
StringBuffer stringBuffer = new StringBuffer("Hello");
System.out.println("\nOriginal StringBuffer: " + stringBuffer);

// Append operation using StringBuffer


stringBuffer.append(" World");
System.out.println("Modified StringBuffer: " + stringBuffer);

// Further append operation


stringBuffer.append("!");
System.out.println("Further Modified StringBuffer: " + stringBuffer);
}
}
Output:
 PROGRAM 5:
Write a program in java to implement the concept of Exception
Handling with Five Keywords:-
TRY,CATCH,FINALLY,THROW AND THROWS.

SOURCE CODE
// Custom Exception Class
import java.util.Scanner;
class InvalidAgeException extends Exception
{ public InvalidAgeException(String message) {
super(message); // Pass the message to the Exception class
}
}
public class CustomException {
// Method to validate age, demonstrates "throws" keyword
public static void validateAge(int age) throws InvalidAgeException
{if (age < 0 || age > 150) {
throw new InvalidAgeException("Age must be between 0 and 150."); // Demonstrates
"throw" keyword
} else {
System.out.println("Valid age: " + age);
}
}
public static 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("Starting age validation...");
validateAge(age); // Passing invalid age, triggers exception
} catch (InvalidAgeException e) { // Demonstrates "catch" keyword
System.out.println("Exception caught: " + e.getMessage());
} finally { // Demonstrates "finally" keyword
System.out.println("Age validation process completed.");
}
}
}
Output:
 PROGRAM 6:
Write a java program to show the concept of multithreading.

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 (InterruptedException e)
{ System.out.println(threadName + " interrupted."); }
System.out.println(threadName + " exiting."); }}

public class Main {


public static 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 (InterruptedException e)
{ System.out.println("Main thread interrupted."); }
System.out.println("Main thread exiting."); }}

Output:
 PROGRAM 7:
Write a program in java to create package in java.

SOURCE CODE
// Simulating a package
class Greeting {
public void displayMessage()
{ System.out.println("Hey there, nice to meet
You");
}

public void farewellMessage()


{ System.out.println("Goodbye");
}
}

public class TestPackage {


public static void main(String[] args) {
// Create an object of the Greeting class
Greeting greeting = new Greeting();

// Call the first method


greeting.displayMessage();

// Call the second method


greeting.farewellMessage();
}
}

Output:
 PROGRAM 8:
Write a program in Java to create a Calculator using AWT.

SOURCE CODE
import java.awt.*;
import java.awt.event.*;

public class CalculatorAWT extends Frame implements ActionListener {


// Define components
TextField input1, input2, result;
Button add, subtract, multiply, divide;

CalculatorAWT() {
// Set up the frame
setTitle("Simple Calculator");
setSize(300, 200);
setLayout(new GridLayout(5, 2));

// Initialize components
input1 = new TextField();
input2 = new TextField();
result = new TextField();
result.setEditable(false); // Result field is not editable

add = new Button("Add");


subtract = new Button("Subtract");
multiply = new Button("Multiply");
divide = new Button("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(multiply);
add(divide);

// Add action listeners


add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
// Close window on clicking the close button
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e) {
dispose();
}
});

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


double num1 = Double.parseDouble(input1.getText());
double num2 = Double.parseDouble(input2.getText());
double res = 0;

// Perform the appropriate operation


if (e.getSource() == add)
{res = num1 + num2;
} else if (e.getSource() == subtract)
{res = num1 - num2;
} else if (e.getSource() == multiply)
{res = num1 * num2;
} else if (e.getSource() == divide)
{res = num1 / num2;
}

// Display the result


result.setText(String.valueOf(res));
}

public static void main(String[] args)


{new CalculatorAWT();
}
}
Output:
 PROGRAM 9:
Create an editor like MS-word using swings.

SOURCE CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class SimpleTextEditor extends JFrame implements ActionListener


{JTextArea textArea;
JMenuBar menuBar;
JMenu fileMenu, editMenu;
JMenuItem openItem, saveItem, exitItem, newItem;
JMenuItem cutItem, copyItem, pasteItem;

public SimpleTextEditor() {
// Set up the frame
setTitle("Simple Text Editor");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Initialize the text area


textArea = new JTextArea();
add(new JScrollPane(textArea), BorderLayout.CENTER);

// Initialize the menu bar


menuBar = new JMenuBar();

// Initialize File menu


fileMenu = new JMenu("File");
newItem = new JMenuItem("New");
openItem = new JMenuItem("Open");
saveItem = new JMenuItem("Save");
exitItem = new JMenuItem("Exit");

newItem.addActionListener(this);
openItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);

fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(exitItem);
// Initialize Edit menu
editMenu = new JMenu("Edit");
cutItem = new JMenuItem("Cut");
copyItem = new JMenuItem("Copy");
pasteItem = new JMenuItem("Paste");

cutItem.addActionListener(this);
copyItem.addActionListener(this);
pasteItem.addActionListener(this);

editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);

// Add menus to the menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);

// Set the menu bar for the frame


setJMenuBar(menuBar);

setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e)
{if (e.getSource() == newItem) {
textArea.setText("");
} else if (e.getSource() == openItem)
{openFile();
} else if (e.getSource() == saveItem)
{saveFile();
} else if (e.getSource() == exitItem)
{System.exit(0);
} else if (e.getSource() == cutItem)
{textArea.cut();
} else if (e.getSource() == copyItem)
{textArea.copy();
} else if (e.getSource() == pasteItem)
{textArea.paste();
}
}

private void openFile() {


JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try (BufferedReader reader = new BufferedReader(new
FileReader(fileChooser.getSelectedFile()))) {
textArea.read(reader, null);
} catch (IOException ex)
{ex.printStackTrace();
}
}
}

private void saveFile() {


JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showSaveDialog(this);

if (option == JFileChooser.APPROVE_OPTION) {
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(fileChooser.getSelectedFile()))) {
textArea.write(writer);
} catch (IOException ex)
{ex.printStackTrace();
}
}
}

public static void main(String[] args)


{new SimpleTextEditor();
}
}
Output:
 PROGRAM 10:
Write a java program to show the concept of Collections.

SOURCE CODE
import java.util.*;

public class CollectionsExample {


public static void main(String[] args) {
// Example of ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("Nestle");
arrayList.add("Bajaj");
arrayList.add("Orient");

System.out.println("ArrayList Elements:");
for (String company : arrayList) {
System.out.println(company);
}

// Example of HashSet
Set<String> hashSet = new HashSet<>();
hashSet.add("Orient");
hashSet.add("Bajaj");
hashSet.add("Tata");
hashSet.add("Himani"); // This will not be added as Set does not allow duplicates

System.out.println("\nHashSet Elements:");
for (String company : hashSet) {
System.out.println(company);
}

// Example of HashMap
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Tata Tea");
hashMap.put(2, "Tata Salt");
hashMap.put(3, "Tata Masale");

System.out.println("\nHashMap Elements:");
for (Map.Entry<Integer, String> entry : hashMap.entrySet())
{ System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Output:

You might also like