You are on page 1of 67

EXPERIMENT 10

AIM : Initialise an integer array with ASCII values and print the corresponding
character values in a single row.

SOURCE CODE:
import java.util.Scanner;
public class LAB3Q1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] asciiArray = new int[5];
System.out.println("Enter ASCII values: ");
for(int i=0; i<5; i++){
asciiArray[i] = scanner.nextInt();
}
System.out.println("Corresponding characters: ");
for(int i=0; i<5; i++){
char c= (char)asciiArray[i];
System.out.println(c);
}
}
}

OUTPUT:

10 | P a g e
EXPERIMENT 11

AIM : Write a program to reverse the elements of a given 2*2 array. Four
integer numbers need to be passed as Command-Line arguments.

SOURCE CODE:
public class LAB3Q2 {
public static void main(String[] args) {
int[][] array = new int[2][ 2];
int idx = 0;
for(int i=0; i<2; i++){
for(int j=0; j<2; j++){
array[i][ j] = Integer.parseInt(args[idx]);
idx++;
}
}
for(int i=1; i>=0; i--){
for(int j=1; j>=0; j--){
System.out.print(array[i][ j] + " " );
}
System.out.println();
}

}
}

OUTPUT:

11 | P a g e
EXPERIMENT 12

AIM : Create a java program to implement stack and queue concept.

SOURCE CODE:
public class stackAndQueue {
public static void main(String[] args) {
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
System.out.println("Stack implementation");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());

Queue q = new Queue();


q.push(10);
q.push(20);
q.push(30);
q.push(40);
System.out.println("Queue implementation");
System.out.println(q.pop());
System.out.println(q.pop());
System.out.println(q.pop());
System.out.println(q.pop());
}
}
class Stack{
private int[] array;
private int currIndx;

12 | P a g e
public Stack(){
array = new int[ 50];
currIndx = 0;
}
public void push(int num){
array[ currIndx] = num;
currIndx++;
}

public int pop(){


if(currIndx != 0){
currIndx--;
return array[ currIndx];
}
return -1;
}
}
class Queue{
private int[] array;
private int front;
private int rear;

public Queue(){
array = new int[ 50];
front = rear = 0;
}
public void push(int num){
array[ rear] = num;
rear++;
}

public int pop(){


if(rear != front){
return array[ front++];
}
return -1;
}

13 | P a g e
}

OUTPUT:

14 | P a g e
EXPERIMENT 13

AIM : Write a java program to produce the tokens from long string.

