You are on page 1of 31

ExpNo: 1.

(a) Date:
Roots of a Quadratic Equation
1(A). Aim: To write a java program that prints all real solutions to quadratic equation ax2+bx+c=0

2. Description: Write main method in a class named Quadratic. a, b and c are variables of type
double for which we will assign some values. Variable d is used to store discriminant value (i.e.,
b*b – 4*a*c). r1, r2 are two double variables used to store two roots when discriminant value
that is d is greater than zero. When d is greater than zero, the two roots are real. When d is equal
to zero, the two roots are equal. When d is less than zero, the two roots are imaginary.

3. Program:
class Quadratic
{ public static void main(String args[])
{ double a=5,b=10,c=2,r1,r2,d;
d=(b*b)-(4*a*c);
if(d==0)
{ System.out.println("Roots are real and equal");
System.out.println("The roots are : " + (-b/(2*a) ) );
}
else if(d<0)
System.out.println("The roots are imaginary");
else if(d>0)
{ r1=-b+(Math.sqrt(d))/(2*a);
r2=-b-(Math.sqrt(d))/(2*a);
System.out.println("root1=" + r1);
System.out.println("root2=" + r2);
}
}
}

4. Input/Output Processing:

5. Conclusion:

1
ExpNo: 1.(b) Date:

Printing nth Fibonacci Element


1. Aim: To write a java program that uses recursive procedure to print the nth value in the
Fibonacci sequence.

2. Description: The Fibonacci sequence (denoted by f0, f1, f2 …) is as follows: 1, 1, 2, 3, 5, 8,


13, 21, 34, 55 … That is, f0 = 1 and f1 = 1 and each succeeding term is the sum of the two
preceding terms. Typically, recursion is more elegant and requires fewer variables to make the
same calculations. Recursion takes care of its book-keeping by stacking arguments and variables
for each method call. This stacking of arguments, while invisible to the user, is still costly in time
and space. Fibonacci sequence is recursively defined by f0 = 1, f1 = 1, fi+1 = fi + fi-1 for i = 1, 2

3. Program:
class Demo
{
int fib(int n)
{ if(n==1)
return (1);
else if(n==2)
return (1);
else
return (fib(n-1)+fib(n-2));
}
}
class Fib1
{ public static void main(String args[])
{
Demo ob=new Demo();
System.out.println("The 10th fibonacci element is " + ob.fib(10));
}
}

4. Input/Output Processing:

5. Conclusion:

2
ExpNo: 2.(a) Date:

Given Number Is Armstrong or Not


1. Aim: To write a java program that the given number is Armstrong Number or Not.

2. Description: Given a number x, determine whether the given number is Armstrong number
or not. A positive integer of n digits is called an Armstrong number of order n (order is
number of digits) if.

abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....

3. Program:
class ArmstrongExample
{
public static void main(String[] args)
{
int c=0,a,temp;
int n=153;//It is the number to check armstrong
temp=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(temp==c)
System.out.println("armstrong number");
else
System.out.println("Not armstrong number");
}
}

4. Input/Output Processing:

5. Conclusion:

3
ExpNo: 2.(b) Date:
Find the Simple Interest

1. Aim: To write a java program to find the Simple Interest.

2. Description: This is a Java Program to Find the Simple Interest.


Formula:
Simple Interest = (Principal * Rate * Time)/100
Enter the principal, rate of interest and time period as input. Now we use the
given formula to calculate the simple interest.

3. Program:
import java.io.*;

class GFG
{
public static void main(String args[])
{
// We can change values here for
// different inputs
float P = 1, R = 1, T = 1;

/* Calculate simple interest */


float SI = (P * T * R) / 100;
System.out.println("Simple interest = " + SI);
}
}

4. Input/Output Processing:

5. Conclusion:

4
ExpNo: 3.(a) Date:

String Palindrome

1. Aim: To write a java program that checks whether a given string is palindrome or not.

2. Description: First accept a string from the keyboard using BufferedReader class of java.io
package. Create StringBuffer class object and pass the String as argument to that object. Call
reverse() method of StringBuffer object such that the string in that object will get reverse. After
converting that StringBuffer object into String type store it in another String variable. Now by
making use of equals method of String class compare two strings if both are equal then given
string is palindrome otherwise it is not a palindrome.

