Csl 203 Oops Lab Manual
Csl 203 Oops Lab Manual
SEMESTER: III
COURSE NAME:
OBJECT ORIENTED
PROGRAMMING LAB
(IN JAVA) St. Thomas Institute for Science &
Technology Trivandrum,(College Code: STI)
L-T-P: 0-0-3
LAB MANUAL
HOURS: 3
CREDIT: 2
NAME/S OF STAFF:
NIKHIL V MATHEW
1
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00
Object Oriented Programming (In Java)
TABLE OF CONTENTS
SYLLABUS 3-4
ii
COURSE PLAN 5iii
INTRODUCTION 6-7
iv
1 PALINDROME CHECK 8-11
1
4 INHERITANCE 20-25
10
5 POLYMORPHISM 26-29
15
6 FILE READ & WRITE 30-33
18
8 EXCEPTIONS 38-41
23
9 DOUBLY LINKED LIST 42-47
26
11 THREADS 52-55
32
2
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00
Object Oriented Programming (In Java) i
SYLLABUS
The syllabus contains six sessions (A, B, C, D, E, F). Each session consists of three concrete
Java exercises, out of which at least two questions (**) are mandatory.
(A) Basic programs using datatypes, operators, and control statements in Java.
1) Write a Java program that checks whether a given string is a palindrome or not.
Ex: MALAYALAM is palindrome.
2) Write a Java Program to find the frequency of a given character in a string. **
3) Write a Java program to multiply two given matrices. **
4) Write a Java program which creates a class named 'Employee' having the following
members: Name, Age, Phone number, Address, Salary. It also has a method named 'print-
Salary( )' which prints the salary of the Employee. Two classes 'Officer' and 'Manager'
inherits the 'Employee' class. The 'Officer' and 'Manager' classes have data members 'spe-
cialization' and 'department' respectively. Now, assign name, age, phone number, address
and salary to an officer and a manager by making an object of both of these classes and
print the same. (Exercise to understand inheritance). **
5) Write a java program to create an abstract class named Shape that contains an empty
method named numberOfSides( ). Provide three classes named Rectangle, Triangle and
Hexagon such that each one of the classes extends the class Shape. Each one of the class-
es contains only the method numberOfSides( ) that shows the number of sides in the giv-
en geometrical structures. (Exercise to understand polymorphism). **
6) Write a Java program to demonstrate the use of garbage collector.
(C) Handling different types of files as well as input and output management methods:
3
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00 ii
Object Oriented Programming (In Java)
10) Write a Java program that shows the usage of try, catch, throws and finally. **
11) Write a Java program that implements a multi-threaded program which has three threads.
First thread generates a random integer every 1 second. If the value is even, second
thread computes the square of the number and prints. If the value is odd the third thread
will print the value of cube of the number.
12) Write a Java program that shows thread synchronization. **
13) Write a Java program that works as a simple calculator. Arrange Buttons for digits and
the + - * % operations properly. Add a text field to display the result. Handle any possible
exceptions like divide by zero. Use Java Swing. **
14) Write a Java program that simulates a traffic light. The program lets the user select one of
three lights: red, yellow, or green. When a radio button is selected, the light is turned on,
and only one light can be on at a time. No light is on when the program starts. **
15) Write a Java program to display all records from a table using Java Database Connectivi-
ty (JDBC).
(F) Standard Searching and Sorting Algorithms using data structures and algorithms
learnedfrom course Data Structures (CST 201):
4
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00 iii
Object Oriented Programming (In Java)
COURSE PLAN
1 PALINDROME CHECK P
2 P
CHARACTER COUNT
3 MATRIX MULTIPLICATION P
4 INHERITANCE P
5 POLYMORPHISM P
7 STRING TOKENIZATION P
8 EXCEPTIONS P
10 QUICK SORT P
11 THREADS P
5
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00 iv
Object Oriented Programming (In Java)
INTRODUCTION
In object-oriented programming, computer programs are designed by making them out of objects that interact
with one another. There is significant diversity in object-oriented programming, but most popular languages
are class-based, meaning that objects are instances of classes, which typically also determines their type.
Any given procedure might be called at any point during a program’s execution, including by other procedures
or itself. Procedural programming is a list or set of instructions telling a computer what to do step by step and
how to perform from the first code to the second code. Procedural programming languages include C, Fortran,
Pascal, and BASIC.
The focus of procedural programming is to break down a programming task into a collection of variables, data
structures, and subroutines, whereas in object-oriented programming it is to break down a programming task
into objects that expose behavior (methods) and data (fields) using interfaces. The most important distinction is
that while procedural programming uses procedures to operate on data structures, object-oriented programming
bundles the two together, so an object, which is an instance of a class, operates on its “own” data structure.
Encapsulation
Encapsulation refers to the creation of self-contained modules (classes) that bind processing functions
to its data members. The data within each class is kept private. Each class defines rules for what is
publicly visible and what modifications are allowed.
Inheritance
Classes may be created in hierarchies, and inheritance lets the structure and methods in one class pass
down the class hierarchy. By inheriting code, complex behaviors emerge through the reuse of code in a
parent class. If a step is added at the bottom of a hierarchy, only the processing and data associated with
that unique step must be added. Everything else above that step may be inherited. Reuse is considered a
major advantage of object orientation.
6
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00 v
Object Oriented Programming (In Java)
Polymorphism
Object oriented programming lets programmers create procedures for objects whose exact type is not
known until runtime. For example, a screen cursor may change its shape from an arrow to a line
depending on the program mode. The routine to move the cursor on screen in response to mouse
movement can be written for “cursor”, and polymorphism lets the right version for the given shape be
called.
Abstraction
An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds
of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the
viewer. Abstraction denotes a model, a view, or some other focused representation for an actual item.
It’s the development of a software object to represent an object we can find in the real world.
Encapsulation hides the details of that implementation.
vi 7
LAB MANUAL/IQAC/SEM 3/AY 22-23/rev 00
Object Oriented Programming (In Java)
PALLINDROME CHECK
Experiment
EXPERIMENT NO : 1
Write a Java program that checks whether a given string is a palindrome or not.
PALINDROME CHECK
Ex: MALAYALAM is palindrome.
Aim: To write a program to check whether the input string is palindrome or not.
Algorithm:
1. Start
2. Read a string using nextLine().
3. Declare a Boolean variable and initialize it as “true”to set as a flag to check palindrome
4. Copy the input string to another string variable for later use
5. Convert the string to lowercase using toLowerCase()
6. Inside the for loop , compare the characters in forward and backward direction of the input string
using charAt().
7. If the first and last characters aren’t equal then set Boolean value to “false“.
8. if Boolean variable = false print “ Not Pallindrome”
else if Boolean variable = true print “Pallindrome”.
9. Stop
Functions and Conditions :Following are the functions and conditions used in this
program.
Functions Description
1. nextLine() reads a line of text from the user.
return value:readLine() returns null on end of file.
The function does not accepts any parameter.
Sample Output
Result: The program to read a string from the user and check whether it is palindrome or not was implemented
successfully.
CHARACTER COUNT
Experiment
Write a Java Program to find the frequency of a given character
EXPERIMENT NOin :a 2string
Ex: Hello CHARACTER COUNT
Frequency of charcter ‘l’ = 2
Aim: To write a Java Program to find the frequency of a given character in a string
Algorithm:
1. Start
2. Declare an integer variable count to maintain the count of characters.
3. Declare a Sting variable input to read the string value from user using readLine().
4. Convert the string to lowercase using toLowerCase() function and store it in a string
variable named inputCopy.
5. Read the character whose frequency to be found out using next()function to a charcter
variable charToSearch.
6. Now convert the string stored in inputCopy variable to a charcter array using
toCharArray() function.
7. Now using a for loop search the index of this array for the search character
(charToSearch).
8. If a match is found perform count++.
9. On exiting the for loop print the count variable
10. Stop
4. next() The next() is a method of Java Scanner class which finds and
returns the next complete token from the scanner which is in
using.
5. for(char ch : array) To iterate through every value present in the array, we make use
of for loop.
Example:
Program:
Sample Output:
Result: The program to find frequency of a character in the inputs string was implemented successfully.
MATRIX MULTIPLICATION
Resultant Matrix
Algorithm:
Step 1: Start
Step 3: Read number of rows (m) and columns (n) of first array and create the matrix as
Step 5: Read number of rows (p) and columns (q) of first array and create the matrix as
Step 6: If column size (n) of first matrix not equal to row size (p) of second matrix print
“Multiplication not possible”.
Functions Used:
Functions Description
1. nextInt() The nextInt() method of a Scanner object reads
in a string of digits (characters) and converts
them into an int type. The Scanner object reads
the characters one by one until it has collected
those that are used for one integer.
Program:
Sample Output:
Result:
The program to multiply two matrices was successfully implemented.
EXPERIMENT NO:4
INHERITANCE
Experiment INHERITANCE
• Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
• The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).
• extends is the keyword used to inherit the properties of a class. Following is the syntax
of extends keyword.
classSuperclass
{
.....
.....
}
classSubclass extends Superclass
{
.....
.....
}
Aim:
Write a Java program which creates a class named 'Employee' having the followingmembers:
Name, Age, Phone number, Address, Salary. It also has a method named 'printSalary( )' which
prints the salary of the Employee. Two classes 'Officer' and 'Manager' inherits the 'Employee'
class. The 'Officer' and 'Manager' classes have data members 'specialization' and 'department'
respectively. Now, assign name, age, phone number, address and salary to an officer and a
manager by making an object of both of these classes and print the same.
Algorithm:
1. Start
2. Create a class Employee
3. Declare member variables of Employee class: String variables name and address, integer
variables age and salary, long variable phone.
10
4. Add a member functions printSalary() with no return statement to print the salary details
and printDetails() with no return to print the details of an employee.
5. Create two child classes for Employee: Officer and Manager.
6. Declare a String variable name specialization inside Officer and String variable named
department inside Manager.
7. Add member functions specPrint() inside Officer to print specialization details and
deptPrint() inside Manager to print Department details.
8. Create an Officer object o as Officer o=new Oficer(); . Using object o initialize all the
variables inherited. Call member functions to print Officer details.
9. Create an Manger object m as Manager m=new Manager(); . Using object m initialize all
the variables inherited. Call member functions to print Manager details
10. Stop
11
Program:
import java.io.*;
import java.util.Scanner;
class Employee
{
String name, address;
int age, salary;
long phone;
class Manager extends Employee// Manager is a child class(sub class) of Employee class
{
String department; //variable of Manager class
void deptPrint()
{
System.out.println("Department: "+department);
}
}
public class Sample
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Officer o=new Officer();
12
13
Output:
Result: The program to understand the concept of inheritance was done and output was
obtained.
14
ABSTRACT CLASSES
EXPERIMENT NO : 5
Abstract Classes: That is to create a superclass that only defines a generalized form that will be
shared by all of its subclasses, leaving it to each subclass to define these methods. Such a class
determines the nature of the methods that the subclasses must implement.This means that certain
methods be overridden by subclasses by specifying the abstract type modifier
abstracttype methodName(parameter-list);
Any class that contains one or more abstract methods must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class keyword at
the beginning of the class declaration.
Aim:Write a java program to create an abstract class named Shape that contains an emptymethod
named numberOfSides( ). Provide three classes named Rectangle, Triangle andHexagon such
that each one of the classes extends the class Shape. Each one of the classescontains only the
method numberOfSides( ) that shows the number of sides in the given geometrical structures.
Algorithm:
1. Start
2. Create an abstract class named shape and declare and abstract method named countsides()
with void return type
3. Create a class named Rectangle and define the countsides() with a print statement
printing number of sides as 4
4. Create a class named Triangle and define the countsides() with a print statement printing
number of sides as 3
5. Create a class named Hexagon and define the countsides()with a print statement printing
number of sides as 6
6. Inside main class Sides, create objects for Rectangle, Triangle and Hexagon classes and
call the corresponding countsides()
7. Stop
Keywords Used
15
Program:
import java.io.*;
//Program to print number of sides for different shapes
abstract class Shape
{
abstract void numberOfSides();
}
class Rectangle extends Shape
{
void numberOfSides()
{
System.out.println("Number of sides of Rectangle is : 4");
}
}
class Triangle extends Shape
{
void numberOfSides()
{
System.out.println("Number of sides of Triangle is : 3");
}
}
class Hexagon extends Shape
{
void numberOfSides()
{
System.out.println("Number of sides of Hexagon is : 6");
}
}
public class Sides
{
public static void main(String args[])
{
}
}
16
Output:
Result: The program to understand the concept of abstract classes and polymorphism was done
and output was obtained.
17
EXPERIMENT NO:6
AIM
To write a program to write contents to a file and read it to output the contents
ALGORITHM
1. Start
2. import all the required packages
3. Create a class name WriteFile
4. Read the target filename to which contents need to be stored to a String variable named
fileName
5. Create the file using File constructor as
File objFile=new File(fileName);
6. Read the contents for the file and store it in a String variable named text
7. Create a FileOutputStream as
FileOutputStreamfileOut=new FileOutputStream(objFile);
8. Write contents of text to output stream using write()
fileOut.write(text.getBytes());
9. Handle all file exceptions using try- catch(Exception obj) blocks
10. Create a FileInputStream as
FileInputStreamfileIn=new FileInputStream(objFile);
11. Print contents of file to the console using read() as
while read returns -1 print all bytes to the console
12. Close all streams.
13. Stop
EXPLANATION
For writing to a file we need to create a output stream which connects to the the
destination file using FileOutputStream class.
3. write(text.getBytes());
26
18
Function used to write to a file that writes the byte specified. If an error occurs
during writing, an IOException is thrown.
To read from a file, you can use a version of read( ) that is defined within
FileInputStream. The one that we will use is shown here:
intread( ) throws IOException
Each time that it is called, it reads a single byte from the file and returns the byte as
an integer value. read( ) returns –1 when the end of the file is encountered. It can
throw an IOException.
PROGRAM
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
try{
File infile =new File("E:\\Java\\input.txt");
File outfile =new File("E:\\output.txt");
int length;
/*copying the contents from input stream to
* output stream using read and write methods
*/
while ((length = instream.read(buffer)) > 0){
outstream.write(buffer, 0, length);
27
19
}catch(IOException ioe){
ioe.printStackTrace();
}
}
RESULT
The program to copy contents of q file to another file was done and output wasobtained.
OUTPUT
28
20
EXPERIMENT NO: 7
STRING TOKENIZATION
AIM
Write a Java program that reads a line of integers, and then displays each integer , and the sum
of all the integers using String Tokenizer class of java.Util.
ALGORITHM
1. Start
2. Import all the require packages
3. Create a class named StringTokenizerDemo
4. Declare 2 integer variables named n and sum. Initialize sum to 0
5. Read string of integers to a string variable s
6. Create a StringTokenizer object. Pass the string to be tokenized along with a delimeter to
the constructor as:
StringTokenizer st = new StringTokenizer(s, " ");
7. do until hasMoreTokens() returns false
read next token using nextToken()
typecast the token to integer and store it in n
find sum as sum = sum+n
8. Print sum
9. Stop
29
21
PROGRAM
import java.util.*;
public class StringTokenizerDemo
{
public static void main(String args[])
{
int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
}
System.out.println("sum of the integers is: " + sum);
sc.close();
}
}
RESULT:
The program that reads a line of integers, and then displays each integer, and the sum ofall the integers using
StringTokenizer class of java.util was done and output was obtained
OUTPUT
30
22
EXPERIMENT NO: 8
EXCEPTION HANDLING
AIM
Write a Java program that carry out a division operation on two integers to show the usageof try,
catch, throws and finally.
ALGORITHM
1. Start
2. Create a class named Division which contains a function named divide() with void return
type
3. Include the code float qt=nr/dr inside try block
4. ifdr=0 catch block will be called.
5. Inside the catch block handle the ArithmeticException. Make the denominator dr as 1 and
continue division.
6. Inside finally print the statement Division Complete
7. Stop
KEYWORDS USED:
• try: Program statements that we want to monitor for exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown.
• catch: Code can catch this exception (using catch) and handle it in some rational manner.
System-generated exceptions are automatically thrown by the Java run-time system.
• throws: Any exception that is thrown out of a method must be specified as such by a
throws clause.
• finally: Any code that absolutely must be executed after a try block completes is put in a
finally block.
31
23
PROGRAM
RESULT
The program that carries out a division operation on two integers to show the usage of try,
catch, throws and finally was done and output was obtained
32
24
33
25
EXPERIMENT NO:9
AIM
ALGORITHM
1. Define a Node class which represents a node in the list. It will have three properties: data, previous which
will point to the previous node and next which will point to the next node.
2. Define another class for creating a doubly linked list, and it has two nodes: head and tail. Initially, head and
tail will point to null.
3. addNode() will add node to the list:
3.1. Check whether the head is null, then it will insert the node as the head.
3.2. Both head and tail will point to a newly added node.
3.3. Head's previous pointer will point to null and tail's next pointer will point to null.
3.4. If the head is not null, the new node will be inserted at the end of the list such that new node's previous
pointer will point to tail.
3.5. The new node will become the new tail. Tail's next pointer will point to null.
4. display() will show all the nodes present in the list.
4.1. Define a new node 'current' that will point to the head.
4.2. Print current.data till current points to null.
4.3. Current will point to the next node in the list in each iteration.
5. Define a delete() function for deleting from the front
5.1. Set head.left=null and head=head.right
34
26
PROGRAM
import java.util.Scanner;
class LinkedList
{
private Node head;
class Node
{
private int data;
private Node left;
private Node right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
public void insert(int data)
{
Node temp = new Node(data);
if(head == null)
{
head = temp;
}
else
{
Node ptr = head;
while(ptr.right != null)
{
ptr = ptr.right;
}
ptr.right = temp;
temp.left = ptr;
}
}
public void delete()
{
int x = head.data;
head = head.right;
head.left = null;
System.out.println("Element "+x +" got deleted");
}
public void display()
{
if(head == null)
35
27
System.out.println("List is Empty");
else
{
Node ptr = head;
while(ptr != null)
{
System.out.print(ptr.data +"\t");
ptr = ptr.right;
}
System.out.println();
}
}
}
class Test
{
public static void main(String [] args)
{
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
String choice = "";
while(!choice.equals("4"))
{
System.out.print("1. Insert at End \n 2. Delete From Front \n 3. Display \n
4.Exit \n");
System.out.println("Enter the choice:");
choice = sc.nextLine();
switch(choice)
{
case "1":
System.out.print("Enter the number to insert:");
int data = sc.nextInt();
sc.nextLine();
list.insert(data);
System.out.println("Data inserted Successfully");
break;
case "2":
list.delete();
break;
case "3":
list.display();
break;
case "4":
break;
default: System.out.println("Invalid Choice");
}
}
36
28
}
}
RESULT:
OUTPUT
37
29
EXPERIMENT NO:10
QUICK SORT
AIM
To write a Java program that implements Quick sort algorithm for sorting a list of names in ascending order.
ALGORITHM
1. An array is divided into subarrays by selecting a pivot element (element selected from the array).
While dividing the array, the pivot element should be positioned in such a way that elements less than
pivot are kept on the left side and elements greater than pivot are on the right side of the pivot.
2. The left and right subarrays are also divided using the same approach. This process continues until each
subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to form a sorted array.
PROGRAM
import java.util.Scanner;
class QuickS
{
public static void quickSort(String A[],int p,int r)
{
if(p<r)
{
int q = partition(A,p,r);
quickSort(A,p,q-1);
quickSort(A,q+1,r);
}
}
public static int partition(String A[],int p,int r)
{
String x = A[r];
int i = p-1;
for(int j=p;j<=r-1;j++)
{
if(A[j].compareTo(x) <=0)
{
i = i + 1;
String temp = A[i];
A[i] = A[j];
38
30
A[j] = temp;
}
}
String temp = A[i+1];
A[i+1] = A[r];
A[r] = temp;
return i +1 ;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit:");
int n = sc.nextInt();
sc.nextLine();
String A[] = new String[n];
System.out.println("Enter the names");
for(int i =0;i<n ;i++)
{
A[i] = sc.nextLine();
}
quickSort(A,0,n-1);
System.out.println("After Quick Sort");
for(int i =0;i<n;i++)
System.out.println(A[i]);
}
}
RESULT:
The program is implemented and output is verified
OUTPUT
39
31
EXPERIMENT NO:11
THREADS
AIM
Write a java program to create two threads that prints multiplication table of a given number.
ALGORITHM:
1. Start
2. Create a class named Table and define a synchronized method printTable that will be shared by the threads
and print the table of inputs.
3. Create two subclasses Thread1 and Thread2 for the Thread superclass.
4. Define the run () method of both the threads.
5. Read two numbers for both the threads Thread1 and Thread2
6. Create instances for Thread1 and Thread2 and invoke the run () method.
7. Stop.
PROGRAM
import java.util.Scanner;
class Table
{
synchronized void printTable (int n)
{
System.out.println("Printing the multiplication table for "+n);
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
40
32
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number for Thread 1 and");
int a=sc.nextInt();
t.printTable(a);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number for Thread 2 ");
int b=sc.nextInt();
t.printTable(b);
}
}
public class TestSync
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start(); //call to run() function of Thread 1
t2.start(); //call to run() function of Thread 2
}
}
41
33
RESULT:
OUTPUT
42
34
EXPERIMENT NO :12
SWING – CALCULATOR
AIM
To write a Java program that works as a simple calculator. Arrange Buttons for digits andthe
+ - * % operations properly. Add a text field to display the result.
ALGORITHM
1. Start
2. Create class that implements actionListener interface
3. Create a frame object as JFrame f=new JFrame(“String str”);
4. Create require number objects of JTextField, JButton as
JTextField obj=new JTextField(“String str”); JButton
bobj= new JButton(“String str”);
5. Set boundaries of all components using setBounds (int x, int y, int width, intheight)
6. Add the components into frame using add(Component obj) function
7. Register all buttons with actionListener using addActionListener() function.
8. Set size, layout and visibility of the frame using setSize(), setLayout(),setVisibility()
functions.
9. Define the actionPerformed(ActionEvent e) as
if(e.getSource()==compenent 1)
{
do something
}
repeat for all components
10. End
PROGRAM
import javax.swing.*;
import java.awt.event.*;
class Calc implements ActionListener
{
43
35
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;
static double a=0,b=0,result=0;
static int operator=0;
Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("Delete");
bclr=new JButton("Clear");
t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);
b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);
b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);
bdec.setBounds(40,310,50,40);
44
36
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);
bdel.setBounds(60,380,100,40);
bclr.setBounds(180,380,100,40);
f.add(t);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(bdiv);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(bmul);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(bsub);
f.add(bdec);
f.add(b0);
f.add(beq);
f.add(badd);
f.add(bdel);
f.add(bclr);
f.setLayout(null);
f.setVisible(true);
f.setSize(350,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
45
37
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
t.setText(t.getText().concat("1"));
if(e.getSource()==b2)
t.setText(t.getText().concat("2"));
if(e.getSource()==b3)
t.setText(t.getText().concat("3"));
if(e.getSource()==b4)
t.setText(t.getText().concat("4"));
if(e.getSource()==b5)
t.setText(t.getText().concat("5"));
if(e.getSource()==b6)
t.setText(t.getText().concat("6"));
if(e.getSource()==b7)
t.setText(t.getText().concat("7"));
if(e.getSource()==b8)
t.setText(t.getText().concat("8"));
if(e.getSource()==b9)
t.setText(t.getText().concat("9"));
if(e.getSource()==b0)
t.setText(t.getText().concat("0"));
if(e.getSource()==bdec)
t.setText(t.getText().concat("."));
if(e.getSource()==badd)
{
a=Double.parseDouble(t.getText());
operator=1;
t.setText("");
}
if(e.getSource()==bsub)
{
a=Double.parseDouble(t.getText());
operator=2;
46
38
t.setText("");
}
if(e.getSource()==bmul)
{
a=Double.parseDouble(t.getText());
operator=3;
t.setText("");
}
if(e.getSource()==bdiv)
{
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}
if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());
switch(operator)
{
case 1: result=a+b;
break;
case 2: result=a-b;
break;
case 3: result=a*b;
break;
case 4: result=a/b;
break;
default: result=0;
}
t.setText(""+result);
}
if(e.getSource()==bclr)
t.setText("");
if(e.getSource()==bdel)
{
String s=t.getText();
t.setText("");
for(int i=0;i<s.length()-1;i++)
t.setText(t.getText()+s.charAt(i));
}
}
47
39
RESULT:
The Program to implement a SWING based calculator was done and output was obtained.
OUTPUT :
48
40
EXPERIMENT NO:13
TRAFFIC LIGHT
AIM:
To write a java program that implements a traffic light by creating 3 radio buttons for red, green and yellow
and when one of the button is selected corresponding light must turn on.
ALGORITHM:
1. Start
2. Create a class named TrafficLightsDemo that inherits JFrame and implements
ActionListener interface.
3. Create radio button objects using JRadioButton class.
4. Initialize the signal colors using a class named Signal.
5. Inside TrafficLightsDemo constructor
Set layout as GridLayout
Create ButtonGroup and add all radio buttons to the group
Create a panel using Jpanel
Register the radio buttons using addActionListener()
Define actionPerformed() function as
if(e.getSource==greenradiobutton)
call turnOn() and set green=true
call fillCircle() and set circle color as green
repeat for other radio buttons
6. End
FUNCTIONS/CLASSES USED:
1. getContentPane() : The getContentPane() method retrieves the content pane layer so
that you can add an object to it. the layer that is used to hold objects is called the content
pane.
2. JRadioButton : Class used to create JRadioButton component.
3. ButtonGroup : All the radio buttons must be added to a ButtonGroup object
4. JPanel : class used to create a panel container to separate the content pane into different
panels
5. Graphics : class used to add graphic properties like creating shapes, filling colors etc.
6. paint() : used to carry out the the graphics related tasks.
PROGRAM:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TrafficLightsDemo extends JFrame implements ActionListener
49
41
{
JRadioButton buttonRed, buttonYellow, buttonGreen;
Signal green = new Signal(Color.green);
Signal yellow = new Signal(Color.yellow);
Signal red = new Signal(Color.red);
public TrafficLightsDemo()
{
super("Java Traffic Light Program"); //calls the superclass constructor, JFrame().
getContentPane().setLayout(new GridLayout(2, 1));
buttonRed = new JRadioButton("Red");
buttonYellow = new JRadioButton("Yellow");
buttonGreen = new JRadioButton("Green");
buttonRed.addActionListener(this);
buttonYellow.addActionListener(this);
buttonGreen.addActionListener(this);
ButtonGroup bg=new ButtonGroup();
bg.add(buttonRed);bg.add(buttonYellow); bg.add(buttonGreen) ;
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(false);
JPanel trafficPanel = new JPanel(new GridLayout(3,1));
trafficPanel.add(red);
trafficPanel.add(yellow);
trafficPanel.add(green);
JPanel lightPanel = new JPanel(new FlowLayout());
lightPanel.add(buttonRed);
lightPanel.add(buttonYellow);
lightPanel.add(buttonGreen);
getContentPane().add(trafficPanel);
getContentPane().add(lightPanel);
pack();
}
public static void main(String[] args)
{
TrafficLightsDemo trafficLight = new TrafficLightsDemo();
trafficLight.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == buttonRed)
{
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(true);
} else if (e.getSource() == buttonYellow)
{
yellow.turnOn(true);
50
42
green.turnOn(false);
red.turnOn(false);
} else if (e.getSource() == buttonGreen)
{
red.turnOn(false);
yellow.turnOn(false);
green.turnOn(true);
}
}
}
class Signal extends JPanel
{
Color on;
int radius = 40;
int border = 10;
boolean change;
Signal(Color color)
{
on = color;
change = true;
}
public void turnOn(boolean a)
{
change = a;
repaint();
}
public Dimension getPreferredSize()
{
int size = (radius+border)*2;
return new Dimension( size, size );
}
public void paintComponent(Graphics graphics)
{
graphics.setColor( Color.black );
graphics.fillRect(0,0,getWidth(),getHeight());
if (change)
{
graphics.setColor( on );
} else
{
graphics.setColor( on.darker().darker().darker() );
}
graphics.fillOval( border,border,2*radius,2*radius );
}
}
51
43
RESULT:
The program to implement Traffic Light using Swing has been implemented successfully and Output was
obtained.
OUTPUT:
52
44