SOURCE CODE:
import java.util.Scanner;
import java.util.StringTokenizer;
public class Tokens {
public static void main(String[] args) {
String str = new String();
System.out.print("Enter a string: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
StringTokenizer st1 = new StringTokenizer(str, " " );

while (st1.hasMoreTokens()){
System.out.println(st1.nextToken());
}
}
}

OUTPUT:

15 | P a g e
EXPERIMENT 14

AIM : Using the concept of method overloading. Write method for calculating
the area of triangle, circle and rectangle.

SOURCE CODE:
public class Main {
public static void main(String[] args) {
double area_triangle = area(2,3,4);
System.out.printf("%.2f%n", area_triangle);
double area_circle = area(7);
System.out.printf("%.2f%n", area_circle);
double area_rectangle = area(6,8);
System.out.printf("%.2f%n", area_rectangle);
}

public static double area(double a, double b, double c){


double s = (a+b+c)/2.0;
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
public static double area(double radius){
return 3.14 * radius * radius;
}

public static double area(double length, double breadth){


return length * breadth;
}
}

16 | P a g e
OUTPUT:

17 | P a g e
EXPERIMENT 15

AIM : Create a class Box that uses a parameterized constructor to initialize the
dimensions of a box. The dimensions of the Box are width, height, depth. The
class should have a method that can return the volume of the box. Create an
object of the Box class and test the functionalities.

SOURCE CODE:
public class LAB4Q1 {
public static void main(String[] args) {
Box box = new Box(7,8,9);
System.out.println("Volume = " + box.volume());
}
}
class Box{
private double width;
private double height;
private double depth;
public Box(double width, double height, double depth){
this.width = width;
this.height = height;
this.depth = depth;
}
public double volume(){
return width * height * depth;
}
}

OUTPUT :

18 | P a g e
EXPERIMENT 16

AIM : WAP to display the use of this keyword.

SOURCE CODE:
import java.util.Date;
public class LAB4Q2 {
public static void main(String[] args) {
Person p = new Person("James Gosling", 1955);
System.out.println(p.getName() + " is " + p.getAge() + " years old");
}
}
class Person{
private String name;
private int birthYear;
public Person(String name, int birthYear){
this.name = name;
this.birthYear = birthYear;
}
public int getAge(){
Date dt=new Date();
int year=dt.getYear();
int currentYear=year+1900;
int age = currentYear - birthYear;
return age;
}
public String getName(){
return name;
}
}

OUTPUT :

19 | P a g e
EXPERIMENT 17

AIM : Write a program that can count the number of instances created for the
class.

SOURCE CODE:
public class LABQ3 {
public static void main(String[] args) {
Student s1 = new Student("Priya", 120);
Student s2 = new Student("Sahil", 165);
Student s3 = new Student("Shreya", 210);
Student s4 = new Student("Mansha", 202);
Student s5 = new Student("Vivek", 217);
System.out.println("No. of Student objects created = " +
Student.countStudents());
}
}
class Student{
private String name;
private int rollno;
private static int no_of_students = 0;
public Student(String name, int rollno){
this.name = name;
this.rollno = rollno;
no_of_students++;
}
public static int countStudents(){
return no_of_students;
}
}

OUTPUT :

20 | P a g e
EXPERIMENT 18

AIM : Java program to get the cube of a given number using the static
method.

SOURCE CODE:
public class LAB4Q4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number = ");
double number = scanner.nextDouble();
System.out.println("Cube of the number = " + cube(number));
}

public static double cube(double number){


return number * number * number;
}
}

OUTPUT :

21 | P a g e
EXPERIMENT 19

AIM : WAP that implements method overriding.

SOURCE CODE:
public class Main {
public static void main(String[] args) {
Pet pet = new Pet("Shreya",8);
pet.describe();
Dog husky = new Dog("Neelnayan", 6, "Siberian Husky");
husky.describe();
}
}
class Pet{
protected String name;
protected int age;
public Pet(String name, int age){
this.name = name;
this.age = age;
}
public void describe(){
System.out.println(name + " is " + age + " years old, lovable pet");
}
}

class Dog extends Pet{


private String breed;
public Dog(String name, int age, String breed) {
super(name, age);
this.breed = breed;
}
@Override
public void describe() {
System.out.println(name + " is " + age + " years old, cute and faithful "+
breed);
}
}
22 | P a g e
OUTPUT :

23 | P a g e
EXPERIMENT 20

AIM : WAP to illustrate simple inheritence.