3. Program:
import java.io.*;
class Palindrome
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Enter the string : ");
String s1=br.readLine();
StringBuffer sb = new StringBuffer( s1 );
sb.reverse();
String s2 = sb.toString();
System.out.println(“The reversed String is : “ + s2);
if( s1.equals(s2) )
System.out.println("Given String is palindrome");
else
System.out.println("Given String is not a palindrome");
}
}

4. Input / Output Processing:

5. Conclusion:

5
ExpNo: 3.(b) Date:

Sorting of Strings
1. Aim: To write a java program to sort a list of names in ascending order.

2. Description: First read number of strings. Accept number of strings into an array. Compare
first string with remaining strings using String class compareTo () method. compareTo () method
compares the given string in dictionary fashion. If the first string is big then by taking a
temporary variable swap the two strings, continue this process till the end of the strings. The
given strings will be in ascending sorted order.

3. Program:
import java.io.*;
class NameSort
{ public static void main(String args[ ]) throws IOException
{ BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter how many names you want");
int n=Integer.parseInt(br.readLine() );
String a[ ]=new String[n];
int i,j;
System.out.println("Enter " + n + " names : ");
for(i=0;i<n;i++)
a[i]=br.readLine();
for(i=0;i<n;i++)
{ for(j=i+1;j<n ;j++)
{ if(a[i].compareTo(a[j])>0)
{ String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("After sorting the names are");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

4. Input/Output Processing:

5.Conclusion:

6
ExpNo: 4.(a) Date:

Counting Words in a given Text


1. Aim: To write a java program to make frequency count of words in a given text.

2. Description: Set is an interface which does not allow any duplication in java.util package.
HashSet is an implementation class for Set interface. First of all store the different types of
words in the entered text using nextToken() method of StringTokenizer class into HashSet
object. By using iterator interface get the individual words one by one and compare that word
with each and every word in that text using nextToken() method of StringTokenizer class. If it
matches then increment word count and display the same.

3. Program:
import java.util.*;
import java.io.*;
class CountWords
{ public static void main(String args[]) throws IOException
{ BufferedReader br = new BufferedReader(new InputStreamReader(
System.in) );
HashSet<String> hs = new HashSet<String>();
System.out.println("Enter a line of text : " );
String s1 = br.readLine();
StringTokenizer st1 = new StringTokenizer( s1 , " ");
while( st1.hasMoreTokens() )
{ hs.add(st1.nextToken() );
}
Iterator it = hs.iterator();
while (it.hasNext() )
{ int count = 0;
String a = (String) it.next();
StringTokenizer st2 = new StringTokenizer( s1, " ");
while( st2.hasMoreTokens() )
{ String b = (String) st2.nextToken();
if (a.equals ( b ) )
count++;
}
System.out.println(a + " count is : " + count);
}
}
}

4. Input / Output Processing:

5. Conclusion:

7
Date:
ExpNo: 4.(b)
Prime Number Generation
1. Aim: To write a java program that prompts the user for an integer and then prints out all prime
numbers up to that integer.

2. Description: A prime number is a positive integer that is exactly divisible only by 1 and itself.
The first few prime numbers are: 2 3 5 7 11 13 17 23 29 31 37 … To do this; let us consider a
number 13. The definition of prime number suggests that to determine whether or not 13 is
prime, we need to divide it in turn by the set of numbers 2, 3, 4, 5 …12. If any of these numbers
divide into 13 without remainder we will know it cannot be prime number.That is, we can test
for mod operation with numbers, from 2 to n-1.

3. Program:
import java.io.*;
class Prime
{ public static void main(String args[])throws IOException
{ int i,j,a=0,n;
BufferedReader br= new BufferedReader(new InputStreamReader (
System.in) );
System.out.println("Enter range : " );
n = Integer.parseInt(br.readLine() );
for(i=2;i<=n;i++)
{ a=0;
for(j=2;j<i;j++)
{
if(i%j==0)
a=1;
}
if(a==0)
System.out.print(i + "\t");
}
}
}

4. Input/Output Processing:

5. Conclusion:

8
ExpNo: 5.(a) Date:

Multiplication of Two Matrices


1. Aim: To write a java program to multiply two given matrices.

2. Description: If the order of matrix A is r1 x c1 and of matrix B is r2 x c2 (number of columns


of A = number of rows of B = c1=r2), then the order of matrix C is r1 x c2, where C = A x B
otherwise matrix multiplication is not possible. First accept number of rows and columns of
matrix A into r1, c1 then accept number of rows and columns of matrix B into r2, c2. If c1 is not
equal to r2 then display a message matrix multiplication is not available otherwise accept two
matrices into two arrays and perform the multiplication operation and store the result in another
array and display the same as result.

3. Program:
public class MatrixMultiplicationExample
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}

4. Input/Output Processing:

5. Conclusion:
9
Date:
ExpNo: 5.(b)
Sum of Integers
1. Aim: To write a java program that reads a line of integers and then displays each integer and
the sum of all integers.

2. Description: The StringTokenizer class allows an application to break a string into tokens.
The discrete parts of a string are called tokens. Therefore, given an input string, we can
enumerate the individual tokens contained in it using StringTokenizer. The default delimiters are
whitespace characters. By parsing individual tokens into integers we will get integers and we can
add those integers to find the sum.

3. Program:
import java.util.*;
import java.io.*;
class SumInt
{ public static void main(String args[ ]) throws IOException
{ BufferedReader br = new BufferedReader ( new InputStreamReader(
System.in) );
System.out.println ("Enter a line of integers : ");
String str= br.readLine ();
StringTokenizer sc=new StringTokenizer (str," ");
System.out.println ("The integers are:");
int total=0;
while(sc.hasMoreTokens())
{ int k=Integer.parseInt(sc.nextToken());
System.out.println (k);
total = total+k;
}
System.out.println("Sum of all integers:"+total);
}
}

4. Input/Output Processing:

5. Conclusion:

10
ExpNo: 6.(a) Date:

Displaying File Properties

1. Aim: To write a java program that reads a file name from the user then displays information
about whether the file exists, whether the file is readable, whether the file is writable, type of file
and the length of the file in bytes.

2. Description:A File object is used to get information or manipulate the information associated
with a disk file; such as the permissions, time, date, directory path, is it readable or writable, file
size, and so on. File class defines many methods that obtain the standard properties of a File
object. For example, getName () returns the file name, and exists() returns true if the file exists,
false if it does not.

3. Program:
import java.io.*;
class FileProp
{ public static void main(String args[]) throws IOException
{ BufferedReader br = new BufferedReader(new InputStreamReader (
System.in));
System.out.println("Enter file name :");
String fname = br.readLine();
File f = new File (fname);
System.out.println ("File name: " + f.getName ());
System.out.println ("Path:"+ f.getPath ());
System.out.println ("Absolute Path:"+ f.getAbsolutePath ());
System.out.println ("Parent:"+ f.getParent ());
System.out.println ("Exists:"+ f.exists ());
if ( f.exists() )
{
System.out.println ("Is writable: "+ f.canWrite ());
System.out.println ("Is readable: "+ f.canRead ());
System.out.println ("Is executable: "+ f.canExecute ());
System.out.println ("Is directory: "+ f.isDirectory());
System.out.println ("File size in bytes: "+ f.length());
}
}
}
4. Input / Output Processing:

5. Conclusion:

11
ExpNo: 6.(b) Date:

Displaying Contents of a file


1. Aim: To write a java program that reads a file and displays the file on the screen, with a line
number before each line.

2. Description: The FileInputStream class creates an InputStream that we can use to read bytes
from a file. When a FileInputStream is created, it is opened for reading. To display a line number
for each line at the time of reading, declare a variable of type int and initialize it with 1 and
increment the variable by 1 whenever a new line character is encountered.

3. Program:
import java.io.*;
class FileRead
{ public static void main(String args[]) throws IOException
{
int ch,ctr=1;
String fname;
BufferedReader br = new BufferedReader(new InputStreamReader (
System.in));
System.out.print("Enter a file name: ");
fname=br.readLine();
FileInputStream fin =new FileInputStream(fname);
System.out.print(ctr+" ");
while((ch=fin.read())!=-1)
{
System.out.print((char)ch);
if(ch=='\n')
{
ctr++;
System.out.print(ctr+" ");
}
}
fin.close();
}
}

4. Input / Output Processing:

5. Conclusion:

12
ExpNo: 6.(c) Date:

Displaying number of Characters, Lines & Words in a File


1. Aim: To write a java program that displays the number of characters, lines and words in a text
file.

2. Description:The FileInputStream class creates an InputStream that we can use to read bytes
from a file.When a FileInputStream is created, it is opened for reading. Take three variables of
type int and initialize it with zero for counting number of characters, words and lines. Read the
contents from file character by character and increment character count by 1 for each character.
Whenever a new line character is encountered then increment line count by 1. Whenever a space
is encountered then increment word count by 1.

3. Program:
import java.io.*;
class FileStat
{ public static void main(String args[]) throws IOException
{ int pre=' ' , ch , ctr=0 , L=0 , w=1;
String fname;
BufferedReader br=new BufferedReader(new InputStreamReader (
System.in));
System.out.print("Enter a file name: ");
fname=br.readLine();
FileInputStream fin = new FileInputStream(fname);
while((ch=fin.read())!=-1)
{ //char count
if(ch!=' ' && ch!='\n')
ctr++;
//line count
if(ch=='\n')
L++;
//word count
if(ch==' ' && pre!=' ')
w++;
pre=ch;
}
System.out.println("Char count="+ctr);
System.out.println("Word count="+(w+(L-1)));
System.out.println("Line count="+L);
}
}
4. Input / Output Processing:

5. Conclusion:
13
ExpNo: 7.(a) Date:

Stack ADT using Arrays


1. Aim: To write a java program that implements stack ADT using an array.

2. Description: Create an interface StackADT with a constant size and declare


methodprototypes push (), pop (), traverse () in that interface. By writing a class implements
those method bodies. Declare a variable top which is initialized with -1 for every push operation
the top is incremented by 1 and an element of type int is stored into an arry stack (i.e stk[]). For
every pop operation the top is decremented by 1. For traverse operation the elements are
displayed starting from stk[top] to stk[0].

3. Program:
import java.io.*;
interface StackADT
{
int SIZE = 10;
void push(int elem);
void pop();
void traverse();
}
class MyClass implements StackADT
{
int top = -1;
int stk[];
MyClass()
{
stk = new int[SIZE];
}
public void push(int elem)
{
if ( top == (SIZE-1) )
System.out.println("Stack is full");
else
{ top++;
stk[top] = elem;
}
}
public void pop()
{
if ( top == -1)
System.out.println("Stack is empty, no element to delete");
else
{ System.out.println("The deleted element is : " + stk[top]);
top--;

14
}
}
public void traverse()
{ if ( top == -1)
System.out.println("Stack is empty, no elements to traverse");
else
{ System.out.println("Elements in the stack are : ");
for(int i= top; i>= 0 ; i--)
System.out.println(stk[i]);
}
}
}
class StackDemo
{ public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader(
System.in));
MyClass ob = new MyClass();
int ch, elem;
do
{
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Traverse");
System.out.println("4.Exit");
System.out.println("Enter your choice : ");
ch = Integer.parseInt(br.readLine());
switch( ch )
{ case 1 : System.out.println("Enter element to insert :");
elem = Integer.parseInt( br.readLine() );
ob.push(elem);
break;
case 2: ob.pop();
break;
case 3: ob.traverse();
break;
case 4: System.exit(0);
}
}while( ch>0 && ch< 5);
}
}
4. Input/Output Processing:

5. Conclusion:
15
Date:
ExpNo: 7.(b)

Infix to Postfix Conversion


1. Aim: To write a java program that converts infix expression into postfix expression.

2. Description: This Program translates an infix expression to a postfix expression. In this


program we take “infix” string as an input and displays “postfix” string. In the process, we use a
stack as a temporary storage. So, instead of writing a separate program for stack operations, the
Infix_Postfix class uses java.util.Stack class.

3. Program:
import java.io.*;
import java.util.*;
class Infix_Postfix
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader( new InputStreamReader (
System.in));
System.out.println("Enter Infix Expression : ");
String s= br.readLine();
Stack<Character> st=new Stack<Character>();
String output="";
int i=0,len=s.length();
char x;
st.push('@');
while(len!=0)
{ char c=s.charAt(i);
if(c=='(')
{ st.push(c);
}
else if(c=='+'||c=='-'||c=='*'||c=='/'||c=='^'||c=='$')
{ check(st,c,output);
st.push(c);
}
else if(c==')')
{ while((x=(Character)st.pop())!='(')
{ output=output+x;
}
}
else
{ output+=s.charAt(i);
}
i=i+1;

16
len--;
}
while((x=(Character)st.pop())!='@')
{ output+=x;
}
System.out.println("postfix Expression is : "+ output);
}
static void check(Stack st,char c,String output)
{ while(priority(c)<=priority((Character)st.peek()))
output=output+st.pop();
}
static int priority(char ch)
{ if(ch=='+'||ch=='-')
return(1);
else if(ch=='*'||ch=='/')
return(2);
else if(ch=='$'||ch=='^')
return(3);
else
return(0);
}
}

