0% found this document useful (0 votes)
12 views31 pages

CD FILE

Uploaded by

Nepturious
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

CD FILE

Uploaded by

Nepturious
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

INDEX

Submission
S.No. EXPERIMENT NAME Practical Date REMARKS
Date

Write a Java program to


1. implement stack and queue
concept.

Write a Java program to


2. produce the tokens from
given long string.

Write a Java package to


3. show dynamic polymorphism
and interfaces.

Write a Java program to show


4. multithreaded producer and
consumer application.

Create a customized
exception and also make use
5.
of all the 5 exception
keywords.

Convert the content of a given


6. file into the uppercase content
of the same file.

Write a program in Java to


7. sort the content of a given text
file.

Develop an analog clock


8.
using applet.

Develop a scientific calculator


9.
using swings.

Create an editor like MS-


10.
Word using swings.
EXPERIMENT-1
Aim: Write a Java program to implement stack and queue concept.
Language Used: Java

Theory:
 Stack:- The stack is a linear data structure that is used to store the
collection of objects. It is based on the Last-In- First-Out (LIFO). Java
collection framework provides many interfaces and classes to store the
collection of objects.
 Queue:- A queue is an interface provided in the java.util package that
extends collections to provide additional methods to access or manipulate
items at the head of the queue. Queue elements are commonly accessed in
a First-In- First-Out (FIFO) manner.

