Java Lab Manual
Java Lab Manual
a. Try debug step by step with small program of about 10 to 15 lines which contains at least
one if else condition and a for loop.
Program:
import java.io.*;
class Primes
{
public static void main(String args[])throws IOException
{
int num,range,i,c=0;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the range value : ");
range=Integer.parseInt(in.readLine());
System.out.println("The prime series is : ");
for(num=1;num<=range;num++)
{
for(i=num-1,c=0;i>1;i--)
{
if(num % i==0)
c++;
}
if(c==0)
System.out.println(num);
}
}
}
b. Write a java program that prints all real solutions to the quadratic equation ax2+bx+c=0.
Read in a, b, c and use the quadratic formula.
Program:
}
}
c. The Fibonacci sequence is defined by the following rule. The first two values in the
sequence are 1 and every subsequent value is the sum of the two values preceding it. Write a
java program that uses both recursive and non-recursive functions.
Program:
import java.io.*;
class Fibonacci //creating a class named Fibonacci
{
int fib(int n) // a method fib with one integer argument and return type integer is
defined
{
int f1=1,f2=1,f3=0,i; //variable declaration
if(n==1) return 1;
else if(n==2) return 1;
i=2;
while(i<n) //if n>2 add the two preceding terms of the series to get the next term
{
f3=f1+f2;
f1=f2;
f2=f3;
i=i+1;
}
return f3;
}
}
class Fibn
{
public static void main(String args[]) throws IOException
{
Fibonacci f =new Fibonacci(); //creating an instance to the class Fibonacci
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter N value:");
int n1;
n1=Integer.parseInt(dis.readLine());
System.out.println(n1 +"th Fibonacci value is " + f.fib(n1)); //to print the nth
term of the series
}
}
Week-2: Matrices, Overloading, Overriding
Program:
import java.io.*;
class Matrix
{
public static void main(String args[]) throws IOException
{
int mul[][],m1[][],m2[][];
int i1,i2,j1,j2;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Row Size of the First Matrix : ");
i1=Integer.parseInt(in.readLine());
System.out.println("Enter the Col Size of the First Matrix : ");
j1=Integer.parseInt(in.readLine());
System.out.println("Enter the Row Size of the Second Matrix : ");
i2=Integer.parseInt(in.readLine());
System.out.println("Enter the Col Size of the Second Matrix : ");
j2=Integer.parseInt(in.readLine());
if(j1 != i2)
{
System.out.println("Matrix Multiplication is not possible");
return;
}
m1=new int[i1][j1];
m2=new int[i2][j2];
System.out.println("Enter the values of the First Matrix : ");
for(int i=0;i<i1;i++)
{
for(int j=0;j<j1;j++)
{
m1[i][j]=Integer.parseInt(in.readLine());
}
}
System.out.println("Enter the values of the Second matrix : ");
for(int i=0;i<i2;i++)
{
for(int j=0;j<j2;j++)
{
m2[i][j]=Integer.parseInt(in.readLine());
}
}
mul=new int[i1][j2];
for(int i=0;i<i1;i++)
{
for(int j=0;j<j2;j++)
{
mul[i][j]=0;
for(int k=0;k<j1;k++)
{
mul[i][j]+=m1[i][k] * m2[k][j];
}
}
}
System.out.println("The Resultent Matrix is: ");
for(int i=0;i<i1;i++)
{
for(int j=0;j<j2;j++)
{
System.out.print(mul[i][j] + "\t");
}
System.out.print( "\n");
}
}
}
b. Write a java program to implement method overloading and constructors overloading.
Program:
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
Program:
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Week-3: Palindrome, Abstract Class
Program:
import java.io.*;
class Palindrome
{
public static void main(String args[])throws IOException
{
int i;
String s1,s2;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string");
s1=in.readLine();
StringBuffer s3=new StringBuffer(s1);
s2=new String(s3.reverse());
i=s1.compareTo(s2);
if(i==0)
System.out.println("Given String is a palindrome");
else
System.out.println("Given String is not a palindrome");
}
}
b. Write a java program for sorting a given list of names in ascending order.
Program:
import java.io.*;
class Sort
{
public static void main(String args[])throws IOException
{
String[] st;
String hold;
int n,j,k;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no.of strings that you want to enter");
n=Integer.parseInt(in.readLine());
st=new String[n];
System.out.println("Enter "+n+" strings");
int m=0;
while(m<st.length)
{
st[m]=in.readLine();
m++;
}
for(int i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
k=st[i].compareTo(st[j]);
if(k>0)
{
hold=st[i];
st[i]=st[j];
st[j]=hold;
}
}
}
System.out.println("\n\n");
System.out.println("Strings in Sorted Order : ");
for(int i=0;i<n;i++)
System.out.println(st[i]);
}
}
c. Write a java program to create an abstract class named Shape that contains two integers
and an empty method named print Area (). Provide three classes named Rectangle, Triangle
and Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the given shape.
Program:
import java.util.*;
Write a program that creates a user interface to perform integer division. 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 and Num2 were not integers, the
program would throw a Number Format Exception. If Num2 were zero, the program would
throw an Arithmetic Exception Display the exception in a message dialog box.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="Division" height="1000" width="1000">
* </applet>
*/
public class Division extends JApplet implements ActionListener
{
int a,b,c;
JButton b1;
JTextField t1,t2,res;
JLabel l1,l2,l3;
public void init()
{
l1=new JLabel("Enter First Number");
l2=new JLabel("Enter Second Number");
l3=new JLabel("Result is: ");
t1=new JTextField(10);
t2=new JTextField(10);
res=new JTextField(10);
b1=new JButton("Division");
setLayout(new FlowLayout(FlowLayout.LEFT));
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(l3);
add(res);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equalsIgnoreCase("Division"))
{
try
{
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
c=a/b;
res.setText(String.valueOf(c));
}
catch(NumberFormatException ne)
{
res.setText("");
JOptionPane.showMessageDialog(null, ne.getMessage(),"Exception
Handling",JOptionPane.INFORMATION_MESSAGE);
}
catch(ArithmeticException ae1)
{
res.setText("");
JOptionPane.showMessageDialog(null,ae1.getMessage(),"Exception
Handling",JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e)
{
res.setText("");
JOptionPane.showMessageDialog(null,e.getMessage(),"Exception
Handling",JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
Week-5: Multithreading
a) Write a java program that implements a multi-thread application that has three threads.
First thread generates random integer every 1 second and 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.
Program:
import java.util.Random;
SquareThread(int randomNumbern) {
number = randomNumbern;
}
Program:
a. Write a java program that reads a file name from the user, and then displays information
about whether the file exists, whether the file is readable, whether the file is writable, the type
of file and the length of the file in bytes.
Program:
import java.io.*;
class CheckFile
{
public static void main(String[] a) throws IOException
{
String s;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a file name:");
s=in.readLine();
File f=new File(s);
if(f.exists())
{
System.out.println("GIVEN FILE IS EXISTS");
System.out.println("Name of the file is : "+ f.getName());
System.out.println("Path of the file is : "+ f.getPath());
System.out.println("Absolute Path of the file is : "+ f.getAbsolutePath());
if(f.canRead())
System.out.println("GIVEN FILE IS READABLE");
else
System.out.println("GIVEN FILE IS NOT READABLE");
if(f.canWrite())
System.out.println("GIVEN FILE IS WRITABLE");
else
System.out.println("GIVEN FILE IS NOT WRITABLE");
if(f.isDirectory())
System.out.println("GIVEN FILE IS DIRECTORY");
else
System.out.println("GIVEN FILE IS NOT DIRECTORY");
if(f.isFile())
System.out.println("GIVEN FILE IS NORMAL FILE");
else
System.out.println("GIVEN FILE IS NOT A NORMAL FILE");
System.out.println("LENGTH OF THE FILE IN BYTES IS : "+f.length());
}
else
System.out.println("FILE DOES NOT EXISTS");
}
}
b. Write a java program that displays the number of characters, lines and words in a text file.
Program:
import java.io.*;
class ContentCount
{
public static void main(String args[]) throws IOException
{
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the File Name : ");
String s1=dis.readLine();
File f = new File(s1);
if(f.exists())
{
if(f.canRead())
{
FileInputStream in=new FileInputStream(s1);
int str,nc=0,nl=0,nw=0;
System.out.println("\n Contents of File is:");
while((str=in.read())!=-1)
{ //to increment word count when space occurs
System.out.print((char)str);
if((char)str==' ')
nw++; //to increment line count and
word count when end line character occurs
else if((char)str=='\n')
{
nw++;
nl++;
}
else
nc++;
}
in.close();
System.out.println("\n No.of lines:"+nl+"\n No.of
words:"+nw+"\n No.of chars:"+nc);
}
else
{
System.out.println("Given File is Not Readable");
}
}
else
{
System.out.println("Given File Does Not Exists");
}
}
}
c. Write a java program that reads a file and displays the file on the screen with line number
before each line.
Program:
import java.io.*;
public class ReadLine
{
public static void main(String args[])throws IOException
{
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the File Name : ");
String s1=dis.readLine();
File file=new File(s1); //creates a new file instance
if(file.exists())
{
if(file.canRead())
{
try
{
FileReader fr=new FileReader(file); //reads the file
BufferedReader br=new BufferedReader(fr); //creates a buffering character input stream
String line;
int num=1;
System.out.println("Contents of File: ");
while((line=br.readLine())!=null)
{
System.out.print(num+". ");
System.out.println(line);
num++;
}
fr.close(); //closes the stream and release the resources
}
catch(IOException e)
{
e.printStackTrace();
}
}
else
{
System.out.println("Given File is Not Readable");
}
}
else
{
System.out.println("Given File Does Not Exists");
}
}
}
Week-7: Files
a. Suppose that table named table.txt is stored in a text file. The first line in the file is the
header, and the remaining lines correspond to rows in the table. The elements are separated
by commas. Write a java program to display the table using labels in grid layout.
Program:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame
{
public A()
{
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try
{
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the File Name : ");
String s1=dis.readLine();
File file=new File(s1);
if(file.exists())
{
if(file.canRead())
{
}
else
{
System.out.println("Given File is Not Readable");
}
}
else
{
System.out.println("Given File Does Not Exists");
}
}
catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(true);
pack();
setVisible(true);
}
}
public class TableDemo {
public static void main(String[] args) {
A a = new A();
}
}
b. Write a java program that connects to a database using JDBC and does add, delete, modify
and retrieve operations.
Program:
import java.sql.*;
import javax.sql.*;
import java.util.*;
public class CRUD
{
public static void main(String[] args)
{
Connection cn;
Statement st;
ResultSet rs;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
cn = DriverManager.getConnection("jdbc:oracle:thin:@DESKTOP-
2QLKCGL:1521:XE","system","manager");
st = cn.createStatement();
System.out.println("Welcome To Institute of Aeronautical Engineering College");
System.out.println("------MENU------");
System.out.println("1.Insert");
System.out.println("2.EDIT");
System.out.println("3.Delete");
System.out.println("4.Display");
System.out.println("5.Exit");
System.out.println("----------------");
String opt = "";
String htno = "", sname = "", mobile = "", sql = "";
Scanner sc = new Scanner(System.in);
while (opt != "5")
{
System.out.println("Enter Your Option");
opt = sc.next();
switch (opt)
{
case "1":
{
System.out.println("Enter Htno");
htno = sc.next();
System.out.println("Enter Name");
sname = sc.next();
System.out.println("Enter Mobile");
mobile = sc.next();
sql = "insert into student values(" + "'" + htno + "'" + "," + "'" + sname + "'" + "," + "'" +
mobile + "'" + ")";
if (st.executeUpdate(sql) > 0)
{
System.out.println("Record Inserted");
}
}
break;
case "2":
{
System.out.println("Enter Htno to Update");
htno = sc.next();
System.out.println("Enter Name");
sname = sc.next();
System.out.println("Enter Mobile");
mobile = sc.next();
sql = "update student set sname=" + "'" + sname + "'" + "," + "mobile=" + "'" + mobile +
"'" + " where rollno='" + htno + "'";
if (st.executeUpdate(sql) > 0) {
System.out.println("Record Updated");
}
else
{
System.out.println("Operation Failed");
}
}
break;
case "3":
{
System.out.println("Enter Htno to delete");
htno = sc.next();
sql = "delete from student where rollno=" + "'" + htno + "'";
if (st.executeUpdate(sql) > 0) {
System.out.println("Record deleted");
} else {
System.out.println("Operation Failed");
}
}
break;
case "4": {
sql = "select * from student";
rs = st.executeQuery(sql);
System.out.println("Htno\tSname\tMobile");
while (rs.next()) {
System.out.println(rs.getString("rollno") + "\t" + rs.getString("sname") + "\t" +
rs.getString("mobile"));
}
rs.close();
}
break;
case "5":
{
opt = "5";
System.out.println("Thank You");
st.close();
cn.close();
}
break;
default: {
System.out.println("Choose Option between 1 and 5 only"); }
}
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
Week-8: Java Program with Database
a. Write a java program that loads names and phone numbers from a text file where the data
is organized as one line per record and each field in a record are separated by a tab (/t). It
takes a name or phone number as input and prints the corresponding other value from the
hash table. Hint: Use hash tables.
Program:
import java.util.*;
import java.io.*;
public class PhoneDictionary
{
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("E:\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("Welcome to Institute of Aeronautical
Engineering");
System.out.println("Student Phone numbers are");
while (sc.hasNext()) {
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("iare");
System.out.println("MENU");
System.out.println("1.Search by Name");
System.out.println("2.Search by Mobile");
System.out.println("3.Exit");
String opt = "";
String name, mobile;
Scanner s = new Scanner (System.in);
while (opt != "3")
{
System.out.println("Enter Your Option (1,2,3): ");
opt = s.next();
switch (opt)
{
case "1":
{
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " +
ht.get(name));
}
else
{
System.out.println("Not Found");
}
}
break;
case "2":
{
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile))
{
for (Map.Entry e : ht.entrySet())
{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " +
e.getKey());
}
}
}
else {
System.out.println("Not Found");
}
}
break;
case "3":
{
opt = "3";
System.out.println("Menu Successfully
Exited");
}
break;
default:
System.out.println("Choose Option betwen 1
and Three");
break;
}
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
b. Implement the above program with database instead of a text file.
Program:
import java.sql.*;
import java.util.*;
public class PhoneDB
{
public static void main(String[] args)
{
Connection cn;
Statement st;
ResultSet rs;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
cn = DriverManager.getConnection("jdbc:oracle:thin:@DESKTOP-
2QLKCGL:1521:XE","system","manager");
System.out.println("Data Base Connected");
st = cn.createStatement();
rs = st.executeQuery("select * from student");
Hashtable<String, String> ht = new Hashtable<String, String>();
System.out.println("IARE");
System.out.println("Student Phone numbers are");
while (rs.next())
{
ht.put(rs.getString(2), rs.getString(3));
System.out.println(rs.getString(2) + ":" + rs.getString(3));
}
rs.close();
st.close();
cn.close();
System.out.println("-----------------------------------------------------");
System.out.println("Welcome IARE");
System.out.println("Main Menu");
System.out.println("1.Search by Name");
System.out.println("2.Search by Mobile");
System.out.println("3.Exit");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("-----------------------");
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt)
{
case "1":
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
} else {
System.out.println("Not Found");
}
break;
case "2":
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile))
{
for (Map.Entry e : ht.entrySet())
{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
break;
case "3":
opt = "3";
System.out.println("Menu Successfully Exited");
break;
default:
System.out.println("Choose Option betwen 1 and Three");
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Week-9: Files
a. Write a java program that takes tab separated data (one record per line) from a text file and
insert them into a database.
Program:
import java.sql.*;
import java.io.*;
import java.util.*;
public class TblToDb
{
public static void main(String[] args)
{
Connection cn;
Statement st;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
cn=DriverManager.getConnection("jdbc:oracle:thin:@DESKTOP-
2QLKCGL:1521:XE","system","manager");
st=cn.createStatement();
String sql="";
FileInputStream fin=new FileInputStream("E:\\employee.txt");
Scanner sc=new Scanner(fin);
String[] arrayList;
String a="";
int i=0;
while(sc.hasNext())
{
a=sc.nextLine();
arrayList =a.split("\\s+");
sql="insert into employee values("+"'"+arrayList[0]+"','"+arrayList[1]+"','"+arrayList[2]+"')";
st.execute(sql);
i++;
System.out.println(arrayList[0]+":"+arrayList[1]+":"+arrayList[2]);
}
System.out.println(i+" Records are inserted");
st.close();
cn.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
b. Write a java program that prints the metadata of a given table.
Program:
import java.sql.*;
import java.util.*;
class Tblmdata
{
public static void main(String[] args)
{
Connection cn;
Statement st;
ResultSet rs, rs1;
ResultSetMetaData rsmd;
try
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Table Name");
String tblname = sc.next();
Class.forName("oracle.jdbc.driver.OracleDriver");
cn=DriverManager.getConnection("jdbc:oracle:thin:@DESKTOP-
2QLKCGL:1521:XE","system","manager");
st = cn.createStatement();
String sql = "select * from "+tblname;
System.out.println("-------Table Name: " + tblname + "---------");
rs1 = st.executeQuery(sql);
rsmd = rs1.getMetaData();
System.out.println("Columns are ");
System.out.println("Column Name\tColumn Type\tSize");
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.println(rsmd.getColumnLabel(i) + "\t\t" + rsmd.getColumnTypeName(i) + "\t" +
rsmd.getColumnDisplaySize(i));
}
rs1.close();
cn.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Week-10: Traffic Light
Write a java program that simulates a traffic 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.
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ItemListener
{
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
public JPanel p, p1;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setSize(800, 400);
p = new JPanel(new FlowLayout());
p1 = new JPanel(new FlowLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 60);
l1.setFont(f);
add(l1);
p.add(l1);
add(p);
l2 = new JLabel("Select Lights");
p1.add(l2);
JRadioButton r1 = new JRadioButton("Red Light");
r1.setBackground(Color.red);
p1.add(r1);
r1.addItemListener(this);
JRadioButton r2 = new JRadioButton("Yellow Light");
r2.setBackground(Color.YELLOW);
p1.add(r2);
r2.addItemListener(this);
JRadioButton r3 = new JRadioButton("Green Light");
r3.setBackground(Color.GREEN);
p1.add(r3);
r3.addItemListener(this);
add(p1);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
setVisible(true);
}
public void itemStateChanged(ItemEvent i)
{
JRadioButton jb = (JRadioButton) i.getSource();
switch (jb.getText())
{
case "Red Light":
{
l1.setText("STOP");
l1.setForeground(Color.RED);
}
break;
case "Yellow Light":
{
l1.setText("Ready");
l1.setForeground(Color.YELLOW);
}
break;
case "Green Light":
{
l1.setText("GO");
l1.setForeground(Color.GREEN);
}
break;
}
}
}
public class TLights
{
public static void main(String[] args)
{
A a = new A();
}
}
Week-11: Mouse Events
a. Write a java program that handles all mouse events and shows the event name at the centre
of the window when a mouse event is fired. Use adapter classes.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="MouseEvents" height="300" width="300">
* </applet>
*/
public class MouseEvents extends Applet implements MouseListener,MouseMotionListener
{
String msg=" ";
int mouseX=0,mouseY=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me){
mouseX=0;
mouseY=10;
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me){
mouseX=0;
mouseY=10;
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me){
mouseX=0;
mouseY=10;
msg="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent me){
mouseX=me.getX();
mouseY=me.getY();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Up";
repaint();
}
public void mouseDragged(MouseEvent me){
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at:"+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me){
showStatus("Mouse moved at :"+me.getX()+","+me.getY());
}
public void paint(Graphics g){
g.drawString(msg,mouseX,mouseY);
}
}
b. Write a java program to demonstrate the key event handlers.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="KeyEvents" height="300" width="300">
* </applet>
*/
public class KeyEvents extends Applet implements KeyListener
{
String msg="";
int X=10,Y=20;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("key Down");
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
Write a java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +,-,*, % operations. Add a text field to display the result. Handle any
possible exception like divided by zero.
Program:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="Calculator" height="300" width="300">
* </applet>
*/
public class Calculator extends Applet implements ActionListener
{
TextField result;
int res, value;
char op;
public void init() {
setLayout(new GridLayout(4, 4));
Font f = new Font("Arial", Font.BOLD, 20);
setFont(f);
setForeground(Color.RED);
result = new TextField(5);
result.setCaretPosition(99999);
add(result);
Button b1 = new Button("1");
add(b1);
b1.addActionListener(this);
Button b2 = new Button("2");
add(b2);
b2.addActionListener(this);
Button b3 = new Button("3");
add(b3);
b3.addActionListener(this);
Button b4 = new Button("4");
add(b4);
b4.addActionListener(this);
Button b5 = new Button("5");
add(b5);
b5.addActionListener(this);
Button b6 = new Button("6");
add(b6);
b6.addActionListener(this);
Button b7 = new Button("7");
add(b7);
b7.addActionListener(this);
Button b8 = new Button("8");
add(b8);
b8.addActionListener(this);
Button b9 = new Button("9");
add(b9);
b9.addActionListener(this);
Button b0 = new Button("0");
add(b0);
b0.addActionListener(this);
Button ba = new Button("+");
add(ba);
ba.addActionListener(this);
Button bs = new Button("-");
add(bs);
bs.addActionListener(this);
Button bd = new Button("/");
add(bd);
bd.addActionListener(this);
Button bm = new Button("*");
add(bm);
bm.addActionListener(this);
Button bmo = new Button("%");
add(bmo);
bmo.addActionListener(this);
Button be = new Button("=");
add(be);
be.addActionListener(this);
Button bc = new Button("C");
add(bc);
bc.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int a;
String str = ae.getActionCommand();
if(str.equalsIgnoreCase("0"))
{
result.setText(result.getText()+str);
}
else if(str.equalsIgnoreCase("1"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("2"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("3"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("4"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("5"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("6"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("7"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("8"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("9"))
result.setText(result.getText()+str);
else if(str.equalsIgnoreCase("+"))
{
res = Integer.parseInt(result.getText());
result.setText("");
op=str.charAt(0);
}
else if(str.equalsIgnoreCase("-"))
{
res = Integer.parseInt(result.getText());
result.setText("");
op=str.charAt(0);
}
else if(str.equalsIgnoreCase("*"))
{
res = Integer.parseInt(result.getText());
result.setText("");
op=str.charAt(0);
}
else if(str.equalsIgnoreCase("/"))
{
res = Integer.parseInt(result.getText());
result.setText("");
op=str.charAt(0);
}
else if(str.equalsIgnoreCase("%"))
{
res = Integer.parseInt(result.getText());
result.setText("");
op=str.charAt(0);
}
else if(str.equalsIgnoreCase("="))
{
a=Integer.parseInt(result.getText());
switch(op)
{
case '+': res=res+a;
result.setText("");
result.setText(String.valueOf(res));
break;
case '-': res=res-a;
result.setText("");
result.setText(String.valueOf(res));
break;
case '*': res=res*a;
result.setText("");
result.setText(String.valueOf(res));
break;
case '/': try
{
res=res/a;
result.setText("");
result.setText(String.valueOf(res));
}
catch(ArithmeticException ae2)
{
result.setText("");
showStatus("Division by Zero Not Possible");
}
break;
case '%': res=res%a;
result.setText("");
result.setText(String.valueOf(res));
break;
}
}
else if(str.equalsIgnoreCase("c"))
{
result.setText("");
res=0;
a=0;
op='\0';
}
}
}
Week-13: Applet
Program:
import java.applet.Applet;
import java.awt.*;
/* <applet code="MyApplet" height="300" width="300">
* </applet>
*/
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
Font f = new Font("Times New Roman", Font.BOLD,30);
g.setFont(f);
g.drawString("Hello Applet!", 50, 25);
}
}
b. Develop an applet that receives an integer in one text field and computes its factorial value
and returns it in another text field, when the button named ―compute‖ is clicked.
Program:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <applet code="Factorial" height="1000" width="1000">
* </applet>
*/
public class Factorial extends Applet implements ActionListener
{
Button b1;
TextField t1,t2;
Label l1,l2;
public void init()
{
b1=new Button("Calculate");
t1=new TextField(10);
t2=new TextField(10);
l1=new Label("Enter A Number to Find Factorial :");
l2=new Label("The Factorial of Given Number is :");
setLayout(new FlowLayout(FlowLayout.LEFT));
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
long fact=1;
if(ae.getActionCommand().equals("Calculate"))
{
int n=Integer.parseInt(t1.getText());
for(int i=n;i>0;i--)
{
fact=fact*i;
}
t2.setText(String.valueOf(fact));
}
}
}