4. Input / Output Processing:

5. Conclusion:

17
ExpNo: 7.(c) Date:

Postfix Evaluation
1. Aim: To write a java program that evaluates the postfix expression.

2. Description: This Program illustrates the evaluation of postfix expression. The program
works for expressions that contain only single-digit integers and the four arithmetic operators.
The program uses java.util.Stackclass for creating a stack of integer values.
While evaluating a postfix expression if we encounter an operand then push that operand onto
stack otherwise if we encounter an operator Pop the top two operands from the stack, apply the
operator to them, and evaluate it. Push this result onto the stack. Initially stack is empty

3. Program:
import java.io.*;
import java.util.*;
class MyClass
{
int isoperator(char symbol)
{
if(symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' )
return 1;
else
return 0;
}
double evaluate(String postfix)
{
Stack<Double> stk = new Stack<Double>();
int i;
char symbol;
double oper1,oper2,result;
for(i=0;i<postfix.length();i++)
{
symbol = postfix.charAt(i);
if (isoperator(symbol)==0)
stk.push((double)(symbol-48) );
else
{
oper2 = stk.pop();
oper1 = stk.pop();
result = calculate(oper1,symbol,oper2);
stk.push(result);
}
}//end of for.
result = stk.pop();
return(result);

18
}
double calculate(double oper1,char symbol,double oper2)
{ switch(symbol)
{
case '+' : return(oper1+oper2);
case '-' : return(oper1-oper2);
case '*' : return(oper1* oper2);
case '/' : return(oper1/oper2);
default : return(0);
}
}
}
class Postfix
{
public static void main(String args[]) throws IOException
{ BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter postfix expression : ");
String postfix = br.readLine();
MyClass ob = new MyClass();
System.out.println("The result value is : " + ob.evaluate(postfix));
}
}

4. Input / Output Processing:

5. Conclusion:

19
ExpNo: 8.(a) Date:

Applet to Display a Message


1. Aim: To develop an applet that displays a simple message

2. Description: An applet is a Java program that runs in a browser. Unlike Java applications applets
do not have a main () method. To create applet we can use java.applet.Applet. All applets inherit the
super class ‘Applet’. An Applet class contains several methods that help to control the execution of
an applet. Let the Applet class extends Applet. Provide paint () method in that class. Using
drawstring () method of Graphics class display the message on the applet.

3. Program:
import java.io.*;
import java.awt.*;
import java.applet.Applet;
/*<applet code="App1.class" height=100 width=500></applet>*/
public class App1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("MCA III semester Students",50,60);
setForeground(Color.blue);
}
}