SOURCE CODE:
public class LAB5Q2 {
public static void main(String[] args) {
Car car = new Car("Toyota", "Petrol", 90);
Truck truck = new Truck("TATA", "Diesel", 120);
car.getSpeed();
truck.getSpeed();
}
}
class Vehicle{
private String fuel;
private double kmPerHour;
public Vehicle(String fuel, double kmPerHour){
this.fuel = fuel;
this.kmPerHour = kmPerHour;
}
public void getSpeed(){
System.out.println(getClass().getSimpleName() + " runs on "+ fuel + " with
an avg speed of " + kmPerHour + " km/h");
}
}

class Car extends Vehicle{


String brand;
public Car(String brand, String fuel, double kmPerHour) {
super(fuel, kmPerHour);
this.brand = brand;
}
}

class Truck extends Vehicle{


String brand;
public Truck(String brand, String fuel, double kmPerHour){

24 | P a g e
super(fuel, kmPerHour);
this.brand = brand;
}
}

OUTPUT :

25 | P a g e
EXPERIMENT 21

AIM : Write a program to implement multilevel inheritance

SOURCE CODE:
// Animal class
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

// Dog class extending Animal


class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

// Bulldog class extending Dog


class Bulldog extends Dog {
void displayInfo() {
System.out.println("Bulldog is a type of dog");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Bulldog bulldog = new Bulldog();
bulldog.displayInfo();
bulldog.bark();
bulldog.eat();
}
}

26 | P a g e
OUTPUT :

27 | P a g e
EXPERIMENT 22

AIM : Write a program to illustrate all uses of super keywords.

SOURCE CODE:
class Parent {
protected int value;

public Parent(int value) {


this.value = value;
}

public void printValue() {


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

class Child extends Parent {


private int value;

public Child(int parentValue, int childValue) {


super(parentValue); // Calling parent class constructor
this.value = childValue;
}

public void printValue() {


super.printValue(); // Calling parent class method
System.out.println("Child value: " + value);
}

public void accessParentField() {


System.out.println("Parent value from Child class: " + super.value);
}
}

public class Main {


public static void main(String[] args) {

28 | P a g e
Child child = new Child(10, 20);
child.printValue(); // Calling child class method
child.accessParentField(); // Accessing parent class field using super
keyword
}
}

OUTPUT :

29 | P a g e
EXPERIMENT 23

AIM : Write a program to show dynamic polymorphism and interface.

SOURCE CODE:
// Interface
interface Shape {
void draw();
}

// Concrete classes implementing the Shape interface


class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

class Triangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a triangle");
}
}

// Main class
public class PolymorphismExample {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();

30 | P a g e
shapes[1] = new Rectangle();
shapes[2] = new Triangle();

for (Shape shape : shapes) {


shape.draw();
}
}
}

OUTPUT :

31 | P a g e
EXPERIMENT 24

AIM : Write a Java program to show multithreaded producer and consumer


application.

SOURCE CODE:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;

