You are on page 1of 55

Week -1:

b. Aim:
To 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:
public class Main {
public static void main(String[] args) {
double a = 2.3, b = 4, c = 5.6;
double root1, root2;
double determinant = b * b - 4 * a * c;
if (determinant > 0) {
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.println("root1 "+Double.toString(root1));
System.out.println("root2 "+Double.toString(root2));
}
else if (determinant == 0) {
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
}
else {
double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
}
}
}
Executed Input and Output:

C . Aim:
Develop a Java application to generate Electricity bill. Create a class with the following members: Consumer no.,
consumer name, previous month reading, current month reading, type of EB connection (i.e domestic or
commercial). Commute the bill amount using the following tariff. If the type of the EB connection is domestic,
calculate the amount to be paid as follows: First 100 units - Rs. 1 per unit 101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit > 501 units - Rs. 6 per unit If the type of the EB connection is commercial,
calculate the amount to be paid as follows: First 100 units - Rs. 2 per unit 101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit > 501 units - Rs. 7 per unit
Program:
import java.io.*;
class UAE extends Exception
{
UAE(String s)
{
super(s);
}
}
public class Electricity
{
public static void main(String a[])throws Exception
{
int i=0,j=1;
while(j!=0)
{
try{
i=0;
System.out.println("Type of electricity bill \n 1.Domestic\n 2.Commercial\n 3.for exit press 0");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
}
catch(Exception e){throw new UAE("enter correct choice");}
if(i==1)
{
try{
System.out.println("Consumer number: ");
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
String connum=br1.readLine();
System.out.println("Consumer name: ");
String coname=br1.readLine();
System.out.println("previous month reading: ");
float prev=Float.parseFloat(br1.readLine());
System.out.println("Current month reading: ");
float curr=Float.parseFloat(br1.readLine());
float s=curr-prev;
if(s<100.0f)
{
System.out.println("your Bill is"+Float.toString(s*1.0f));
}
else if(s<200)
{ System.out.println("your Bill is"+Float.toString(s*2.50f)); }
else if(s<500)
{ System.out.println("your Bill is"+Float.toString(s*4.0f)); }
else
{ System.out.println("your Bill is"+Float.toString(s*6.0f)); }
}

catch(Exception d)
{throw new UAE("enter correct reading");}
}
BufferedReader br2=new BufferedReader(new InputStreamReader(System.in));
if(i==2)
{
try{
System.out.println("Consumer number: ");
String connum=br2.readLine();
System.out.println("Consumer name: ");
String coname=br2.readLine();
System.out.println("previous month reading: ");
float prev=Float.parseFloat(br2.readLine());
System.out.println("Current month reading: ");
float curr=Float.parseFloat(br2.readLine());
float s=curr-prev;
if(s<=100.0f)
{ System.out.println("your Bill is"+Float.toString(s*2.0f)); }
else if(s<=200)
{ System.out.println("your Bill is"+Float.toString(s*4.50f)); }
else if(s<=500)
{ System.out.println("your Bill is"+Float.toString(s*6.0f)); }
else
{ System.out.println("your Bill is"+Float.toString(s*7.0f)); }
}
catch(Exception f)
{throw new UAE("enter correct reading");}
}
if(i==0)
{ j=0;}
}
}
}
Expected Input and Output:

d.1.Aim:
To Write a Java program to multiply two given matrices.
Program:
public class MatrixMul
{
public static void main(String aa[])
{
int a[][]={{1,3},{2,4}};
int b[][]={{4,3},{1,2}};
int c[][]=new int[2][2];
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
{ c[i][j]+=a[i][k]+b[k][j];
System.out.println(c[i][j]+" "); }
}
System.out.println( );
}
}
}
Executed Input and Output:
Week-2:
b) Aim:
To Write Java program on dynamic binding, differentiating method overloading and overriding.
Program:
abstract class arc
{
public abstract void hello();
}
class a extends arc
{
public void hello()
{
System.out.println("hii");
}
}
class b extends arc
{
public void hello()
{
System.out.println("hello");
}
}
class II
{
public static void main(String args[])
{
arc dy=new b();
arc dy1=new a();
dy.hel();
dy1.hel();
}
}
Executed Input and Output:

C . Aim:
To develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen) using
Interfaces.
Program:
import java.io.*;
interface converter
{
public void DollartoInr();
public void EurotoInr();
}
class A implements converter
{
public void DollartoInr()
{
try{
float b,c;
System.out.println("enter Dollars : ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
c=Float.parseFloat(br.readLine());
b=c*70;
System.out.println("the Indian currency is : "+Float.toString(b));
}catch(Exception e){}
}
public void EurotoInr()
{
try{
float d,f;
System.out.println("enter Euro's : ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
d=Float.parseFloat(br.readLine());
f=d*70;
System.out.println("the Indian currency is : "+Float.toString(f));
}catch(Exception s){}
}
}
class MainClass
{
public static void main(String a[])
{
A obj=new A();
obj.DollartoInr();
obj.EurotoInr();
}
}
Week-3:
a.Aim:
To Write Java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number is read
display it only if it’s not a duplicate of any number already read display the complete set of unique values
input after the user enters each new value.
Program:
import java.io.*;
public class MainClass {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a[]=new int[5];
int x=0,n;
System.out.println("enter the 5 elements between 10 and 100");
while(x<5)
{
n=Integer.parseInt(br.readLine());
int j;
for( j=0;j<=x;j++)
{
if(n==a[j])
{
for(int k=0;k<x;k++)
{ System.out.println(a[k]); }
break;
}
}
if(j>x)
{ a[x]=n;
System.out.println(a[x]);
++x; }
}
}
}
b. Aim:
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.io.*;
abstract class Shape
{
float x,y,z;
public abstract void area();
}
class rectangle extends Shape
{
public void area()
{
try{
System.out.println("enter length and breadth of a rectangle");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Float.parseFloat(br.readLine());
y=Float.parseFloat(br.readLine());
z=x*y;
System.out.println("the srea of rectangle is "+Float.toString(z));
}
catch(Exception e){}
}
}
class square extends Shape
{
public void area()
{
try{
System.out.println("enter a side for the area of square");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Float.parseFloat(br.readLine());
z=x*x;
System.out.println("the area of square is " +Float.toString(z));
}
catch(Exception e){}
}
}
class triangle extends Shape
{
public void area()
{
try{
System.out.println("enter the vertices for the area of triangle");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Float.parseFloat(br.readLine());
y=Float.parseFloat(br.readLine());
z=0.5f*x*y;
System.out.println("the area of triangle is : "+Float.toString(z));
}catch(Exception e){}
}
}
class dyn
{
public static void main(String a[])
{
rectangle b=new rectangle();
square c=new square();
triangle d=new triangle();
b.area();
c.area();
d.area();
}
}
Executed Input and Output:

C.Aim:
Write a Java program to read the time intervals (HH:MM) and to compare system time if the system Time
between your time intervals print correct time and exit else try again to repute the same thing. By using String
Toknizer class.
Program:
import java.io.*;
import java.util.*;
import java.text.*;
public class Time
{
public static void main(String ar[])
{
int HOUR,SECOND,MINUTE;
Scanner s=new Scanner(System.in);
System.out.println(“Enter seconds : “);
int a=s.nextInt();
System.out.println(“Enter Minutes : “);
int b=s.nextInt();
System.out.println(“Enter Hours : “);
int c=s.nextInt();
GregorianCalendar date=new GregorianCalendar();
int second=date.get(Calendar.SECOND);
int minute=date.get(Calendar.MINUTE);
int hour=date.get(Calendar.HOUR);
if(second >a)
SECOND=second-a;
else
SECOND=a-second;
if(minute >b)
MINUTE=minute-b;
else
MINUTE=b-minute;
if(hour>c)
HOUR=hour-c;
else
HOUR=c-hour;
System.out.println(“Difference between two times is “+HOUR+”:”+MINUTE+”:”+SECOND);
} }
Excecuted Input and Output:

Week-4:
a. Aim:
Write a Java program to implement user defined exception handling.
Program:
import java.io.*;
class UAE extends Exception
{
UAE(s)
{ super(s); }
}
class voter
{
public static void main(String aa[])
{
try{
System.out.println("enter age");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a=Integer.parseInt(br.readLine());
if(a<18)
{ throw new UAE(); }
catch(UAE e)
{System.out.println(e.getMessage());}
else
{ System.out.println("eligible"); }
}
catch(Exception ee){}
}

Week-5:
a.Aim:
Write a Java 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.*;
public class week5a extends JFrame implements ActionListener
{
JButton b1;
JTextField t1,t2,t3;
GridBagConstraints gc;
public week5a()
{
setSize(400,600);
setLayout(new GridBagLayout());
gc=new GridBagConstraints();
b1=new JButton("divide");
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
addC(new JLabel("enter 1st number"),1,1,1,1);
addC(t1,1,2,1,1);
addC(new JLabel("enter 2nd number"),2,1,1,1);
addC(t2,2,2,1,1);
addC(b1,3,1,1,1);
addC(new JLabel("result"),4,1,1,1);
addC(t3,4,2,1,1);
b1.addActionListener(this);
setVisible(true);
}
public void addC(Component cc,int r,int c,int w,int h)
{
gc.gridx=c;
gc.gridy=r;
gc.gridwidth=w;
gc.gridheight=h;
gc.fill=gc.BOTH;
gc.fill=gc.BOTH;
add(cc,gc);
}
public static void main(String a[])
{ new week5a(); }
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
try{
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
int c=a/b;
t3.setText(Integer.toString(c));
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(null,ee.getMessage(), "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
Executed Input and Output:

b.Aim:
Write a Java program that creates three threads. First thread displays ―Good Morningǁ every one second, the
second thread displays ―Helloǁ every two seconds and the third thread displays ―Welcomeǁ every three
seconds.
Program:
class MT1
{
public static void main(String a[]) throws Exception
{
Thread t1=Thread.currentThread();
t1.setName("arc");
t1.setPriority(1);
for(int i=0;i<5;i++)
{
System.out.println("Good Morning");
Thread.sleep(1000);
}
Thread t2=Thread.currentThread();
t2.setName("arc123");
t2.setPriority(2);
for(int j=0;j<3;j++)
{
System.out.println("hello");
Thread.sleep(3000);
}
Thread t3=Thread.currentThread();
t3.setName("arc123");
t3.setPriority(3);
for(int j=0;j<3;j++)
{
System.out.println("welcome");
Thread.sleep(5000);
}
}
}
Executed Input and Output:

Week-6:
a. Aim:
Write a java program to split a given text file into n parts. Name each part as the name of the original file
followed by part where n is the sequence number of the part file.
Program:
import java.io.*;
public class Splitter
{
public static void main(String a[])
{
try{
byte b[]=new byte[1000000];
int x=1,j=0;
String s="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("path:");
String path=br.readLine();
FileInputStream fin=new FileInputStream(path);
int readbytes;
while(fin.available()!=0)
{
j=0;
s="";
if(x<=9)
{ s=path+".00"+x; }
else
{ s=path+".0"+x; }
FileOutputStream fot=new FileOutputStream(s);
while(j<50000000 && fin.available()!=0)
{
readbytes=fin.read(b,0,1000000);
j=j+readbytes;
fot.write(b,0,readbytes);
}
System.out.println("part "+x+"created");
x++;
}
System.out.println("file splitted ");
fin.close();
}
catch(Exception e)
{e.printStackTrace();}
}
}
b.Aim:
Write a Java program that reads a file name from the user, displays information about whether the file exists,
whether the file is readable, or writable, the type of file and the length of the file in bytes.
Program:
import java.io.*;
class filedemo
{
public static void p(String str)
{ System.out.println(str); }
public static void analyze(String s)
{
File f=new File(s);
if(f.exists())
{
p(f.getName()+" is a file");
p(f.canRead()?"is readable":" is not readable");
p(f.canWrite()?" is writable":" is not writable");
p("Filesize:"+f.length()+"bytes");
p("File last mdified:"+f.lastModified());
}
if(f.isDirectory())
{
p(f.getName()+"is directory");
p("List of files");
String dir[]=f.list();
for(int i=0;i<dir.length;i++)
p(dir[i]);
}
}
}
public class FileDetails
{
public static void main(String rr[])throws IOException
{
filedemo fd=new filedemo();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name:");
String s=br.readLine();
fd.analyze(s);
}
}

Week-7:
a . Aim:
Write a java program that displays the number of characters, lines and words in a text file.
Program:
import java.util.*;
import java.io.*;
class Myfile
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;

char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;
}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n);
}
}
b.Aim:
Write a java program that reads a file and displays the file on the screen with line number before each line.
Program:
import java.util.*;
import java.io.*;
class Rfile
{
public static void main(String args[])throws IOException
{
int j=1;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.next();
FileInputStream f=new FileInputStream(str);
System.out.println("\nContents of the file are");
int n=f.available();
System.out.print(j+": ");
for(int i=0;i<n;i++)
{
ch=(char)f.read();
System.out.print(ch);
if(ch=='\n')
{ System.out.print(++j+": ");
}
}
}
}

Week-8:
a. Aim:
Write a Java program that correctly implements producer consumer problem using the concept of inter thread
communication.
Program:
public class ProducerConsumer
{
public static void main(String[] args)
{
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Shop
{
private int materials;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
try
{
wait();
}
catch (InterruptedException ie)
{
}
}
available = false;
notifyAll();
return materials;
}
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
materials = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread
{
private Shop Shop;
private int number;
public Consumer(Shop c, int number)
{
Shop = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = Shop.get();
System.out.println("Consumed value " + this.number+ " got: " + value);
}
}
}
class Producer extends Thread
{
private Shop Shop;
private int number;

public Producer(Shop c, int number)


{
Shop = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
Shop.put(i);
System.out.println("Produced value " + this.number+ " put: " + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}

b.Aim:
Develop a Java application for stack operation using Buttons and JOptionPane input and Message dialog box.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class stack extends JFrame implements ActionListener
{
JButton push,pop;
JTextArea ta;
JTextField t;
JPanel p,p1;
int top=-1;
int stck[]=new int[5];
GridBagConstraints gc;
stack()
{
setSize(600,600);
setLocation(300,300);
setLayout(new GridBagLayout ());
gc=new GridBagConstraints();
push=new JButton("PUSH");
pop=new JButton("pop");
ta=new JTextArea(10,15);
t=new JTextField(10);
p=new JPanel();
p1=new JPanel();
p1.add(new JLabel("enter the value "));
p.add(t);
p.setBounds(60,90,300,300);
addC(new JLabel("push"),1,1,1,1);
addC(push,1,2,1,1);
addC(new JLabel(" "),2,1,1,1);
addC(p1,2,2,1,1);
addC(p,2,3,2,2);
addC(new JLabel(" "),2,4,1,1);
addC(new JLabel("the stack is"),2,5,1,1);
addC(ta,2,6,1,1);
addC(new JLabel("POP"),3,1,1,1);
addC(pop,3,2,1,1);
push.addActionListener(this);
pop.addActionListener(this);
ta.setEditable(false);
setVisible(true);
}
public void addC(Component cc,int r,int c,int w,int h)
{
gc.gridx=c;
gc.gridy=r;
gc.gridheight=h;
gc.gridwidth=w;
gc.fill=gc.BOTH;
add(cc,gc);
}
public static void main(String a[])
{ new stack(); }
public void push(int data)
{
++top;
stck[top]=data;
}
public void pop()
{
int data;
data=stck[top];
top--;
}
public void actionPerformed(ActionEvent e)
{
try
{
if(e.getSource()==push)
{
if(top==5)
{
JOptionPane.showMessageDialog(null,"stack overflow:::::cannot enter values", "Error",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
ta.setText(" ");
int data;
data=Integer.parseInt(t.getText());
push(data);
JOptionPane.showMessageDialog(null,"value pushed successfully", "Error",
JOptionPane.INFORMATION_MESSAGE);
for(int i=0;i<=top;i++)
{
ta.append("\n"+Integer.toString(stck[i])+"--position "+Integer.toString(i));
}
}
}
if(e.getSource()==pop)
{
t.setEditable(false);
ta.setText(" ");
pop();
JOptionPane.showMessageDialog(null,"value popped", "Error", JOptionPane.INFORMATION_MESSAGE);
for(int i=0;i<=top;i++)
{
ta.append("\n"+Integer.toString(stck[i])+"--position "+Integer.toString(i));
}
t.setText(" ");
t.setEditable(true);
}
}
catch(Exception t)
{ JOptionPane.showMessageDialog(null,"Do not enter non integers and do not push a value with out entering
numbers", "Error", JOptionPane.INFORMATION_MESSAGE);}
}
}
C.Aim:
Develop a Java application to perform Addition, Division, Multiplication and substraction using JOption Pane
dialog Box and Text fields.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Maths extends JFrame implements ActionListener
{
JTextField n1,n2,res;
JButton add,sub,mul,div,radd,rsub,rmul,rdiv,can;
JLabel ln1,ln2,lres,lg;
GridBagConstraints gc;
Maths()
{
setTitle("calculations");
setSize(800,800);
setLocation(300,300);
setLayout(new GridBagLayout());
n1=new JTextField(10);
n2=new JTextField(10);
res=new JTextField(10);
add=new JButton("Addition");
sub=new JButton("Subtraction");
mul=new JButton("Multiplication");
div=new JButton("division");
radd=new JButton("Add");
can=new JButton("cancel");
rsub=new JButton("Subtract");
rmul=new JButton("Multiply");
rdiv=new JButton("divide");
ln1=new JLabel("enter number: ");
ln2=new JLabel("enter another number : ");
lres=new JLabel("result : ");
lg=new JLabel(" ");
gc=new GridBagConstraints();
res.setEditable(false);
addC(add,1,1,1,1);
addC(sub,2,1,1,1);
addC(mul,3,1,1,1);
addC(div,4,1,1,1);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
radd.addActionListener(this);
rsub.addActionListener(this);
rmul.addActionListener(this);
rdiv.addActionListener(this);
can.addActionListener(this);
setVisible(true);
}
public void addC(Component cc,int r,int c,int w,int h)
{
gc.gridx=c;
gc.gridy=r;
gc.gridwidth=w;
gc.gridheight=h;
gc.fill=gc.BOTH;
add(cc,gc);
}
public static void main(String a[])
{ new Maths(); }
public void actionPerformed(ActionEvent e)
{
try{
if(e.getSource()==add)
{
remove(add);
remove(sub);
remove(mul);
remove(div);
addC(ln1,1,1,1,1);
addC(n1,1,2,1,1);
addC(ln2,2,1,1,1);
addC(n2,2,2,1,1);
addC(lres,3,1,1,1);
addC(res,3,2,1,1);
addC(radd,4,1,1,1);
addC(lg,4,2,1,1);
addC(can,4,3,1,1);
setVisible(true);
}
if(e.getSource()==sub)
{
remove(add);
remove(sub);
remove(mul);
remove(div);
addC(ln1,1,1,1,1);
addC(n1,1,2,1,1);
addC(ln2,2,1,1,1);
addC(n2,2,2,1,1);
addC(lres,3,1,1,1);
addC(res,3,2,1,1);
addC(rsub,4,1,1,1);
addC(lg,4,2,1,1);
addC(can,4,3,1,1);
setVisible(true);
}
if(e.getSource()==mul)
{
remove(add);
remove(sub);
remove(mul);
remove(div);
addC(ln1,1,1,1,1);
addC(n1,1,2,1,1);
addC(ln2,2,1,1,1);
addC(n2,2,2,1,1);
addC(lres,3,1,1,1);
addC(res,3,2,1,1);
addC(rmul,4,1,1,1);
addC(lg,4,2,1,1);
addC(can,4,3,1,1);
setVisible(true);
}
if(e.getSource()==div)
{
remove(add);
remove(sub);
remove(mul);
remove(div);
addC(ln1,1,1,1,1);
addC(n1,1,2,1,1);
addC(ln2,2,1,1,1);
addC(n2,2,2,1,1);
addC(lres,3,1,1,1);
addC(res,3,2,1,1);
addC(rdiv,4,1,1,1);
addC(lg,4,2,1,1);
addC(can,4,3,1,1);
setVisible(true);
}
if(e.getSource()==radd)
{
int i,j;
i=Integer.parseInt(n1.getText());
j=Integer.parseInt(n2.getText());
res.setText(Integer.toString(i+j));
}
if(e.getSource()==rsub)
{
int i,j;
i=Integer.parseInt(n1.getText());
j=Integer.parseInt(n2.getText());
res.setText(Integer.toString(i-j));
}
if(e.getSource()==rmul)
{
int i,j;
i=Integer.parseInt(n1.getText());
j=Integer.parseInt(n2.getText());
res.setText(Integer.toString(i*j));
}
if(e.getSource()==rdiv)
{
int i,j;
i=Integer.parseInt(n1.getText());
j=Integer.parseInt(n2.getText());
res.setText(Integer.toString(i/j));
}
if(e.getSource()==can)
{
n1.setText(" ");
n2.setText(" ");
res.setText(" ");
}
}catch(Exception ee){ JOptionPane.showMessageDialog(null,"enter integers", "Error",
JOptionPane.INFORMATION_MESSAGE);}
}
}
Week-9:
a. Aim:
Develop a Java application for the blinking eyes and mouth should open while blinking.
Program:
import java.awt.*;
import java.applet.*;
public class Pucca extends Applet {
public Pucca(){
setSize(700, 700); }
public void paint(Graphics g){
Color white = new Color(255,255,255);
g.setColor(white);
g.fillOval(600, 100, 125, 125); //left white fill eye
g.setColor(Color.BLA-CK);
g.drawOval(600, 100, 125, 125); // left big black line eye
g.setColor(white);
g.fillOval(700, 100, 125, 125); //right white fill eye
g.setColor(Color.BLA-CK);
g.drawOval(700, 100, 125, 125); //right big black line eye
Color blue = new Color(0, 160, 198);
g.setColor(blue);
g.fillOval(635, 130, 51, 51); // left blue fill eye
g.setColor(Color.BLA-CK);
g.drawOval(635, 130, 50, 50); // left black small line eye
g.setColor(blue);
g.fillOval(735, 130, 51, 51); // right blue fill eye
g.setColor(Color.BLA-CK);
g.drawOval(735, 130, 50, 50); // right black small line eye
g.setColor(Color.BLA-CK);
g.fillOval(650, 145, 20, 20); // left black iris
g.setColor(Color.BLA-CK);
g.fillOval(750, 145, 20, 20); // right black iris
}
}
public class Pucca extends Applet {
public Pucca() {
setSize(700, 700);
Thread t = new Thread(new Runnable() {
private int xDelta = -1;
private int yDelta = 0;
private int blinkCount = 0;
@Override
public void run() {
while (true) {
try {
Thread.sleep(40);
} catch (InterruptedException ex) {
}
xOffset += xDelta;
double irisSize = eyeSize.width * irisScale;
double range = ((eyeSize.width - irisSize) / 2);
if (xOffset <= -range) {
xOffset = -(int) range;
xDelta *= -1;
} else if (xOffset >= range) {
xOffset = (int) range;
xDelta *= -1;
}
blinkCount++;
if (blink && blinkCount > 10) {
blink = false;
blinkCount = 0;
} else if (blinkCount > 25) {
blink = true;
blinkCount = 0;
}
repaint();
}
}
});
t.setDaemon(true);
t.start();
}
private boolean blink = false;
private int xOffset, yOffset = 0;
private Dimension eyeSize = new Dimension(125, 125);
private Point left = new Point(20, 20);
private Point right = new Point(left.x + 100, left.y);
private double irisScale = 0.4;
private double pupilScale = 0.16;
//paint method
@Override
public void paint(Graphics g) {
super.paint(g);
paintEye(g, new Rectangle(left, eyeSize));
paintEye(g, new Rectangle(right, eyeSize));
}
protected void paintEye(Graphics g, Rectangle bounds) {
Color white = new Color(255, 255, 255);
if (blink) { g.setColor(Color.YELLOW); }
else {
g.setColor(white);
}
g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height); //left white fill eye
g.setColor(Color.BLACK);
g.drawOval(bounds.x, bounds.y, bounds.width, bounds.height); // left big black line eye
if (!blink) {
Color blue = new Color(0, 160, 198);
paintEyePartAt(g, bounds, irisScale, blue);
paintEyePartAt(g, bounds, pupilScale, Color.BLACK);
}
}
private void paintEyePartAt(Graphics g, Rectangle bounds, double delta, Color color) {
int width = (int) (bounds.width * delta);
int height = (int) (bounds.height * delta);
g.setColor(color);
g.fillOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width, height); // left blue fill eye
g.setColor(Color.BLACK);
g.drawOval(
xOffset + bounds.x + ((bounds.width - width) / 2),
yOffset + bounds.y + ((bounds.height - height) / 2),
width, height); // left blue fill eye
}
}
Week-10:
a. Aim:
Develop a Java application by using JtextField to read decimal value and converting a decimal number into
binary number then print the binary value in another JtextField.
Program:
importjava.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class DecimalToBinary extends JFrame implements
ActionListener {
private JPanel contentPane;
private JTextField txtDecimal;
private JTextField txtBinary;
/**
* Launch the application.
*/
public static void main(String[] args) {
new DecimalToBinary();
}
/**
* Create the frame.
*/
public DecimalToBinary() {
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLabel("Decimal",12, 16, 80, 19));
contentPane.add(getLabel("Binary",12, 47, 80, 19));
txtDecimal = getTextField(90, 16, 126, 19);
contentPane.add(txtDecimal);
txtBinary = getTextField(90, 47, 126, 19);
contentPane.add(txtBinary);
JButton cmdConvert = new JButton("Convert");
cmdConvert.setFont(new Font("Dialog", Font.PLAIN,
11));
cmdConvert.addActionListener( this );
cmdConvert.setBounds(227, 16, 80, 50);
contentPane.add(cmdConvert);
setResizable(false);
setTitle("Decimal To Binary");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 330, 114);
setLocationRelativeTo( null );
setVisible( true );
}
private JLabel getLabel( String caption, int x, int y, int w,
int h ) {
JLabel lbl = new JLabel( caption );
lbl.setBounds(x, y, w, h);
return lbl;
}
private JTextField getTextField( int x, int y, int w, int h )
{
JTextField tf = new JTextField();
tf.setBounds(x, y, w, h);
return tf;
}
@Override
public void actionPerformed(ActionEvent evt) {
try {
int decimal = Integer.parseInt(
txtDecimal.getText() );
String str ="";
for(;decimal>0;){
int binary = decimal%2;
str = Integer.toString(binary) + str;
decimal /= 2;
}
txtBinary.setText( str );
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog( null,
e.getMessage() );
txtDecimal.setText( "" );
}
}
}

Week-11
a. Aim :
To develop 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.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=Mouse width=600 height=500>
</applet>*/
public class Mouse extends Applet implements MouseListener,MouseMotionListener
{ int X=30,Y=30;
String msg="MOUSE EVENTS";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.white);
}
public void mouseEntered(MouseEvent me)
{
msg="MOUSE ENTERED";
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent me)
{
msg="MOUSE EXITED";
setBackground(Color.red);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent me)
{
msg="MOUSE PRESSED";
setBackground(Color.yellow);
showStatus("Mouse Pressed");
repaint();
}
public void mouseReleased(MouseEvent me)
{
msg="MOUSE RELEASED";
setBackground(Color.green);
showStatus("Mouse Released");
repaint();
}
public void mouseMoved(MouseEvent me)
{
msg="MOUSE MOVED";
X=me.getX();
Y=me.getY();
setBackground(Color.blue);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent me)
{
msg="MOUSE DRAGGED";
setBackground(Color.pink);
showStatus("Mouse Dragged at ("+me.getX()+","+me.getY()+")");
repaint();
}
public void mouseClicked(MouseEvent me)
{
setBackground(Color.green);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

b. Aim :
To develop a java application to demonstrate the key event handlers
Program :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=Key width=600 height=500>
</applet>*/
public class Key extends Applet implements KeyListener
{
int X=40,Y=40;
String msg="KEY EVENTS";
public void init()
{
setBackground(Color.black);
setForeground(Color.yellow);
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
msg="KEY PRESSED";
setBackground(Color.pink);
showStatus("Key Pressed");
repaint();
}
public void keyReleased(KeyEvent ke)
{
msg="KEY RELEASED";
setBackground(Color.red);
showStatus("Key Released");
repaint();
}
public void keyTyped(KeyEvent ke)
{
msg="KEY TYPED IS";
msg+=ke.getKeyChar();
setBackground(Color.black);
showStatus("Key Typed");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
Week-12
a .Aim:
To develop a Java application to find the maximum value from the given type of elements using a generic
function.
Program:
public class MainClass {
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x; // assume x is initially the largest
if (y.compareTo(max) > 0)
max = y; // y is the largest so far
if (z.compareTo(max) > 0)
max = z; // z is the largest
return max; // returns the largest object
} // end method maximum
public static void main(String args[]) {
System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));
System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6,
8.8, 7.7));
System.out.printf("Maximum of %s, %s and %s is %s\n", "pear", "apple", "orange", maximum(
"pear", "apple", "orange"));
}
}