4. Input / Output Processing:

5. Conclusion:

20
ExpNo: 8.(b) Date:

Applet to Calculate Factorial Value


1. Aim: To develop an applet that receives an integer in one text field, and computes as factorial
value and returns it in another text field, when the button named “Compute” is clicked

2. Description: Write a class by extending Applet class and implement ActionListener. Attach
two textfileds and a button to the applet. Attach actionlistener to the button and provide
actionPerformed () method to compute factorial value. First textfield is used for entering a
number and after clicking on the button the result will be displayed on the second textfield.

3. Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;

/*<applet code="App2.class" height=100 width=500></applet>*/

public class App2 extends Applet implements ActionListener


{ JTextField tf1;
JTextField tf2;
JButton b;
JLabel l;
public void init()
{
l =new JLabel("Enter the number & press the button");
tf1=new JTextField("",5);
tf2=new JTextField("",10);
b=new JButton("Compute");
add(l);
add(tf1);
add(tf2);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
String str1;
int fact=1;
if(str=="Compute")
{
int n=Integer.parseInt(tf1.getText());
for(int i=1;i<=n;i++)

21
fact=fact*i;
str1=""+fact;
tf2.setText(str1);
}
}
}

4. Input / Output Processing:

5. Conclusion:

22
ExpNo: 9 Date:

Simple Calculator
1. Aim: To write a java program that works as a simple calculator. Use a grid layout to
arrangebuttons for the digits +,-,*,/,% operations. Add a text field to display the result.

2. Description:Write a class by extending JFrame class of javax.swing package and


implementing ActionListener interface. Attach the components like JTextField, JButtons, two
JPanels to the contentPane() of JFrame by setting grid layout. Attach listeners to the buttons and
implement the actionPerformed method to perform operations. One JPanel is used for placing
textbox and clear buttons, the second JPanel is used to add remaining components.

3. Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Calculator extends JFrame implements ActionListener
{ Container c;
JTextField t1;
String a="",b;
String oper="",s="",p="";
int first=0,second=0,result=0;
JButton b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;
JButton add,sub,mul,div,mod,res,clear;
JPanel p1,p2;
Calculator()
{ c =getContentPane();
p1 = new JPanel();
p2 = new JPanel(new GridLayout(4,4));
t1=new JTextField(a,10);
c.setLayout(new GridLayout(2,1));
b0=new JButton("0");
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");
add=new JButton("+");
sub=new JButton("-");
mul=new JButton("*");
div=new JButton("/");

23
mod=new JButton("%");
res=new JButton("=");
clear = new JButton("CE");
b0.addActionListener(this);
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);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
res.addActionListener(this);
clear.addActionListener(this);
p1.add(t1); p1.add(clear);
p2.add(b0); p2.add(b1); p2.add(b2);
p2.add(b3); p2.add(b4); p2.add(b5);
p2.add(b6); p2.add(b7); p2.add(b8);
p2.add(b9); p2.add(add); p2.add(sub);
p2.add(mul); p2.add(div); p2.add(mod);
p2.add(res);
c.add(p1);
c.add(p2);
}
public void actionPerformed(ActionEvent ae)
{ a=ae.getActionCommand();
if(a=="0" || a=="1" || a=="2" || a=="3" || a=="4" || a=="5"
|| a=="6" || a=="7" || a=="8" || a=="9")
{
t1.setText(t1.getText()+a);
}
if(a=="+" || a=="-" || a=="*" || a=="/" || a=="%")
{
first = Integer.parseInt(t1.getText());
oper = a;
t1.setText("");
}
if(a=="=")
{ if(oper=="+")
result=first+Integer.parseInt(t1.getText());

24
if(oper=="-")
result=first-Integer.parseInt(t1.getText());
if(oper=="*")
result=first*Integer.parseInt(t1.getText());
if(oper=="/")
result=first/Integer.parseInt(t1.getText());
if(oper=="%")
result=first%Integer.parseInt(t1.getText());
t1.setText(result+"");
}
if(a == "CE")
t1.setText("");
}
public static void main(String args[])
{ Calculator ob = new Calculator();
ob.setSize(200,200);
ob.setVisible(true);
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

4. Input / Output Processing:

5. Conclusion:

25
ExpNo: 10 Date:

Mouse Events
1. Aim: To write a java program for handling mouse events.

2. Description: The user may click, release, drag or move a mouse while interacting with the
application. If the programmer knows what the user has done, he can write the code according to
the mouse event. To trap the mouse events, MouseListener and MouseMotionListener interfaces
of jav.awt.event package are used. MouseListener contains five methods mousePressed (),
mouseReleased (), mouseClicked (), mouseEntered (), and mouseExited (). Attach these two
listenersto applet and implement seven methods.

3. Program:
import java.awt.*;
import java.awt.event.*;
public class MouseListener extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}