class Producer implements Runnable {


private final BlockingQueue<Integer> queue;

public Producer(BlockingQueue<Integer> queue) {


this.queue = queue;
}

public void run() {


try {
for (int i = 1; i <= 10; i++) {
System.out.println("Producing: " + i);
queue.put(i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

class Consumer implements Runnable {


private final BlockingQueue<Integer> queue;

public Consumer(BlockingQueue<Integer> queue) {


this.queue = queue;
}

public void run() {

32 | P a g e
try {
while (true) {
int number = queue.take();
System.out.println("Consuming: " + number);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

public class ProducerConsumerExample {


public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

Producer producer = new Producer(queue);


Consumer consumer = new Consumer(queue);

Thread producerThread = new Thread(producer);


Thread consumerThread = new Thread(consumer);

producerThread.start();
consumerThread.start();
}
}

33 | P a g e
OUTPUT :

34 | P a g e
EXPERIMENT 25

AIM : Write an application that shows thread priorities.

SOURCE CODE:
public class ThreadPriorityExample {

public static void main(String[] args) {


Thread thread1 = new MyThread("Thread 1");
Thread thread2 = new MyThread("Thread 2");
Thread thread3 = new MyThread("Thread 3");

thread1.setPriority(Thread.MIN_PRIORITY); // Set the lowest priority


thread2.setPriority(Thread.NORM_PRIORITY); // Set the default priority
thread3.setPriority(Thread.MAX_PRIORITY); // Set the highest priority

thread1.start();
thread2.start();
thread3.start();
}

static class MyThread extends Thread {


public MyThread(String name) {
super(name);
}

public void run() {


for (int i = 0; i < 5; i++) {
System.out.println(getName() + " is running (" + i + ")" );
}
}
}
}

35 | P a g e
OUTPUT :

36 | P a g e
EXPERIMENT 26

AIM : Write an application that displays deadlock between threads.

SOURCE CODE:
public class DeadlockExample {
public static Object lock1 = new Object();
public static Object lock2 = new Object();

public static void main(String[] args) {


Thread thread1 = new Thread(() -> {
synchronized (lock1) {
System.out.println("Thread 1: Holding lock 1...");

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Thread 1: Waiting for lock 2...");


synchronized (lock2) {
System.out.println("Thread 1: Holding lock 1 and lock 2...");
}
}
});

Thread thread2 = new Thread(() -> {


synchronized (lock2) {
System.out.println("Thread 2: Holding lock 2...");

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

37 | P a g e
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (lock1) {
System.out.println("Thread 2: Holding lock 2 and lock 1...");
}
}
});

thread1.start();
thread2.start();
}
}

OUTPUT :

38 | P a g e
EXPERIMENT 27

AIM : Create a Customized Exception and also make use of all the 5 exception
keywords.

SOURCE CODE:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}

public void handle() {


try {
throw this;
} catch (CustomException ce) {
System.out.println("Handling CustomException...");
System.out.println("Exception message: " + ce.getMessage());
} finally {
System.out.println("Executing finally block...");
}
}
}

public class Main {


public static void testCustomException() {
try {
throw new CustomException("This is a customized exception.");
} catch (CustomException ce) {
System.out.println("Caught CustomException: " + ce.getMessage());
ce.handle();
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}

public static void main(String[] args) {


testCustomException();

39 | P a g e
}
}

OUTPUT :

40 | P a g e
EXPERIMENT 28

AIM : Write a Program to take care of Number Format Exception if user enters
values other than integer for calculating average marks of 2 students. The
name of the students and marks in 3 subjects are taken from the user while
executing the program. In the same Program write your own Exception classes
to take care of Negative values and values out of range (i.e. other than in the
range of 0-100).

SOURCE CODE:
import java.util.Scanner;

class NegativeValueException extends Exception {


public NegativeValueException(String message) {
super(message);
}
}

class OutOfRangeException extends Exception {


public OutOfRangeException(String message) {
super(message);
}
}

public class AverageMarksCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

String[] names = new String[2];


int[][] marks = new int[2][ 3];

try {
for (int i = 0; i < 2; i++) {
System.out.print("Enter the name of student " + (i + 1) + ": ");
names[i] = scanner.nextLine();

41 | P a g e
for (int j = 0; j < 3; j++) {
System.out.print("Enter the marks for subject " + (j + 1) + ": ");
String marksInput = scanner.nextLine();
marks[i][ j] = parseMarks(marksInput);
}
}

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


int totalMarks = 0;
for (int j = 0; j < 3; j++) {
totalMarks += marks[i][ j];
}

double averageMarks = (double) totalMarks / 3;


System.out.println("Average marks for " + names[i] + ": " +
averageMarks);
}
} catch (NumberFormatException e) {
System.out.println("Invalid marks entered. Please enter integer
values.");
} catch (NegativeValueException e) {
System.out.println(e.getMessage());
} catch (OutOfRangeException e) {
System.out.println(e.getMessage());
}
}

private static int parseMarks(String marksInput) throws


NegativeValueException, OutOfRangeException {
int marks = Integer.parseInt(marksInput);

if (marks < 0) {
throw new NegativeValueException("Negative marks are not allowed.");
}

if (marks < 0 || marks > 100) {


throw new OutOfRangeException("Marks should be in the range of 0-
100.");
}

42 | P a g e
return marks;
}
}

OUTPUT :

43 | P a g e
EXPERIMENT 29

AIM : Convert the content of a given file into the uppercase content of the
same file.

SOURCE CODE:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileContentToUpper {


public static void main(String[] args) {
String filePath = "C:\\IdeaProjects\\file\\src\\CodeFile.java";

try {
// Read the content of the file
BufferedReader reader = new BufferedReader(new
FileReader(filePath));
StringBuilder content = new StringBuilder();
String line;

while ((line = reader.readLine()) != null) {


content.append(line).append(" \n" );
}

reader.close();

// Convert the content to uppercase


String uppercaseContent = content.toString().toUpperCase();

// Write the uppercase content back to the file


BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write(uppercaseContent);
writer.close();

44 | P a g e
System.out.println("File content converted to uppercase successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

OUTPUT :

45 | P a g e
EXPERIMENT 30

AIM : Write a program in Java to sort the content of a given text file.

SOURCE CODE:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileSorter {

public static void main(String[] args) {


String fileName = "C:\\IdeaProjects\\file\\src\\CodeFile.java"; // Replace
with the name of your input file

List<String> lines = readLinesFromFile(fileName);


if (lines != null) {
Collections.sort(lines);
writeLinesToFile(fileName, lines);
System.out.println("File sorted successfully.");
} else {
System.out.println("Failed to read the file.");
}
}

private static List<String> readLinesFromFile(String fileName) {


List<String> lines = new ArrayList<>();

try (BufferedReader br = new BufferedReader(new FileReader(fileName)))


{
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();

46 | P a g e
return null;
}

return lines;
}

private static void writeLinesToFile(String fileName, List<String> lines) {


try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
for (String line : lines) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT :

47 | P a g e
EXPERIMENT 31

AIM : Write a program in Java to sort the content of a given text file.

SOURCE CODE:
1) JAVA CODE
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AnalogClockApplet extends Applet implements Runnable {

private Thread thread;


private SimpleDateFormat dateFormat;
private int centerX, centerY;
private int radius;
private int hourHandLength, minuteHandLength, secondHandLength;
private Point hourHandEnd, minuteHandEnd, secondHandEnd;

public void init() {


setSize(400, 400);
setBackground(Color.white);

// Set the dimensions and lengths of the clock hands


centerX = getSize().width / 2;
centerY = getSize().height / 2;
radius = Math.min(centerX, centerY) - 10;
hourHandLength = (int) (radius * 0.5);
minuteHandLength = (int) (radius * 0.8);
secondHandLength = (int) (radius * 0.9);

// Set the initial position of the clock hands

48 | P a g e
hourHandEnd = new Point(centerX, centerY);
minuteHandEnd = new Point(centerX, centerY);
secondHandEnd = new Point(centerX, centerY);

// Create a date format for displaying the time


dateFormat = new SimpleDateFormat("hh:mm:ss a");

// Start the clock update thread


thread = new Thread(this);
thread.start();
}

public void run() {


while (true) {
// Get the current time
Calendar calendar = Calendar.getInstance();
Date currentTime = calendar.getTime();

// Update the clock hands positions


updateClockHands(currentTime);

// Repaint the applet


repaint();

try {
// Delay for 1 second
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void updateClockHands(Date time) {


Calendar calendar = Calendar.getInstance();
calendar.setTime(time);

int hour = calendar.get(Calendar.HOUR);


int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

49 | P a g e
// Calculate the angles for each clock hand
double hourAngle = Math.toRadians(360 * ((hour % 12) + minute /
60.0) / 12);
double minuteAngle = Math.toRadians(360 * (minute + second / 60.0) /
60);
double secondAngle = Math.toRadians(360 * second / 60.0);

// Calculate the end positions for each clock hand


hourHandEnd.x = (int) (centerX + hourHandLength *
Math.sin(hourAngle));
hourHandEnd.y = (int) (centerY - hourHandLength *
Math.cos(hourAngle));

minuteHandEnd.x = (int) (centerX + minuteHandLength *


Math.sin(minuteAngle));
minuteHandEnd.y = (int) (centerY - minuteHandLength *
Math.cos(minuteAngle));

secondHandEnd.x = (int) (centerX + secondHandLength *


Math.sin(secondAngle));
secondHandEnd.y = (int) (centerY - secondHandLength *
Math.cos(secondAngle));
}

public void paint(Graphics g) {


// Clear the applet
g.clearRect(0, 0, getSize().width, getSize().height);

// Draw the clock outline


g.setColor(Color.black);
g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);

// Draw the clock hands


g.setColor(Color.blue);
g.drawLine(centerX, centerY, hourHandEnd.x, hourHandEnd.y);
g.setColor(Color.green);
g.drawLine(centerX, centerY, minuteHandEnd.x, minuteHandEnd.y);
g.setColor(Color.red);
g.drawLine(centerX, centerY, secondHandEnd.x, secondHandEnd.y);

50 | P a g e
// Display the current time
g.setColor(Color.black);
g.drawString(dateFormat.format(new Date()), 10, getSize().height - 10);
}

public void stop() {


thread = null;
}
}

2) HTML CODE:

<!DOCTYPE html>
<html>
<head>
<title>Analog Clock Applet</title>
</head>
<body>
<applet code="AnalogClockApplet.class" width="400" height="400">
Your browser does not support Java applets.
</applet>
</body>
</html>

51 | P a g e
EXPERIMENT 32

AIM : Write an Applet that illustrates how to process mouse click, enter, exit,
press and release events. The background color changes when the mouse is
entered, clicked, pressed, released or exited.

SOURCE CODE:
1) JAVA CODE
import java.awt.*;
import java.awt.event.*;

public class MouseEventsApplet extends java.applet.Applet implements


MouseListener {
private Color backgroundColor;

public void init() {


backgroundColor = Color.WHITE;
addMouseListener(this);
}

public void paint(Graphics g) {


setBackground(backgroundColor);
g.drawString("Click, enter, exit, press, or release the mouse", 20,
20);
}

public void mouseClicked(MouseEvent e) {


backgroundColor = Color.YELLOW;
repaint();
}

public void mouseEntered(MouseEvent e) {


backgroundColor = Color.GREEN;
repaint();
}

52 | P a g e
public void mouseExited(MouseEvent e) {
backgroundColor = Color.WHITE;
repaint();
}

public void mousePressed(MouseEvent e) {


backgroundColor = Color.BLUE;
repaint();
}

public void mouseReleased(MouseEvent e) {


backgroundColor = Color.RED;
repaint();
}
}

2) HTML CODE:

<html>
<body>
<applet code="MouseEventsApplet.class" width="400"
height="300"></applet>
</body>
</html>

53 | P a g e
EXPERIMENT 33

AIM : Develop a Scientific calculator using Swings

SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ScientificCalculator extends JFrame implements ActionListener {


private JTextField textField;

public ScientificCalculator() {
setTitle("Scientific Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);

textField = new JTextField(20);


textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.RIGHT);

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(5, 4, 5, 5));

String[] buttons = {
"7" , "8" , "9" , "/" ,
"4" , "5" , "6" , "*" ,
"1" , "2" , "3" , "-" ,
"0" , "." , "=" , "+",
"sin", "cos", "tan", "√"
};

for (String button : buttons) {


JButton btn = new JButton(button);
btn.addActionListener(this);
buttonPanel.add(btn);

54 | P a g e
}

getContentPane().setLayout(new BorderLayout());
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.CENTER);

pack();
setLocationRelativeTo(null);
}

@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
String currentText = textField.getText();

switch (action) {
case "=" :
try {
double result = evaluateExpression(currentText);
textField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
textField.setText("Error");
}
break;
case "sin":
double sinResult = Math.sin(Double.parseDouble(currentText));
textField.setText(String.valueOf(sinResult));
break;
case "cos":
double cosResult = Math.cos(Double.parseDouble(currentText));
textField.setText(String.valueOf(cosResult));
break;
case "tan":
double tanResult = Math.tan(Double.parseDouble(currentText));
textField.setText(String.valueOf(tanResult));
break;
case "√":
double sqrtResult = Math.sqrt(Double.parseDouble(currentText));
textField.setText(String.valueOf(sqrtResult));
break;

55 | P a g e
default:
textField.setText(currentText + action);
}
}

private double evaluateExpression(String expression) {


return new Object() {
int index = -1, ch;

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

boolean isDigit() {
return Character.isDigit(ch);
}

double parse() {
nextChar();
double x = parseExpression();
if (index < expression.length())
throw new RuntimeException("Unexpected: " + (char) ch);
return x;
}

double parseExpression() {
double x = parseTerm();
for (; ; ) {
if (eat('+'))
x += parseTerm();
else if (eat('-' ))
x -= parseTerm();
else
return x;
}
}

double parseTerm() {
double x = parseFactor();
for (; ; ) {

56 | P a g e
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.index;
if (eat('(')) {
x = parseExpression();
eat(')');
} else if (isDigit() || ch == '.') {
while (isDigit() || ch == '.')
nextChar();
x = Double.parseDouble(expression.substring(startPos, this.index));
} else {
throw new RuntimeException("Unexpected: " + (char) ch);
}

return x;
}

boolean eat(int charToEat) {


while (ch == ' ' )
nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}

57 | P a g e
}.parse();
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ScientificCalculator().setVisible(true);
}
});
}
}

OUTPUT:

58 | P a g e
EXPERIMENT 34

AIM : 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 SwingTextEditor extends JFrame implements ActionListener {


private JTextArea textArea;
private JFileChooser fileChooser;

public SwingTextEditor() {
setTitle("Swing Text Editor");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);

createMenuBar();
createTextArea();

setVisible(true);
}

private void createMenuBar() {


JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("File");


JMenuItem openMenuItem = new JMenuItem("Open");
openMenuItem.addActionListener(this);
JMenuItem saveMenuItem = new JMenuItem("Save");
saveMenuItem.addActionListener(this);
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(this);

fileMenu.add(openMenuItem);

59 | P a g e
fileMenu.add(saveMenuItem);
fileMenu.add(exitMenuItem);

menuBar.add(fileMenu);
setJMenuBar(menuBar);
}

private void createTextArea() {


textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane);
}

@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();

if (command.equals("Open")) {
openFile();
} else if (command.equals("Save")) {
saveFile();
} else if (command.equals("Exit")) {
System.exit(0);
}
}

private void openFile() {


if (fileChooser == null)
fileChooser = new JFileChooser();

int option = fileChooser.showOpenDialog(this);


if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line).append(" \n" );
}

60 | P a g e
reader.close();
textArea.setText(content.toString());
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error opening the file.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}

private void saveFile() {


if (fileChooser == null)
fileChooser = new JFileChooser();

int option = fileChooser.showSaveDialog(this);


if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(textArea.getText());
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error saving the file.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new SwingTextEditor());
}
}