Code : Stack
public class Stack {

private int arr[];

private int top;

private int capacity;

Stack(int size){

arr=new int[size];

capacity=size;

top=-1;

public void push(int x)

{ if(isFull()){

System.out.println("Stack Overflow");

System.exit(1);

System.out.println("Inserting"+x); arr[++top]=x;

public int pop(){

if(isEmpty()){

System.out.println(("Stack Empty")); System.exit(1);

}
return arr[top--];

public int getSize(){

return top+1;

public Boolean isEmpty(){

return top==-1;

public Boolean isFull(){

return top==capacity-1;

public void printStack(){

for (int i=0;i<=top;i++){

System.out.println(arr[i]+",");

public static void main(String[] args){

Stack stack=new Stack(5);

stack.push(1);

stack.push(2);

stack.push(3);

System.out.print("Stack: ");

stack.printStack();

stack.pop();

System.out.println("\nAfter popping out");

stack.printStack();

}
Code : Queue
public class Queue {

int size=5;

int items[]=new int[size];

int front,rear;

Queue(){

front=-1; rear=-1;

boolean isFull(){

if(front==0 && rear==size-1){

return true;

return false;

boolean isEmpty(){

if(front==-1){

return true;

else{

return false;

void enQueue(int element){

if (isFull()){

System.out.println("Queue is Full");

else{

if(front==-1){ front=0;

rear++; items[rear]=element;

System.out.println("Insert"+element);

}
}

int deQueue(){

int element;

if(isEmpty()){

System.out.println("Queue is Empty"); return(-1);

else{

element=items[front];

if(front>=rear){ front=-1;

rear=-1;

else{

front++;

System.out.println(element+" Deleted"); return (element);

void display(){

int i;

if(isEmpty()){

System.out.println("Empty Queue");

else{

System.out.println("\nFront index-> "+front);

System.out.println("Items ->");

for(i=front;i<=rear;i++){

System.out.print(items[i]+" ");

System.out.println("\nRear index-> "+rear);

public static void main(String[] args){


Queue q=new Queue();

q.deQueue();

for(int i=1;i<6;i++){

q.enQueue(i);

q.enQueue(6);

q.display();

q.deQueue();

q.display();

OUTPUT:
EXPERIMENT-2
Aim: Write a Java program to produce the tokens from given long string.
Language used: Java
Theory:
Token: In Java, tokens are the basic building blocks of a program. They are the smallest
individual units of a program that have meaning to the compiler and are used to represent
the various elements of a program such as keywords, identifiers and literals.

Code:
import java.util.StringTokenizer; public class
Simple {

public static void main(String[] args) {

StringTokenizer st=new StringTokenizer("My name is Nishant Gupta"); while


(st.hasMoreTokens()) {

System.out.println(st.nextToken());

OUTPUT:
EXPERIMENT-3
Aim: Write a Java package to show dynamic polymorphism and interfaces.
Language used: Java
Theory:
Dynamic Polymorphism:- Dynamic polymorphism in Java refers to the process when a
call to an overridden process is resolved at the runtime. The reference variable of a
superclass calls the overridden method. As the name dynamic connotes, dynamic
polymorphism happens among different classes as opposed to static polymorphism.

Interface:- An interface in Java programming language is defined as an abstract type


used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour.
A Java interface contains static constants and abstract methods.

Code: Dynamic Polymorphism


import java.io.*; class
GFG1{

void name(){

System.out.println("This is the GFG1 class");

public class GFG extends GFG1{ void


name(){

System.out.println("This is the GFG class");

public static void main(String[] args) { GFG1 ob=new


GFG1();

ob.name();

GFG1 ob1=new GFG();

ob1.name();

Code: Interface
import java.io.*; interface
In1{

final int a=10; void


display();
}

class TestClass implements In1{ public void display(){

System.out.println("Geek");

public static void main(String[] args) { TestClass t=new


TestClass(); t.display();

System.out.println(a);

Output:
EXPERIMENT-4
Aim: Write a Java program to show multithreaded producer and consumer application.
Language used: Java
Theory: The producer is to either go to sleep or discard data if the buffer is full. The next
time the consumer removes an item from the buffer, it notifies the producer, who starts to
fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to
be empty. The next time the producer puts data into the buffer, it wakes up the sleeping
consumer. An inadequate solution could result in a deadlock where both processes are
waiting to be awakened.

Code:
import java.util.LinkedList; public
class Threadexample {

public static void main(String[] args) throws InterruptedException { final PC pc=new


PC();

Thread t1=new Thread(new Runnable(){


@Override

public void run(){ try{

pc.produce();

catch(InterruptedException e){
e.printStackTrace();

});

Thread t2=new Thread(new Runnable(){


@Override

public void run(){ try{

pc.consume();

catch(InterruptedException e){
e.printStackTrace();

});

t1.start();
t2.start();

t1.join();

t2.join();

public static class PC{

LinkedList<Integer> list=new LinkedList<>(); int


capacity=2;

public void produce() throws InterruptedException{ int


value=0;

while (true){

synchronized(this){

while (list.size()==capacity) wait();

System.out.println("Producer produced- "+value);


list.add(value++);

notify(); Thread.sleep(1000);

public void consume() throws InterruptedException{ while(true){

synchronized(this){
while(list.size()==0)

wait();

int val=list.removeFirst(); System.out.println("Consumer


consumed- "+val); notify();

Thread.sleep(1000);

}
OUTPUT:
EXPERIMENT-5
Aim: Create a customized exception and also make use of all the 5 exception keywords.
Language used: Java
Theory: Customized Exception:- An exception is an issue that occurred during the
execution of a program. When an exception occurred the program gets terminated
abruptly and the code past the line that generated the execution never gets executed.
Java provides the facility to create our own exceptions, which are basically derived
classes of Exception. Creating our own exception is known as custom exception.
Basically, Java custom exceptions are used to customize the exception according to
our needs.

Code:
class MyException extends Exception{ public
MyException(String s){

super(s);

public class Main {

public static void main(String[] args) { try{

throw new MyException("GeeksGeeks");

catch(MyException ex){ System.out.println("Caught");


System.out.println(ex.getMessage());

OUTPUT:
EXPERIMENT-6
Aim: Convert the content of a given file into the uppercase content of the same file.
Language used: Java
Code:
class Main{

public static void main(String[] args) { String str="My


name is Nishant Gupta"; String
strup=str.toUpperCase();
System.out.println(strup);

Output:
EXPERIMENT-7
Aim: Write a program in Java to sort the content of a given text file.

Language used: Java


import java.io.BufferedReader; import
java.io.BufferedWriter; import
java.io.FileReader; import
java.io.FileWriter; import
java.io.IOException; import
java.util.ArrayList; import
java.util.Collections; import java.util.List;

import java.util.Scanner;

public class SortStringsFromFile {

public static void main(String[] args) { Scanner scanner = new


Scanner(System.in);

System.out.print("Enter the number of strings: "); int n =


scanner.nextInt();

scanner.nextLine(); try {

BufferedWriter writer = new BufferedWriter(new


FileWriter("file.txt"));

for (int i = 0; i < n; i++) { System.out.print("Enter the


string: "); String name = scanner.nextLine();
writer.write(name + "\n");

writer.close();

BufferedReader reader = new BufferedReader(new


FileReader("file.txt"));

List<String> names = new ArrayList<String>(); String line;

while ((line = reader.readLine()) != null) { names.add(line);

reader.close(); Collections.sort(names);

writer = new BufferedWriter(new FileWriter("file.txt")); for (String name :


names) {

writer.write(name + "\n");

}
writer.close();

for (String name : names) {


System.out.println(name);

} catch (IOException e) {
e.printStackTrace();

scanner.close();

OUTPUT:
EXPERIMENT-8
Aim; Develop an analog clock using applet.

Code:
import javax.swing.*;

import java.awt.*;

import java.util.Calendar;

public class analogClock extends JPanel implements Runnable {

public static void main(String[] args) {

SwingUtilities.invokeLater(analogClock::createAndShowGUI);

private static void createAndShowGUI() {

JFrame frame = new JFrame("Analog Clock");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(new analogClock());

frame.pack();

frame.setVisible(true);

public analogClock() {

setBackground(new Color(50, 50, 50));

new Thread(this).start();

@Override

public void run() {

while (true) {

repaint();

delayAnimation();

} }

private void delayAnimation() {

try {

Thread.sleep(50);
} catch (InterruptedException e) {

e.printStackTrace();

} }

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

// Get the system time

Calendar time = Calendar.getInstance();

int hour = time.get(Calendar.HOUR_OF_DAY);

int minute = time.get(Calendar.MINUTE);

int second = time.get(Calendar.SECOND);

// 12 hour format

if (hour > 12) {

hour -= 12;

// Calculate the center of the panel

int centerX = getWidth() / 2;

int centerY = getHeight() / 2;

// Draw clock body center at (400, 200)

int clockSize = Math.min(getWidth(), getHeight()) * 1 / 2;

int clockX = centerX - clockSize / 2;

int clockY = centerY - clockSize / 2;

g.setColor(Color.WHITE);

g.fillOval(clockX, clockY, clockSize, clockSize);

// Labeling

g.setColor(Color.BLACK);

g.drawString("12", centerX - 5, clockY + 15);

g.drawString("9", clockX + 5, centerY + 5);

g.drawString("6", centerX - 5, clockY + clockSize - 5);

g.drawString("3", clockX + clockSize - 15, centerY + 5);

// Declaring variables to be used


double angle;

int x, y;

// Second hand's angle in Radian

angle = Math.toRadians((15 - second) * 6);

// Position of the second hand with length 100 unit

x = (int) (Math.cos(angle) * (clockSize / 2 - 10));

y = (int) (Math.sin(angle) * (clockSize / 2 - 10));

// Red color second hand

g.setColor(Color.RED);

g.drawLine(centerX, centerY, centerX + x, centerY - y);

// Minute hand's angle in Radian

angle = Math.toRadians((15 - minute) * 6);

// Position of the minute hand with length 80 unit

x = (int) (Math.cos(angle) * (clockSize / 2 - 20));

y = (int) (Math.sin(angle) * (clockSize / 2 - 20));

// Blue color Minute hand

g.setColor(Color.BLUE);

g.drawLine(centerX, centerY, centerX + x, centerY - y);

// Hour hand's angle in Radian

angle = Math.toRadians((15 - (hour * 5)) * 6);

// Position of the hour hand with length 50 unit

x = (int) (Math.cos(angle) * (clockSize / 2 - 30));

y = (int) (Math.sin(angle) * (clockSize / 2 - 30));

g.setColor(Color.BLACK);

g.drawLine(centerX, centerY, centerX + x, centerY - y);

@Override

public Dimension getPreferredSize() {

return new Dimension(400, 400); // Default preferred size

}
OUTPUT:
EXPERIMENT-9
Aim: Develop a scientific calculator using swings.

Language used: Java

Code:
import javax.swing.*; import
java.awt.*;

import java.awt.event.ActionEvent; import


java.awt.event.ActionListener;

public class Calculator extends JFrame { private


JTextField displayField; public Calculator() {

setTitle("Scientific Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);

displayField = new JTextField(); displayField.setPreferredSize(new


Dimension(300, 30)); displayField.setEditable(false);

JPanel buttonPanel = new JPanel(new GridLayout(6, 4, 10, 10)); String[]


buttonLabels = {

"7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"0", ".", "=", "+",

"sin", "cos", "tan", "sqrt",

"e", "^", "pi", "clr"

};

for (String label : buttonLabels) { JButton button = new


JButton(label);

button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);

setLayout(new FlowLayout());
add(displayField); add(buttonPanel);

pack(); setLocationRelativeTo(null);
setVisible(true);

}
private class ButtonClickListener implements ActionListener {

public void actionPerformed(ActionEvent event) { String


command = event.getActionCommand(); String
expression = displayField.getText(); if
("=".equals(command)) {

calculate();

} else if ("clr".equals(command)) {
displayField.setText("");

} else if ("sin".equals(command)) {
displayField.setText(String.valueOf(Math.sin(Double.parseDoubl

e(expression))));

} else if ("cos".equals(command)) {
displayField.setText(String.valueOf(Math.cos(Double.parseDoubl

e(expression))));

} else if ("tan".equals(command)) {
displayField.setText(String.valueOf(Math.tan(Double.parseDoubl

e(expression))));

} else if ("sqrt".equals(command)) {
displayField.setText(String.valueOf(Math.sqrt(Double.parseDoub

le(expression))));

} else {

displayField.setText(displayField.getText() + command);

private void calculate() {

String expression = displayField.getText(); try {

double result = evaluateExpression(expression);


displayField.setText(String.valueOf(result));

} catch (NumberFormatException e) {
displayField.setText("Error");

private double evaluateExpression(String expression) { return


new Object() {

int pos = -1, ch; void


nextChar() {
ch = (++pos < expression.length()) ?
expression.charAt(pos) : -1;

boolean eat(int charToEat) { while (ch


== ' ') nextChar(); if (ch ==
charToEat) {

nextChar();
return true;

return false;

double parse() {

nextChar();

double x = parseExpression();

if (pos < expression.length()) throw new


RuntimeException ("Unexpected character: " + (char) ch);

return x;

double parseExpression() {
double x = parseTerm();
while(true) {

if (eat('+')) x += parseTerm();

else if (eat('-')) x -= parseTerm(); else


return x;

double parseTerm() {

double x = parseFactor();
while (true) {

if (eat('*')) x *= parseFactor(); else if


(eat('/')) x /= parseFactor(); else return x;

}
double parseFactor() {

if (eat('+')) return parseFactor(); if (eat('-'))


return -parseFactor(); double x;

int startPos = this.pos; if


(eat('(')) {

x = parseExpression();
eat(')');

} else if ((ch >= '0' && ch <= '9') || ch == '.') {

while ((ch >= '0' && ch <= '9') || ch == '.')

nextChar();

x = Double.parseDouble(expression.substring(startPos, this.pos));

} else if (eat('e')) { x =
Math.E;

} else if (eat('p')) { eat('i');

x = Math.PI;

} else {

throw new RuntimeException("Unexpected character: " +(char) ch);

if (eat('^')) x = Math.pow(x, parseFactor());

return x;

}.parse();

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {

public void
run() {
new
Calcul
ator();

});

}
OUTPUT:
EXPERIMENT-10
Aim: Create an editor like MS- Word using swings.

Language used: Java

Code:
import javax.swing.*;

import java.io.*;

import java.awt.event.*;

import javax.swing.plaf.metal.*;

import javax.swing.text.*;

class editor extends JFrame implements ActionListener {

// Text component

JTextArea t;

// Frame

JFrame f;

// Constructor

editor()

// Create a frame

f = new JFrame("editor");

try {

// Set metal look and feel

UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");

// Set theme to ocean

MetalLookAndFeel.setCurrentTheme(new OceanTheme());

catch (Exception e) {

// Text component

t = new JTextArea();

// Create a menubar
JMenuBar mb = new JMenuBar();

// Create amenu for menu

JMenu m1 = new JMenu("File");

// Create menu items

JMenuItem mi4 = new JMenuItem("cut");

JMenuItem mi5 = new JMenuItem("copy");

JMenuItem mi6 = new JMenuItem("paste");

// Add action listener

mi4.addActionListener(this);

mi5.addActionListener(this);

mi6.addActionListener(this);

m2.add(mi4);

m2.add(mi5);

m2.add(mi6);

JMenuItem mc = new JMenuItem("close");

mc.addActionListener(this);

mb.add(m1);

mb.add(m2);

mb.add(mc);

f.setJMenuBar(mb);

f.add(t);

f.setSize(500, 500);

f.show();

// If a button is pressed

public void actionPerformed(ActionEvent e)

String s = e.getActionCommand();

if (s.equals("cut")) {

t.cut();

}
else if (s.equals("copy")) {

t.copy();

else if (s.equals("paste")) {

t.paste();

else if (s.equals("Save")) {

// Create an object of JFileChooser class

JFileChooser j = new JFileChooser("f:");

// Invoke the showsSaveDialog function to show the save dialog

int r = j.showSaveDialog(null);

if (r == JFileChooser.APPROVE_OPTION) {

// Set the label to the path of the selected directory

File fi = new File(j.getSelectedFile().getAbsolutePath());

try {

// Create a file writer

FileWriter wr = new FileWriter(fi, false);

// Create buffered writer to write

BufferedWriter w = new BufferedWriter(wr);

// Write

w.write(t.getText());

w.flush();

w.close();

catch (Exception evt) {

JOptionPane.showMessageDialog(f, evt.getMessage());

// If the user cancelled the operation

else

JOptionPane.showMessageDialog(f, "the user cancelled the operation");


}

else if (s.equals("Print")) {

try {

// print the file

t.print(); }

catch (Exception evt) {

JOptionPane.showMessageDialog(f, evt.getMessage());

else if (s.equals("Open")) {

// Create an object of JFileChooser class

JFileChooser j = new JFileChooser("f:");

// Invoke the showsOpenDialog function to show the save dialog

int r = j.showOpenDialog(null);

// If the user selects a file

if (r == JFileChooser.APPROVE_OPTION) {

// Set the label to the path of the selected directory

File fi = new File(j.getSelectedFile().getAbsolutePath());

try {

// String

String s1 = "", sl = "";

// File reader

FileReader fr = new FileReader(fi);

// Buffered reader

BufferedReader br = new BufferedReader(fr);

// Initialize sl

sl = br.readLine();

// Take the input from the file

while ((s1 = br.readLine()) != null) {

sl = sl + "\n" + s1; }

// Set the text


t.setText(sl);

catch (Exception evt) {

JOptionPane.showMessageDialog(f, evt.getMessage()); }

// If the user cancelled the operation

else

JOptionPane.showMessageDialog(f, "the user cancelled the operation");

else if (s.equals("New")) {

t.setText("");

else if (s.equals("close")) {

f.setVisible(false) }

// Main class

public static void main(String args[])

editor e = new editor(); }

OUTPUT:

You might also like