26
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
4. Input / Output Processing:

5. Conclusion:

27
ExpNo: 11 Date:

Inter Thread Communication


1. Aim: To write a java program that correctly implements Producer consumer problem using
the concept of inter thread communication.

2. Description: In some cases two or more threads should communicate with each other. One
thread output may be send as input to other thread. For example, a consumer thread is waiting for
a Producer to produce the data (or some goods). When the Producer thread completes production
of data, then the Consumer thread should take that data and use it. In producer class we take a
StringBuffer object to store data, in this case; we take some numbers from 1 to 5. These numbers
are added to StringBuffer object. Until producer completes placing the data into StringBuffer the
consumer has to wait. Producer sends a notification immediately after the data production is
over.

3. Program:
class Producer implements Runnable
{ StringBuffer sb;
Producer ()
{ sb = new StringBuffer();
}
public void run ()
{
synchronized (sb)
{
for (int i=1;i<=5;i++)
{ try
{
sb.append (i + " : ");
Thread.sleep (500);
System.out.println (i + " appended");
}
catch (InterruptedException ie){}
}
sb.notify ();
}
}
}
class Consumer implements Runnable
{ Producer prod;
Consumer (Producer prod)
{ this.prod = prod;
}
public void run()
{
synchronized (prod.sb)
28
{
try

{
prod.sb.wait ();
}
catch (Exception e) { }
System.out.println (prod.sb);
}
}
}
class Communicate
{
public static void main(String args[])
{
Producer obj1 = new Producer ();
Consumer obj2 = new Consumer (obj1);
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t2.start ();
t1.start ();
}
}