61 | P a g e
OUTPUT:

62 | P a g e
EXPERIMENT 35

AIM : Create a servlet that recognizes visitor for the first time to a web
application and responds by saying “Welcome, you are visiting for the first
time”. When the page is visited for the second time ,it should say “Welcome
Back.

SOURCE CODE:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WelcomeServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession();


Integer visitCount = (Integer) session.getAttribute("visitCount");

if (visitCount == null) {
// First-time visitor
visitCount = 1;
session.setAttribute("visitCount", visitCount);
out.println("<h2>Welcome, you are visiting for the first time</h2>");
} else {
// Returning visitor
visitCount++;
session.setAttribute("visitCount", visitCount);

63 | P a g e
out.println("<h2>Welcome Back. This is your " + visitCount + "
visit.</h2>");
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
doGet(request, response);
}
}

64 | P a g e
EXPERIMENT 36

AIM : Create a servlet that uses Cookies to store the number of times a user
has visited your Servlet.

SOURCE CODE:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VisitCounterServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
// Get the cookies from the request
Cookie[] cookies = request.getCookies();

// Check if the cookies exist


if (cookies != null) {
// Find the cookie with the name "visitCount"
for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
// Increment the visit count and update the cookie value
int visitCount = Integer.parseInt(cookie.getValue()) + 1;
cookie.setValue(String.valueOf(visitCount));
response.addCookie(cookie);
break;
}
}
}