b. Aim:
To develop a Java application 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.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/<applet code="Calculator1" width=300 height=300></applet>/
public class Calculator1 extends Applet implements ActionListener
{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}

for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
public void actionPerformed(ActionEvent ae)
{

String str=ae.getActionCommand();

if(str.equals("+")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("=")) { str1="";
if(oper.equals("+")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));}
}}}
C .Aim:
To develop a Java application for handling mouse events.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
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("Moving mouse at " + me.getX() + ", " + me.getY()); }
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
Week-13:
a. Aim: To Write a java program establish a JDBC connection, create a table student with properties name,
register number, mark1,mark2, mark3. Insert the values into the table by using the java.
Program:
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = “com.mysql.jdbc.Driver”;
static final String DB_URL = “jdbc:mysql://localhost/STUDENTS”;
// Database credentials
static final String USER = “username”;
static final String PASS = “password”;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
//STEP 3: Open a connection
System.out.println(“Connecting to a selected database…”);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(“Connected database successfully…”);
//STEP 4: Execute a query
System.out.println(“Creating table in given database…”);
stmt = conn.createStatement();
String sql = “CREATE TABLE STUDENT ” + “(RollNo INTEGER, ” + ” Name VARCHAR(255), ” +
” Marks1 INTEGER ” + ” Marks2 INTEGER, ” + ” Marks3 INTEGER, “)”;
stmt.executeUpdate(sql);
System.out.println(“Created table in given database…”);
String sql1=”INSERT INTO STUDENTS (RollNo,Name,Marks1,Marks2,Marks3) values (1,”a”,21,23,34)”;
stmt.executeUpdate(sql1);
System.out.println(“data inserted into table”);
}
catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}
catch(SQLException se){ }// do nothing
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace(); }//end finally try
}//end try
System.out.println(“Goodbye!”);
}//end main
}//end JDBCExample

You might also like