You are on page 1of 75

Department of Computer Science & Engineering

Faculty of Technology & Engineering

SS-BE-III

Advance Java Technologies Lab File


(CSE1606L)
Jan-June 2022

Course Coordinator: Submitted By:


Dr Kanika Lakhani Student Name: Keyur B Ninama
Assistant Professor PRN: 2018033800121251
Contact No.

The Maharaja Sayajirao University of Baroda


Table of Contents

Lab Teacher’s
Contents Date
No Sign
Basics of Core Java 24-01-2022

1. Write a program to find the factorial of a given


number.
2. Write a program to print Fibonacci series up to
a certain limit.
3. Write a program to swap the contents of two
variables without using third variable.
4. Write a program to check if a given number is
even or odd.
1. 5. Write a program to check if the entered three-
digit number is palindrome or not.
6. Create an area menu to find the area of different
shapes using switch case.
7. Write a program to find Armstrong number
between 100 and 1000.
8. Write a program to create multiple classes
where the details of a student are printed with
the object of the class not defining main
method.
Arrays & Strings 31-01-2022

1. Write a program to find the multiplication of


two matrices of dimensions 3*3.
2. Write a program to input strings from the user
2. and display the strings in alphabetic order.
3. Write a program to convert the given string to
uppercase and display them in group of 5
characters.
4. Write a program to use different functions of

2
StringBuffer class.
5. Write a program to sort a given one-
dimensional array using Insertion sort.
Inheritance & Interfaces 07-02-2022

1. Write a program to create a class Square.


Derive a subclass RoundSquare of class Square.
Derive another class Rhombus from
RoundSquare. Create appropriate objects for
the classes with attributes and methods.
2. Write a program to create four classes
Furniture, Chair, bed and Table. Classes Chair,
Bed and Table inherits class Furniture and
overrides method use(). From main method
dynamically call the object of classes Chair,
Bed and Table with the object of Furniture
class.
3. Write a program to create a class with two
3. methods with the same naming add(), one
accepting two integer parameters and other
accepting two double parameters. When
method is called, the appropriate method should
be selected depending on the parameter passed.
4. Write a program that creates a user interface to
perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2.
The division of Num1 and Num2 is displayed
in the Result field when the Divide button is
clicked. If Num1 or Num2 were not an integer,
the program would throw a
NumberFormatException. If Num2 were Zero,
the program would throw an Arithmetic
Exception Display the exception in a message
dialog box.
Multithreading & Exception Handling 14-02-2022

1. Write a program to create a simple thread by


extending Thread class.
4. 2. Write a program to create and run simple thread
by implementing Runnable interface.
3. Write a program to create multiple threads.
4. Write a multithreaded program that sets the

3
priority of threads and gets the name of threads.
5. Write a multithreaded program that displays
whether the thread is alive or not.
6. Write a multithreaded program using isAlive()
and join() methods.
7. Write a program to enter the details of Bride
and Groom. Create user defined exceptions
GroomException and BrideException to display
the appropriate messages if the age of groom
and bride does not qualify for the marriage.
8. Write a program to enter two integers from the
user and display the division of these two
numbers. Handle all the exceptions for invalid
arguments passed.
Collections in Java 21-02-2022

1. Write a program to create an ArrayList to add


elements in the ArrayList. Display the size and
the contents of the ArrayList. Change the
contents of ArrayList by adding few elements
at particular indices. Also use remove() method
to remove the elements at particular indices.
2. Write a program to create a Linked list using
the objects of LinkedList class to display the
first and the last element of the list.
5
3. Write a program to display the methods of
HashSet class and TreeSet class using switch.
4. Write a program that push the elements in a
stack using the objects of Stack class. Display
the elements of the stack and then pop few
elements. Display the popped element out of
the stack and display the entire stack after
popping elements.
5. Write a program that displays the contents of a
hashtable using the objects of Hashtable class.
Swings & AWT 21-03-2022

1. Create a customized functional scientific


6 calculator as shown in the picture. Use Java
Swings, Awt Components, JApplet and
Collections. Use the concept of “Array of
Buttons” for placing the buttons on the

4
calculator. You can also use GridBag layout for
the designing purpose.

GUI, Event Handling & Swings 28-03-2022


1. To creates User Interface to perform Integer
Divisons. The user enters two numbers in text
fields, Num1 and Num2.The division of Num1
and Num2 is displayed in the result field when
the divide button clicked. If Num1 or Num2
were not integer, the program would throw a
NumberFormatException, If Num2 is Zero, and
the program would throw an Athematic
Exception. Display the Exception in message
box.
2. Write a java program that simulates a traffic
7 light. The program lets the user select one of
three lights: Red, Yellow or Green with radio
buttons. On selecting a button an appropriate
message with “STOP” or “READY” or ”GO”
should appear above the buttons in selected
color. Initially, there is no message shown.
3. Write a java program that handles all mouse
events and shows the event name at the center
of the window when a mouse event is fired. Use
adapter classes.
4. Write a java program to demonstrate the key
event handlers.
GUI, Swings & JDBC 04-04-2022

1. Write a program to send an email. Write a


program to create a list using Swing Controls.
2. Create a table using swing controls and show its
8
database connectivity.
3. Write a program to create progress bar using
Swing Controls.
4. Create a split pane swing control.

5
ASSIGNMENT-1
1. Write a program to find the factorial of a number.