65 | P a g e
// If the "visitCount" cookie doesn't exist, create a new one
if (cookies == null || cookies.length == 0 || !hasVisitCountCookie(cookies))
{
Cookie visitCountCookie = new Cookie("visitCount", "1" );
visitCountCookie.setMaxAge(24 * 60 * 60); // Set cookie expiration time
to 24 hours
response.addCookie(visitCountCookie);
}

// Set the response content type


response.setContentType("text/html");

// Get the visit count from the cookie


int visitCount = getVisitCount(cookies);

// Generate the HTML response


PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Visit Counter</title></head>");
out.println("<body>");
out.println("<h1>Visit Counter</h1>");
out.println("<p>You have visited this page " + visitCount + " time(s).</p>");
out.println("</body>");
out.println("</html>");
}

private boolean hasVisitCountCookie(Cookie[] cookies) {


for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
return true;
}
}
return false;
}

private int getVisitCount(Cookie[] cookies) {


for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
return Integer.parseInt(cookie.getValue());
}

66 | P a g e
}
return 0;
}
}

67 | P a g e
EXPERIMENT 37

AIM : Create a simple Java Bean having bound and constrained properties.

SOURCE CODE:
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class PersonBean {


private String name;
private int age;

private PropertyChangeSupport propertyChangeSupport;

public PersonBean() {
propertyChangeSupport = new PropertyChangeSupport(this);
}

public String getName() {


return name;
}

public void setName(String name) {


String oldValue = this.name;
this.name = name;
propertyChangeSupport.firePropertyChange("name", oldValue, name);
}

public int getAge() {


return age;
}

public void setAge(int age) {


int oldValue = this.age;
this.age = age;
propertyChangeSupport.firePropertyChange("age", oldValue, age);
}

68 | P a g e
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener)