4. Input / Output Processing:

5. Conclusion:

29
ExpNo: 12 Date:

User Interface
1. Aim: Write a program that creates a user interface to perform integer divisions. The user enters
two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed
in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the
program would throw a Number Format Exception. If Num2 were Zero, the program would
throw an Arithmetic Exception Display the exception in a message dialog box.

2. Description:Write a class by extending Applet class and implementing ActionListener


interface. Attach the components like TextField, Buttons, two Panels to the contentPane() of
Frame by setting grid layout. Attach listeners to the buttons and implement the actionPerformed
method to perform operations.

3. Program:

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

/*<applet code="DivisionExample"width=230 height=250></applet>*/

public class DivisionExample extends Applet implements ActionListener {


String msg;
TextField num1, num2, res;
Label l1, l2, l3;
Button div;

public void init() {


l1 = new Label("Dividend");
l2 = new Label("Divisor");
l3 = new Label("Result");
num1 = new TextField(10);
num2 = new TextField(10);
res = new TextField(10);
div = new Button("Click");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}

30
public void actionPerformed(ActionEvent ae) {
String arg = ae.getActionCommand();
int num1 = 0, num2 = 0;
if (arg.equals("Click")) {
if (this.num1.getText().isEmpty() && this.num2.getText().isEmpty()) {
msg = "Enter the valid numbers!";
repaint();
} else {
try {
num1 = Integer.parseInt(this.num1.getText());
num2 = Integer.parseInt(this.num2.getText());

int num3 = num1 / num2;

res.setText(String.valueOf(num3));
msg = "Operation Succesfull!!!";
repaint();
} catch (NumberFormatException ex) {
System.out.println(ex);
res.setText("");
msg = "NumberFormatException - Non-numeric";
repaint();
} catch (ArithmeticException e) {
System.out.println("Can't be divided by Zero" + e);
res.setText("");
msg = "Can't be divided by Zero";
repaint();
}
}
}
}

public void paint(Graphics g) {


g.drawString(msg, 30, 70);
}
}

4. Input / Output Processing:

5. Conclusion:
31

You might also like