Code:
public class Factorial {
int factorial(int n)
{
return (n == 0 || n == 1) ? 1 : n * factorial(n-1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Factorial f = new Factorial();
int num = 5;
System.out.println("Factorial of "+ num + " is " +
f.factorial(num));
}
}
Output:

2. Write a program to find Fibonacci series up to a certain limit.


Code:
public class Fibonacci {
static int fib(int n) {
if (n<=1)
return n;
else
return fib(n-1) + fib(n-2);
}

public static void main(String args[])


{
int num =10;
System.out.println(fib(num));
}
}
Output:

3. Write a program to swap contents of two variables without using third

variable.
Code:
public class SwapNumber {
public static void main(String[] args)
{
int x = 10;
int y = 5;

// Code to swap 'x' and 'y'


x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5

System.out.println("After swaping:"
+ " x = " + x + ", y = " + y);
}
}

Output:
4.Write a program to check if a given number is even or odd.
Code:
public class EvenOdd {

public static boolean isEven(int n)


{
return (n % 2 == 0);
}

// Driver code
public static void main(String[] args)
{
int n = 101;
if(isEven(n) == true)
System.out.print("Even");
else
System.out.print("Odd");
}
}
Output:

5. Write a program to check if the entered three digit number is

palindrome or not.
Code:
public class PalindromeNumber {
static int reverseDigits(int num)
{
int rev_num = 0;
while (num > 0) {
rev_num = rev_num * 10 + num % 10;
num = num / 10;
} return rev_num; }

static int isPalindrome(int n)


{

int rev_n = reverseDigits(n);

if (rev_n == n)
return 1;
else
return 0;
}

public static void main(String []args)


{
int n = 488;
System.out.println("Is " + n + " a Palindrome number? -> " +
(isPalindrome(n) == 1 ? "true" : "false"));

n = 101;

System.out.println("Is " + n + " a Palindrome number? -> " +


(isPalindrome(n) == 1 ? "true" : "false"));
}

}
Output:

6. Create an area menu to find the area of different shapes using a switch

case.
Code:

import java.util.Scanner;
public class ShapeArea {

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("Enter c to calculate area of circle");


System.out.println("Enter s to calculate area of square");
System.out.println("Enter r to calculate area of rectangle");
System.out.print("Enter your choice: ");
char choice = in.next().charAt(0);

switch(choice) {
case 'c':
System.out.print("Enter radius of circle: ");
double r = in.nextDouble();
double ca = (22 / 7.0) * r * r;
System.out.println("Area of circle = " + ca);
break;

case 's':
System.out.print("Enter side of square: ");
double side = in.nextDouble();
double sa = side * side;
System.out.println("Area of square = " + sa);
break;

case 'r':
System.out.print("Enter length of rectangle: ");
double l = in.nextDouble();
System.out.print("Enter breadth of rectangle: ");
double b = in.nextDouble();
double ra = l * b;
System.out.println("Area of rectangle = " + ra);
break;

default:
System.out.println("Wrong choice!");
}
}
}
7.Write a program to find Armstrong number between 100 and 1000.
Code:

import java.util.Scanner;
import java.lang.Math;
public class AmstrongNumber {

static boolean isArmstrong(int n)


{
int temp, digits=0, last=0, sum=0;
temp=n;
while(temp>0){
temp = temp/10;
digits++;
}

temp = n;
while(temp>0)
{
last = temp % 10;
sum += (Math.pow(last, digits));
temp = temp/10;
}
if(n==sum) {
return true;
}
else {
return false;
}

public static void main(String args[]){


System.out.println("Armstrong Number between 100 and 1000 are: ");
for(int i=100; i<1000; i++) {

if(isArmstrong(i)) {
System.out.print(i+ ", ");
}

} } }
Output:

8. Write a program to create multiple classes where the details of a student

are printed with the object of the class not defining maid method.
Code:

import java.util.Scanner;

class Students {

String name,course;
int age;
Scanner scan = new Scanner(System.in);

void getDetails(){

System.out.print("Enter Student name : ");


name = scan.nextLine();

System.out.print("\nEnter student age : ");


age = scan.nextInt();

System.out.println("\nEnter course : ");


course = scan.next();
}

public class Student {


public static void main(String[] args) {
Students s1 = new Students();
s1.getDetails();
System.out.println("Student Info \n Name : "+s1.name+"\n Age :
"+s1.age+"\n Course : "+s1.course);
}
}

Output:
Name: Keyur B Niama RollNo:512032

Lab Assignment-2
Arrays and Strings
1. Write a program to find the multiplication of two matrices of dimensions 3*3.
Code:
public class MatrixMultiplication {

public static void main(String args[]){

int a[][]={{1,2,3},{4,5,7},{7,8,9}};

int b[][]={{1,2,3},{4,5,7},{7,8,9}};

int c[][]=new int[3][3];

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

for(int j=0;j<3;j++){

c[i][j]=0;

for(int k=0;k<3;k++) {

c[i][j]+=a[i][k]*b[k][j];

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

System.out.println();

Output:
Name: Keyur B Niama RollNo:512032

2. Write a program to input strings from the user and display the strings in alphabetic order.
Code:

import java.util.Scanner;
public class AlphabeticOrder
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);

System.out.print("Enter number of strings you would like to enter:");


count = scan.nextInt();

String str[] = new String[count];


Scanner scan2 = new Scanner(System.in);
Name: Keyur B Niama RollNo:512032

System.out.println("Enter the Strings one by one:");


for(int i = 0; i < count; i++)
{
str[i] = scan2.nextLine();
}
scan.close();
scan2.close();

for (int i = 0; i < count; i++)


{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}

System.out.print("Strings in Sorted Order:");


for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
}
}

Output:
Name: Keyur B Niama RollNo:512032

3. Write a program to convert the given string to uppercase and display them in group of 5
characters.

Code:
public class StringInUppercase{

public static void main(String args[]){

String s1="hellostring";
String s1upper=s1.toUpperCase();

char[] ch=s1upper.toCharArray();

for(int i=0;i<ch.length;i++){

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

}
}
}

Output:
Name: Keyur B Niama RollNo:512032

4. Write a program to use different functions of String Buffer class.


Code:
class stringbuffer {

public static void main(String[] args)


{
StringBuffer s = new StringBuffer("ArrayandString");

int p = s.length();
int q = s.capacity();
System.out.println("Length of string ="+ p);//Length
System.out.println("Capacity of string =" + q);//Capacity
s.append("Assignment");
System.out.println("String : "+ s);
s.append(2);
System.out.println("String : "+ s);//Append

char arr[] = { 'p', 'a', 'w', 'a', 'n' };


s.insert(2, arr);
Name: Keyur B Niama RollNo:512032

System.out.println("Insert New String: "+ s);//Insert

s.reverse();
System.out.println("Reverse String : "+ s);//Reverse

}
}

Output:

5. Write a program to sort a given one-dimensional array using Insertion sort.


Code:
class InsertionSort {

void sort(int arr[])

int n = arr.length;

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

int key = arr[i];

int j = i - 1;
Name: Keyur B Niama RollNo:512032

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

static void printArray(int arr[])

int n = arr.length;

for (int i = 0; i < n; ++i)

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

System.out.println();

public static void main(String args[])

int arr[] = { 55, 78, 1, 0, 99 };

InsertionSort ob = new InsertionSort();

ob.sort(arr);

printArray(arr);

Output:
Name: Keyur B Niama RollNo:512032
Name: Keyur B Niama Roll No:512032

Lab Assignment-3
Inheritance & Interfaces

1. Write a program to create a class Square. Derive a subclass Round Square of class
Rectangle. Derive another class Rhombus from Round-square. Create appropriate
objects for the classes with attributes and methods.
Code:
class Rectangle {

int length = 10;

void display1() {

System.out.println("Length of Square is :"+length);

class RoundSquare extends Rectangle{

int borderRadius = 5;

void display2() {

System.out.println("Border-Radius of RoundSquare is: "+borderRadius);

class Rombus extends RoundSquare{

int diagonallength = 19;

void display3() {

System.out.println("Diagonal length of Rombus is: "+diagonallength);

}
Name: Keyur B Niama Roll No:512032

public class p1{

public static void main(String arg[]) {

Rombus r = new Rombus();

r.display1();

r.display2();

r.display3();

}
Output:

2. Write a program to create four classes Furniture, Chair, bed and Table. Classes
Chair, Bed and Table inherits class Furniture and overrides method use(). From main
method dynamically call the object of classes Chair, Bed and Table with the object of
Furniture class.
Code:
class Furniture{

void use() {

System.out.println("Furniture Gives a Complete design to Home");

class Chair extends Furniture{

void use() {
Name: Keyur B Niama Roll No:512032

System.out.println("Chiar is a furniture used to sit on it");

class Bed extends Furniture{

void use() {

System.out.println("Bed is a furniture used to sleep");

class Table extends Furniture{

void use() {

System.out.println("Table is a furniture used for Work or Study ");

public class MainClass{

public static void main(String arg[]) {

Furniture c = new Chair();

c.use();

Furniture b = new Bed();

b.use();

Furniture t = new Table();

t.use();

}
Name: Keyur B Niama Roll No:512032

Output:

3.Write a program to create a class with two methods with the same naming add(),
one accepting two integer parameters and other accepting two double parameters.
When method is called, the appropriate method should be selected depending on the
parameter passed.
Code:
class Addition {

public int add(int a, int b)

int sum = a + b;

return sum;

public double add(double a, double b)

double sum = a + b ;

return sum;

public class MethodOverloading {

public static void main(String[] args)

{
Name: Keyur B Niama Roll No:512032

Addition ob = new Addition();

int sum1 = ob.add(21, 92);

System.out.println("sum of the two integer value :"+ sum1);

double sum2 = ob.add(154, 281);

System.out.println("sum of the three integer value :" + sum2);

Output:

4. Write a program that creates a user interface to perform integer divisions. The user
enters two numbers in the text fields, Num1 and Num2. The division of Num1 and
Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or
Num2 were not an integer, the program would throw a NumberFormatException. If
Num2 were Zero, the program would throw an Arithmetic Exception Display the
exception in a message dialog box.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BuildGUI extends JFrame implements ActionListener {
Name: Keyur B Niama Roll No:512032

JFrame actualWindow;
JPanel container;
JTextField txt_num1, txt_num2, txt_result;
JButton btn_div;

BuildGUI() {
actualWindow = new JFrame(" ");
container = new JPanel();
container.setLayout(new FlowLayout());

txt_num1 = new JTextField(20);


txt_num2 = new JTextField(20);
txt_result = new JTextField(20);

btn_div = new JButton("Divide");


btn_div.addActionListener(this);

container.add(txt_num1);
container.add(txt_num2);
container.add(btn_div);
container.add(txt_result);

actualWindow.add(container);
actualWindow.setSize(300, 300);
actualWindow.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int num1, num2;
try {
num1 = Integer.parseInt(txt_num1.getText());
Name: Keyur B Niama Roll No:512032

num2 = Integer.parseInt(txt_num2.getText());
txt_result.setText(num1/num2+"");
}
catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(actualWindow,"Please do enter
only integers");
}
catch(ArithmeticException ae) {
JOptionPane.showMessageDialog(actualWindow,"Divisor can not
be ZERO");
}
}
}
public class Assignment3_4{
public static void main(String[] args) {
new BuildGUI();
}
}

Output:
Name: Keyur B Niama Roll No:512032
Name: Keyur B Niama PRN:2018033800121251

Lab Assignment-4

Multi threading & Exception Handling


1. Write a program to create a simple thread by extending Thread class.

Code:

class Assignment4_1 extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Assignment4_1 t1=new Assignment4_1();

t1.start();

Output:

2. Write a program to create and run simple thread by implementing Runnable


interface.

Code:

class Assignment4_2 implements Runnable{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Assignment4_2 m1=new Assignment4_2();


Name: Keyur B Niama PRN:2018033800121251

Thread t1 =new Thread(m1);

t1.start();

Output:

3. Write a program to create multiple threads.

Code:

class MultiThread implements Runnable {

String name;

Thread t;

MultiThread (String threadname){

name = threadname;

t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start();

public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println(name + ": " + i);

Thread.sleep(1000);

}catch (InterruptedException e) {

System.out.println(name + "Interrupted");
Name: Keyur B Niama PRN:2018033800121251

System.out.println(name + " exiting.");

class Assignment4_3 {

public static void main(String args[]) {

new MultiThread("One");

new MultiThread("Two");

new MultiThread("Three");

try {

Thread.sleep(10000);

} catch (InterruptedException e) {

System.out.println("Main thread Interrupted");

System.out.println("Main thread exiting.");

Output:
Name: Keyur B Niama PRN:2018033800121251

4. Write a multithreaded program that sets the priority of threads and gets the
name of threads.

Code:

class Assignment4_4 extends Thread {

public void run()

System.out.println("Inside run method");

public static void main(String[] args)

Assignment4_4 t1 = new Assignment4_4();

Assignment4_4 t2 = new Assignment4_4();

Assignment4_4 t3 = new Assignment4_4();

System.out.println("t1 thread priority : " + t1.getPriority());


Name: Keyur B Niama PRN:2018033800121251

System.out.println("t2 thread priority : " + t2.getPriority());

System.out.println("t3 thread priority : " + t3.getPriority());

t1.setPriority(2);

t2.setPriority(5);

t3.setPriority(8);

System.out.println("t1 thread priority : " + t1.getPriority());

System.out.println("t2 thread priority : " + t2.getPriority());

System.out.println("t3 thread priority : " + t3.getPriority());

System.out.println("Currently Executing Thread : " +


Thread.currentThread().getName());

System.out.println("Main thread priority : " +


Thread.currentThread().getPriority());

Thread.currentThread().setPriority(10);

System.out.println("Main thread priority : " +


Thread.currentThread().getPriority());

Output:
Name: Keyur B Niama PRN:2018033800121251

5. Write a multithreaded program that displays whether the thread is alive or not.

Code:

public class Assignment4_5 extends Thread {

public void run()

System.out.println("Thread1");

try {

Thread.sleep(300);

catch (InterruptedException ie) {

System.out.println("Thread2");

public static void main(String[] args)

Assignment4_5 c1 = new Assignment4_5();

Assignment4_5 c2 = new Assignment4_5();

c1.start();

// c2.start();

System.out.println(c1.isAlive());

System.out.println(c2.isAlive());

Output:
Name: Keyur B Niama PRN:2018033800121251

6. Write a multithreaded program using isAlive() and join() methods.

Code:

class MyRunnableClass implements Runnable{

@Override

public void run() {

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

System.out.println(Thread.currentThread().getName() + " i - " + i);

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

public class Assignment4_6 {

public static void main(String[] args) {

Thread t1 = new Thread(new MyRunnableClass(), "t1");

Thread t2 = new Thread(new MyRunnableClass(), "t2");

Thread t3 = new Thread(new MyRunnableClass(), "t3");

t1.start();

t2.start();

// t3.start();

System.out.println("t1 Alive - " + t1.isAlive());


Name: Keyur B Niama PRN:2018033800121251

System.out.println("t2 Alive - " + t2.isAlive());

System.out.println("t3 Alive - " + t3.isAlive());

try {

t1.join();

t2.join();

t3.join();

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("t1 Alive - " + t1.isAlive());

System.out.println("t2 Alive - " + t2.isAlive());

System.out.println("t3 Alive - " + t3.isAlive());

System.out.println("Processing finished");

Output:
Name: Keyur B Niama PRN:2018033800121251

7. Write a program to enter the details of Bride and Groom. Create user defined
exceptions GroomException and BrideException to display the appropriate
messages if the age of groom and bride does not qualify for the marriage.

Code:

import java.util.Scanner;

class BriderException extends Exception

BriderException(String str)

super(str);

class GroomException extends Exception

private static final long serialVersionUID = 1L;

GroomException(String str)

super(str);

public class Assignment4_7

static int bage;

static int gage;

public static void main(String[] args)

try (Scanner s = new Scanner(System.in)) {


Name: Keyur B Niama PRN:2018033800121251

System.out.println("Enter Bride age");

bage = s.nextInt();

System.out.println("Enter Groom age");

gage = s.nextInt();

try

if(gage < 18 )

throw new GroomException("\n Groom doesn't Eligible for the Marriage");

else if(bage <21)

throw new BriderException("\n Bride doesn't Eligible for the Marriage


");

else

System.out.println("Both are Eligible for the Marriage….");

catch(Exception e)

System.out.println("Caught an Exception: \n "+e);

Output:
Name: Keyur B Niama PRN:2018033800121251

8. Write a program to enter two integers from the user and display the division of
these two numbers. Handle all the exceptions for invalid arguments passed.

Code:

import java.util.*;

class Assignment4_8 {

public static void main(String[] args)

int a;

int b;

Scanner s = new Scanner(System.in);

System.out.println("Enter a Number:");

a = s.nextInt();

System.out.println("Enter a Number:");

b = s.nextInt();

try {

System.out.println(a / b);

catch (ArithmeticException e) {

System.out.println(

"Divided by zero operation cannot possible");

Output:
Name: Keyur B Niama PRN:2018033800121251

Lab Assignment-5

Collection in Java
1.Write a program to create an ArrayList to add elements in the ArrayList.
Display the size and the contents of the ArrayList. Change the contents of
ArrayList by adding few elements at particular indices. Also use remove() method
to remove the elements at particular indices.

Code:

import java.util.*;

public class collection_ArrayList {

public static void main(String arg[]) {

ArrayList<String> A = new ArrayList<>();

A.add("Java");

A.add("Python");

A.add("C++");

System.out.println("Size of List:"+A.size());

for(String str : A)

System.out.print(str + " ");

A.set(0, "AdvanceJava");

A.set(2, "C");

System.out.println("After the Change Content of ArrayList:" );

for(String str : A)

System.out.print( str + " ");


Name: Keyur B Niama PRN:2018033800121251

System.out.println();

A.remove(1);

System.out.println("After the Index Removal :"+ A);

A.remove("C");

System.out.println("After the Element Removal:"+ A);

Output:

1. Write a program to create a Linked list using the objects of LinkedList class
to display the first and the last element of the list.

Code:

import java.util.*;

public class collection_LinkedList {

public static void main(String arg[]) {

LinkedList<String> list = new LinkedList<>();

list.add("application Layer");
Name: Keyur B Niama PRN:2018033800121251

list.add("presentation Layer");

list.add("session Layer");

list.add("Transport Layer");

list.add("Network layer");

list.add("Data Link Layer");

list.add("Physical Layer");

System.out.println("First Element of List:"+ list.getFirst());

System.out.println("Last Element of List:"+ list.getLast());

Output:

3.Write a program to display the methods of HashSet class and TreeSet class using
switch.

Code:

import java.util.*;

public class collection_hashset_treeset {

public static void main(String arg[]) {

Scanner scan = new Scanner(System.in);

System.out.println("Menu");

System.out.println("1.HashSet");
Name: Keyur B Niama PRN:2018033800121251

System.out.println("2.TreeSet");

System.out.println("3.Exit");

System.out.println("Enter Choice:");

int choice = scan.nextInt();

switch(choice) {

case 1:

HashSet<String> hs = new HashSet<>();

hs.add("computer network");

hs.add("Operating System");

hs.add("Complier Design");

System.out.println("List:" + hs);

break;

case 2:

TreeSet<String> ts = new TreeSet<>();

ts.add("CN");

ts.add("OS");

ts.add("CD");

System.out.println("List:" + ts);

break;

case 3:

System.exit(0);

default :

System.out.println("Enter Wrong Choice !!!1");

}
Name: Keyur B Niama PRN:2018033800121251

Output:

4.Write a program that push the elements in a stack using the objects of Stack
class. Display the elements of the stack and then pop few elements. Display the
popped element out of the stack and display the entire stack after popping
elements.

Code:

import java.util.*;

public class collection_Stack {

public static void main(String args[])

Stack<Integer> stack = new Stack<Integer>();

stack.push(10);
Name: Keyur B Niama PRN:2018033800121251

stack.push(15);

stack.push(30);

stack.push(20);

stack.push(5);

System.out.println("Initial Stack: " + stack);

System.out.println("Popped element: " + stack.pop());

System.out.println("Popped element: " + stack.pop());

System.out.println("Stack after pop operation " + stack);

Output:

5.Write a program that displays the contents of a hashtable using the objects of
Hash table class..

Code:

import java.util.*;
Name: Keyur B Niama PRN:2018033800121251

public class collection_hashtable {

public static void main(String args[])

Hashtable<Integer, String> ht1 = new Hashtable<>();

Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>();

ht1.put(1, "one");

ht1.put(2, "two");

ht1.put(3, "three");

ht2.put(4, "four");

ht2.put(5, "five");

ht2.put(6, "six");

System.out.println("Mappings of ht1 : " + ht1);

System.out.println("Mappings of ht2 : " + ht2);

Output:
Name: Keyur B Niama PRN:2018033800121251

Lab Assignment- 6

1. Create a customized functional Scientific Calculator as show in the picture Use


Java Swings, AWT Components, JApplets and Collections. Use the Concept of Array
of Buttons For placing the button one the calculator. You can also use GridBag
Layout for the designing purpose

Code:

import java.awt.Color;

import java.awt.Font;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.event.TextEvent;

import java.awt.event.TextListener;

import javax.swing.BorderFactory;

import javax.swing.BoxLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.SwingConstants;

class CalculatorLayout implements ActionListener,KeyListener,TextListener {

JFrame frame;

String set1Icon[];

String set2Icon[];
Name: Keyur B Niama PRN:2018033800121251

// String set3Icon[];

String set4Icon[];

JPanel mainPanel;

JPanel set1Panel;

JPanel set1ChildPanel1;

JPanel set2Panel;

JPanel set3Panel;

JPanel set1ChildPanel2;

JButton set1[];

JButton set2[];

JButton set3[];

JButton set4[];

JPanel screenPanel;

JTextField screen;

CalculatorLayout(){

//Frame

frame = new JFrame("Scientific Calculator");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

mainPanel = new JPanel();

mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.PAGE_AXIS));

frame.setLayout(new GridLayout());

frame.add(mainPanel);

//Main Screen

screenPanel = new JPanel(new GridLayout());

screen = new JTextField();

screen.addActionListener(this);

screen.setHorizontalAlignment(JTextField.RIGHT);
Name: Keyur B Niama PRN:2018033800121251

//On resizing add to frame listener

screenPanel.add(screen);

screen.setEditable(false);

screen.setHorizontalAlignment(SwingConstants.RIGHT);

screen.setFont(new Font("Times New Roman", Font.BOLD, 90));

mainPanel.add(screenPanel);

//

set1Icon = new String[]{"7","8","9","4","5","6","1","2","3","+/-


","0","."};

set2Icon = new String[] {"Start","Stop"};

// set3Icon = new String[] {};

set4Icon = new String[] {"*","-


","+","=","/","^","","%","1/x","x^2","x^3","sqrt(x)","log","10^x","CE","DEL"};

//Number Panel1

set1Panel = new JPanel();

set1Panel.setLayout(new BoxLayout(set1Panel,BoxLayout.X_AXIS));

set1ChildPanel1 = new JPanel(new GridLayout(4,3,10,10));

set1 = new JButton[set1Icon.length];

setIcon(set1,set1Icon);

addToPanel(set1,set1ChildPanel1);

set1Panel.add(set1ChildPanel1);

//Panel 2 advance calculation

set2Panel = new JPanel(new GridLayout(1,1,10,10));

set2Panel.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));

set2Panel.setAlignmentY(50);
Name: Keyur B Niama PRN:2018033800121251

set2 = new JButton[set2Icon.length];

setIcon(set2,set2Icon);

addToPanel(set2,set2Panel);

//Panel 3 Operators

// set3Panel = new JPanel(new GridLayout(1,6,10,10));

//

// set3 = new JButton[set3Icon.length];

// setIcon(set3,set3Icon);

// addToPanel(set3,set3Panel);

//Panel 4 Operators

set1ChildPanel2 = new JPanel(new GridLayout(4,1,10,10));

set4 = new JButton[set4Icon.length];

setIcon(set4,set4Icon);

addToPanel(set4,set1ChildPanel2);

set1Panel.add(set1ChildPanel2);

//adding to frame

mainPanel.add(set2Panel);

// mainPanel.add(set3Panel);

mainPanel.add(set1Panel);

frame.setVisible(true);

frame.setSize(500, 500);

frame.setLocation(800, 100);
Name: Keyur B Niama PRN:2018033800121251

//Set Icons

public void setIcon(JButton button[],String icon[]) {

for(int i = 0;i<button.length;i++) {

button[i] = new JButton(icon[i]);

button[i].addActionListener(this);

//Add to Panel

public static void addToPanel(JButton button[],JPanel panel) {

for(int i = 0;i<button.length;i++) panel.add(button[i]);

///EVENT LISTENER METHODS

//ActionEventListener

public void actionPerformed(ActionEvent e) {

JButton obj = (JButton)e.getSource();

String op = obj.getText();

ExpressionEvaluation exp = new ExpressionEvaluation();

int num = 0;

try {

num = Integer.parseInt(op);

op = "num";

catch(Exception exc) {

double ans,num1,num2;

switch(op) {
Name: Keyur B Niama PRN:2018033800121251

case "num": String s = screen.getText();

s += num;

screen.setText(s);

break;

case "CE" :

screen.setText("");

break;

case "log":

double val = Double.parseDouble(screen.getText());

ans = Math.log(val);

screen.setText("log("+val+") = "+ans);

break;

case "+":

screen.setText( screen.getText() + "+");

screen.requestFocus(true);

break;

case "*":

screen.setText( screen.getText() + "*");

screen.requestFocus(true);

break;

case "-":

screen.setText( screen.getText() + "-");

screen.requestFocus(true);

break;

case "/":

screen.setText( screen.getText() + "/");

screen.requestFocus(true);

break;

case "%":

screen.setText( screen.getText() + "%");


Name: Keyur B Niama PRN:2018033800121251

screen.requestFocus(true);

break;

case ".":

screen.setText( screen.getText() + ".");

screen.requestFocus(true);

break;

case "+/-":

String str = screen.getText();

int len = str.length();

if(len == 0) screen.setText("-");

else if( str.charAt(len-1) == '+' ||


(str.charAt(len-1) >= 48 && str.charAt(len-1) <= 57 )) {

if(!(str.charAt(len-1) >= 48 &&


str.charAt(len-1) <= 57 ))

str = str.substring(0, len-1);

str += '-';

screen.setText(str);

else if(str.charAt(len-1) == '-') {

str = str.substring(0, len-1);

str += '+';

screen.setText(str);

screen.requestFocus(true);

break;

case "x^2":

num1 = Double.parseDouble(screen.getText());

num2 = Math.pow(num1, 2);

screen.setText(num1+" ^ 2 = "+num2);

break;

case "x^3":
Name: Keyur B Niama PRN:2018033800121251

num1 = Double.parseDouble(screen.getText());

num2 = Math.pow(num1, 3);

screen.setText(num1+" ^ 3 = "+num2);

break;

case "sqrt(x)":

num1 = Double.parseDouble(screen.getText());

num2 = Math.sqrt(num1);

screen.setText("sqrt("+num1+") = "+num2);

break;

case "^": screen.setText( screen.getText() + "^");

screen.requestFocus(true);

break;

case "DEL" :

String backStr = screen.getText();

if(backStr.length() == 1) {

backStr = "";

else if(backStr.length() > 1) {

backStr = backStr.substring(0, backStr.length()-


1);

screen.setText(backStr);

break;

case "1/x":

double sol =
Double.parseDouble(exp.evaluateExpression(screen.getText()));

sol = 1/sol;

screen.setText(sol+"");

break;

case "=" : sol =


Double.parseDouble(exp.evaluateExpression(screen.getText()));
Name: Keyur B Niama PRN:2018033800121251

screen.setText(sol+"");

break;

//TextEventListener

public void textValueChanged(TextEvent e) {

//KeyEvent Listener

public void keyTyped(KeyEvent e) {

public void keyPressed(KeyEvent e) {

public void keyReleased(KeyEvent e) {

//Check for operator and numbers presses

public String checkPressedButton(Object obj) {

int flag = 0;

for(int i = 0;i<set1.length && flag == 0;i++) {

if(obj.equals(set1[i])) {

return set1Icon[i];

for(int i = 0;i<set2.length && flag == 0;i++) {

if(obj.equals(set2[i])) {
Name: Keyur B Niama PRN:2018033800121251

return set2Icon[i];

for(int i = 0;i<set3.length && flag == 0;i++) {

if(obj.equals(set3[i])) {

// return set3Icon[i];

for(int i = 0;i<set4.length && flag == 0;i++) {

if(obj.equals(set4[i])) {

return set4Icon[i];

return "";

//Evaluate expression

public String evaluateExpression(String exp) {

String ans = "";

String num = "";

int i = 0;

while(i<exp.length()) {

i++;

return ans;

}
Name: Keyur B Niama PRN:2018033800121251

public class ScientificCalculator {

public static void main(String[] args) {

new CalculatorLayout();

Expression class

class ExpressionStack{

String data;

ExpressionStack next;

class StackOperation {

ExpressionStack top;

ExpressionStack base;

StackOperation(){

top = null;

base = null;

public void push(ExpressionStack currNode,String data) {

ExpressionStack newNode;

if(top == null) {

currNode.data = data;

this.top = currNode;

this.base = new ExpressionStack();

this.base.next = currNode;
Name: Keyur B Niama PRN:2018033800121251

else {

while(currNode != top) {

currNode = currNode.next;

newNode = new ExpressionStack();

newNode.data = data;

currNode.next = newNode;

currNode = newNode;

this.top = currNode;

this.top.next = null;

public String pop(ExpressionStack currNode) {

String returnValue = "";

if(currNode == top) {

returnValue = currNode.data;

currNode = null;

this.top = null;

this.base.next = null;

else {

while(currNode.next!=top) {

currNode = currNode.next;

returnValue = currNode.next.data;

currNode.next = null;

this.top = currNode;

return returnValue;
Name: Keyur B Niama PRN:2018033800121251

public boolean isEmpty(ExpressionStack currNode) {

if(this.top == null) return true;

else return false;

public String topValue(ExpressionStack currNode) {

return this.top.data;

public void display(ExpressionStack currNode) {

while(currNode != null) {

System.out.print(currNode.data);

currNode = currNode.next;

public class ExpressionEvaluation {

public String evaluateExpression(String expr) {

try {

ExpressionStack operator = new ExpressionStack();

ExpressionStack operand = new ExpressionStack();

StackOperation stackOperator = new StackOperation();


Name: Keyur B Niama PRN:2018033800121251

StackOperation stackOperand = new StackOperation();

int i = 0;

String num = "";

while(i<expr.length()) {

if( this.isNum(expr.charAt(i)) || expr.charAt(i) == '.') {

num += expr.charAt(i);

if( i == expr.length()-1 || !( this.isNum(expr.charAt(i)) ||


expr.charAt(i) == '.')){

if(i == 0 && expr.charAt(i) == '-') {

num += '-'; i++; continue;

if(i == 0 && expr.charAt(i) != '-') {

i++; continue;

stackOperand.push(operand, num);

num="";

// stackOperand.display(operand);

if(!stackOperator.isEmpty(operator)) {

if(this.precedence(expr.charAt(i)+"") >
this.precedence(stackOperator.topValue(operator))) {

if(expr.charAt(i) != ')') {

stackOperator.push(operator,
expr.charAt(i)+"");

}
Name: Keyur B Niama PRN:2018033800121251

else {

this.popTillOpenBracket(stackOperator,stackOperand,operator,operand);

else {

double num2 =
Double.parseDouble(stackOperand.pop(operand));

double num1 =
Double.parseDouble(stackOperand.pop(operand));

String operat = stackOperator.pop(operator);

double ans = calculate(num1,num2,operat);

stackOperand.push(operand, ans+"");

stackOperator.push(operator,
expr.charAt(i)+"");

else {

stackOperator.push(operator, expr.charAt(i)+"");

i++;

// stackOperand.display(operand);

// stackOperator.display(operator);

//

return stackOperand.pop(operand);
Name: Keyur B Niama PRN:2018033800121251

catch(Exception e) {

return expr;

//Is Number

public boolean isNum(char ch) {

if(ch >= 48 && ch <= 57) {

return true;

return false;

//Precedence

public int precedence(String oprtor) {

if(oprtor.equals("(") || oprtor.equals(")")) return 6;

else if(oprtor.equals("/") || oprtor.equals("%") || oprtor.equals("^"))


return 5;

else if(oprtor.equals("*")) return 4;

else if(oprtor.equals("+")) return 3;

else if(oprtor.equals("-")) return 2;

else return 0;

//Calculate

public double calculate(double num1,double num2,String operator) {

double ans=0;

switch(operator) {

case "+": ans = num1+num2;break;

case "-": ans= num1-num2;break;

case "*": ans = num1*num2;break;

case "/":ans = num1/num2;break;

case "%": ans = num1%num2;break;

case "^":ans = Math.pow(num1, num2);break;


Name: Keyur B Niama PRN:2018033800121251

return ans;

public void popTillOpenBracket(StackOperation stackOperator,StackOperation


stackOperand,ExpressionStack operator,ExpressionStack operand) {

try {

while(stackOperator.topValue(operator) != "(") {

double num2 =
Double.parseDouble( stackOperand.pop(operand));

double num1 =
Double.parseDouble(stackOperand.pop(operand));

String operat = stackOperator.pop(operator);

double ans = calculate(num1,num2,operat);

stackOperand.push(operand,ans+"");

}catch(Exception e) {

System.out.println("Invalid brackets!!");

public static void main(String[] args) {

ExpressionEvaluation exp = new ExpressionEvaluation();

System.out.println(exp.evaluateExpression("3^2+1.5"));

Output:
Name: Keyur B Niama PRN:2018033800121251
Name: Keyur B Niama PRN:2018033800121251

Lab Assignment- 7

1. To Create User Interface to perform Integer Divisions. The User enters two
numbers in text fields. Num1 and Num2 The division of Num1 and Num2 is
displayed in result field when the divide button clicked. If Num1 or Num2 were not
Integer, the program would throw a NumberFormatException, If Num2 is Zero,
and the program would throw an Arithmetic Exception.Display the Exception in
Message Box.

Code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class A7_1 extends JFrame implements ActionListener
{
TextField tf1,tf2,tf3;
Button b1;
JLabel l1,l2,l3;
A7_1()
{
setTitle("Division Operation...");
l1= new JLabel("Number 1:");
add(l1);
tf1= new TextField(15);
add(tf1);
l2= new JLabel(" Number 2:");
add(l2);
tf2= new TextField(15);
add(tf2);
l3= new JLabel("Result:");
Name: Keyur B Niama PRN:2018033800121251

add(l3);
tf3 = new TextField(15);
add(tf3);
b1=new Button("Divide");
add(b1);
b1.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e)
{
String s1="0";
String s2="0";
s1=tf1.getText();
s2=tf2.getText();
int s3 =0;
try
{
int n1=Integer.parseInt(s1);
int n2=Integer.parseInt(s2);
if(n2==0)
{

JOptionPane.showMessageDialog(null,String.valueOf("Divided By Zero"));
}
else {
s3 = n1 / n2;
String result = String.valueOf(s3);
tf3.setText(result);
}
}
Name: Keyur B Niama PRN:2018033800121251

catch(NumberFormatException e1)
{
JOptionPane.showMessageDialog(null,String.valueOf("Division
not possible"));
}
}
public static void main(String[] args)
{
A7_1 a= new A7_1();
a.setVisible(true);
a.setSize(700 , 500);
a.setLayout(new FlowLayout());
}
}

Output:
Name: Keyur B Niama PRN:2018033800121251

2. Write a java program that simulates a traffic light. The program lets the user
select one of three light Red, Yellow, Green with radio button. On Selecting a
button an appropriate message with “STOP” OR “READY” OR “GO” should appear
above the button in selected color. Initially there is no message shown..

Code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class A7_2
{
A7_2()
{
JFrame frame = new JFrame("Traffic Light");
JLabel label = new JLabel();
label.setAlignmentX(JLabel.CENTER);
label.setSize(400,100);
label.setFont(new Font("", Font.PLAIN,25));
label.setBounds(150,10,200,100);
label.setBackground(Color.green);

JRadioButton box1 = new JRadioButton("RED",false);


box1.setBounds(80,100,65,50);
box1.setBackground(Color.red);
JRadioButton box2 = new JRadioButton("Yellow",false);
box2.setBackground(Color.YELLOW);
box2.setBounds(142,100,65,50);
JRadioButton box3 = new JRadioButton("Green",false);
box3.setBackground(Color.GREEN);
Name: Keyur B Niama PRN:2018033800121251

box3.setBounds(210,100,65,50);
ButtonGroup bg = new ButtonGroup();
bg.add(box3);bg.add(box2);bg.add(box3);
frame.add(box1);
frame.add(box2);
frame.add(box3);
frame.add(label);

frame.setBackground(Color.white);
frame.setSize(400,400);
frame.setLayout(null);
frame.setVisible(true);

box1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
label.setText("STOP");
}
});

box2.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
label.setText("READY");
}
});
box3.addItemListener(new ItemListener()
{
Name: Keyur B Niama PRN:2018033800121251

public void itemStateChanged(ItemEvent e)


{
label.setText("GO");
}
});

}
public static void main(String arg[])
{
new A7_2();
}
}

Output:

3. Write a java program to demonstrate the key event handlers.

Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class A7_3 extends JFrame implements KeyListener {
Name: Keyur B Niama PRN:2018033800121251

Label l;
TextArea area;
A7_3() {
JFrame frame = new JFrame();
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
frame.add(l);
frame.add(area);
frame.setSize (400, 400);
frame.setLayout (null);
frame.setVisible (true);
// frame.EXIT_ON_CLOSE()
}
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
public static void main(String[] args) {
new A7_3();
}
}
Name: Keyur B Niama PRN:2018033800121251

Output:

4. Write a java program that handles all mouse events and shows the event names
at center of the window when a mouse event is fired. Use adapter classes.

Code:

import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;
public class A7_4 extends JFrame implements MouseListener{
Label l;
A7_4(){

JFrame frame = new JFrame();


addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
Name: Keyur B Niama PRN:2018033800121251

setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new A7_4();
}
}

Output:
Name: Keyur B Niama PRN:2018033800121251

You might also like