{
propertyChangeSupport.removePropertyChangeListener(listener);
}
}

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class Main {


public static void main(String[] args) {
PersonBean person = new PersonBean();

person.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Property changed: " + evt.getPropertyName());
System.out.println("Old value: " + evt.getOldValue());
System.out.println("New value: " + evt.getNewValue());
}
});

person.setName("John");
person.setAge(30);
}
}

69 | P a g e
OUTPUT:

70 | P a g e
EXPERIMENT 38

AIM : Write RMI based client-server programs.

SOURCE CODE:
1) Server.java:
import java.rmi.*;
import java.rmi.server.*;

public class Server extends UnicastRemoteObject implements


RemoteInterface {
public Server() throws RemoteException {
super();
}

public String sayHello() throws RemoteException {


return "Hello, client!";
}

public static void main(String[] args) {


try {
// Create an instance of the server
Server server = new Server();

// Bind the server object to the RMI registry


Naming.rebind("rmi://localhost/RemoteServer", server);

System.out.println("Server started.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

71 | P a g e
2) RemoteInterface.java:
import java.rmi.*;

public interface RemoteInterface extends Remote {


public String sayHello() throws RemoteException;
}

3) Client.java:
import java.rmi.*;

public class Client {


public static void main(String[] args) {
try {
// Lookup the server object in the RMI registry
RemoteInterface server = (RemoteInterface)
Naming.lookup("rmi://localhost/RemoteServer");

// Invoke a method on the remote server object


String message = server.sayHello();
System.out.println("Server says: " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}

72 | P a g e
EXPERIMENT 39

AIM : Write programs of database connectivity using JDBC-ODBC drivers.

SOURCE CODE:
import java.sql.*;

public class JdbcOdbcExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
static final String DB_URL = "jdbc:odbc:myDatabase";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM employees";
ResultSet rs = stmt.executeQuery(sql);

// Process the result set


while (rs.next()) {
// Retrieve by column name
73 | P a g e
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");

// Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}

// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}

74 | P a g e
EXPERIMENT 40

AIM : Write a program that read from a file and write to file.

SOURCE CODE:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReadWriteExample {


public static void main(String[] args) {
String inputFile = " C:\IdeaProjects\file\src\CodeFile.java ";
String outputFile = " C:\IdeaProjects\file\src\CodeFile.java ";

try {
// Read from the input file
BufferedReader reader = new BufferedReader(new
FileReader(inputFile));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append(" \n" );
}
reader.close();

// Write to the output file


BufferedWriter writer = new BufferedWriter(new
FileWriter(outputFile));
writer.write(content.toString());
writer.close();

System.out.println("File read and write operations completed


successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());

75 | P a g e
}
}
}

OUTPUT:

76 | P a g e

You might also like