Sunday, 7 October 2012

JAVA LAB RECORD -2012



Ex.No.1       Quadratic Equation
Aim:  To print all Real Solutions to the quadratic equation.
Algorithm:
Step 1: Start
Step 2: Declare the variables for 3 values as in ax2+bx+c=0
Step 3: Get the input from the user for the 3 values
Step 4: Process the equation by the formulae:
b2-4ac which is the discriminate
if discriminate is = 0, then x1=x2=-b/(2*a) and display “Roots are Real & equal”
if discriminate is >0,then  x1=(-b+Math.sqrt(disc))/(2*a); and x2=(-b-Math.sqrt(disc))/(2*a);
and display “Roots are Real & unequal”
else display “No real Solutions”
Step 5:  Stop

/* Quadratic Equation */
 import java.io.*;
class Quadratic
{
public static void main(String args[]) throws IOException
{
 double x1,x2,disc, a,b,c;
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("Enter a,b,c Values");
a=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
c=Double.parseDouble(br.readLine());
disc=(b*b)-(4*a*c);
if(disc==0)
{
System.out.println("Roots are real and equal");
x1=x2=-b/(2*a);
System.out.println("Roots are"+x1+","+x2);
}
else if(disc>0)
{
System.out.println("Roots are real and unequal");

x1=(-b+Math.sqrt(disc))/(2*a);
x2=(-b-Math.sqrt(disc))/(2*a);
System.out.println("Roots are"+x1+","+x2);
}
else
{
System.out.println("There are no real solutions");
}
}
}
  
Output:
Enter a,b,c Values
6  8  4
There are no real solutions
Enter a,b,c Values
5  15 6
Roots are real and unequal
Roots are -0.4753049234040402,-2.5246950765959597
Enter a,b,c Values
1  -4  4
Roots are real and equal
Roots are 2.0,2.0


Ex.no.2(a)   Fibonacci Series – Non recursive
Aim: To write a program that uses non recursive function to print the nth value in the Fibonacci sequence.
Algorithm:  
Step 1: Start
Step 2: Initialize and assign the  variables
Step 3: The first two values in the sequence are 1 & 1
Step 4:  Start printing from first two values and find the sum of preceding two values  for next value and print & vice versa by exchanging their values
Step 5: Stop
 
 Fibonacci Series – Non recursive */
class fibonacci
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
System.out.println("*********Fibonacci
Series*****");
int f1,f2=0,f3=1;
for(int i=1;i<=num;i++)
{
System.out.print(" "+f3+" ");
f1=f2;
f2=f3;
f3=f1+f2;
}
}
}



Output:
*********Fibonacci Series*****
1        1  2  3  5  8  13  21  34  55

  

Ex. no.2(b)                       Fibonacci Series– Recursive
Aim : To write a program that uses recursive function to print the nth value in the Fibonacci sequence.

Algorithm:
Step 1: Start
Step 2: Initialize the variables 
Step 3: Get input from the user till which number the Fibonacci series  is to be printed
Step 4:  if the number =0 &1 return the number else return the Fibonacci number using recursion.
Step 5: Start printing from current item and then increase the counter and return preceding item
Step 6: Repeat step 5 until the counter reaches the maximum number
Step 7: Display the Fibonacci series
Step 8: Stop
/* Fibonacci Series – Recursive */
import java.io.*;
public class fibnum{
public static long FibonacciMethod(long number){
if((number==0)|| (number ==1))
return number;
else
return FibonacciMethod(number -1)+FibonacciMethod(number-2);
}
public static void main(String[]args){
try{
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter How many number you want in series:");
int Number=Integer.parseInt(dis.readLine());
System.out.print("Fibonacci Series:");
for(int counter=1;counter<=Number;counter++)
{
System.out.print(FibonacciMethod(counter));
System.out.print(" ");
}}
catch(Exception e){
System.out.println(e);
}
}
}


Output:
Enter How many number you want in series:10
Fibonacci Series:1 1 2 3 5 8 13 21 34 55

      
Ex. No. 3(a)Print all prime numbers up to given Integer   
Aim: To print out all the prime numbers in a series up to the given integer range.
Algorithm:
Step 1: Start
Step 2: Initialize the variables
Step 3: Get the input from the user till which range the prime numbers to be printed in a series
Step 4: Check the number if it is prime or not by “modulus”
if the remainder is zero, skip the element
else return the number
Step 5: Repeat the step 4 until the input range is reached
Step 6: Stop

/* Print all prime numbers up to given Integer */
import java.io.*;
class prime
{
public static void main(String args[])throws IOException
{
int i;
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number till which the prime numbers has to  be printed:");
int num=Integer.parseInt(bf.readLine());
System.out.println("*****Prime Numbers*****");
for(i=1;i<num;i++)
{
int j;
for(j=2;j<i;j++)
{
int n=i%j;
if(n==0)
{
break;
}
}
if(i==j)
{
System.out.print(" "+i);
}
}
}
}



Output:
Enter the number till which the prime numbers has to printed:
60
*****Prime Numbers*****
 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59





Ex. No: 3(b)              Matrix Multiplication
Aim: To implement matrix multiplication and print the elements
Algorithm:
Step 1: Start
Step 2: Initialize the variables and input the user’s choice
Step 3:  Get the number of rows and columns
Step 4: Using the strategy -  check if the two matrices are square matrices
Step 5: Multiply the first row of first matrix with the first column of second matrix
Step 6: Repeat the step 5 for all the rows
Step 7: Display the resultant matrix
Step 8: Stop

/*Matrix Multiplication */
import java.lang.*;
import java.io.*;
class arraymul
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter # of rows");
int m=Integer.parseInt(br.readLine());
System.out.print("Enter the # of columns");
int n=Integer.parseInt(br.readLine());
int a[][]=new int[m][n];
int i,j,k;
System.out.println("Enter First Matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.print("Enter the # of Rows");
int p=Integer.parseInt(br.readLine());
System.out.print("Enter the # of Columns");
int q=Integer.parseInt(br.readLine());
int b[][]=new int[p][q];
System.out.println("Enter Second Matrix");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
int c[][]=new int[m][i];
if(n==p)
{
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{c[i][j]=0;
for(k=0;k<p;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
System.out.println("****Resultant Matrix is:****\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.println(" ");
}
}
}
}

 Output:
Enter # of rows: 2
Enter the # of columns: 2
Enter First Matrix
5  5
6  6
Enter the # of Rows: 2
Enter the # of Columns: 2
Enter Second Matrix
12  32
5     2

****Resultant Matrix ****

85      170
102     204




 Ex. No. 3( c)             Sum of all the Integers   

Aim:  To read line of integers and display them along with the sum of integers using String Tokenizer  class of java.util
Algorithm:
Step 1: Start
Step 2: Get the input from the user
Step 3: Count the tokens one by one  using StringTokenizer() class of java.util
Step 4: Return  the  sum using “hasMoreTokens()”
Step5: Print the sum of all integers
Step 6:  Stop


/* Sum of all the Integers */
import java.io.*;
import java.util.*;
class jtokens{
public static void main (String ar[]) throws Exception{
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader br=new BufferedReader (isr);
System.out.println("Enter Numbers");
String S=br.readLine();
int sum=0;
StringTokenizer st=new StringTokenizer (S," ");
System.out.println("The Given Numbers :");
while (st.hasMoreTokens ()){
String sl= st.nextToken();
int n= Integer.parseInt (sl);
System.out.println(n);
sum=sum+n;
}
System.out.println("The Sum of all Integers:");
System.out.println(sum);
}
}


Output:
Enter Numbers:
1 2 3 6 5 4 9 8 7
The Given Numbers :
1  2 3  6  5 4  9  8 7
The Sum of all Integers:
45





Ex.No. 3(d)         Palindrome (String )
Aim: To check whether the given string is a palindrome or not
Algorithm:
Step 1: Start
Step2: Get the string to be checked
Step 3: Check if the first character is equal to the last character in the string
Step 4: If it is not equal display “ Not a Palindrome” and go to step 8
Step 5: If it is equal check the next element with the next last element
Step 6: Repeat the step 4 and 5 until all the elements in the string are checked
Step7: If all the elements are equal to each other till the middle character,
             display “The given String is a Palindrome”
Step 8: Stop

 
/* Palindrome (String ) */
import java.io.*;
class palindrome{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String");
String str=br.readLine();
StringBuffer sb=new StringBuffer(str).reverse();
String strRev=sb.toString();
if(str.equalsIgnoreCase(strRev))
{
System.out.println("Given String is palindrome");
}
else{
System.out.println("Given String is not a palindrome");
}
}
}



Output:
Enter String
Mam

Given String is palindrome

Enter String
Java

Given String is not a palindrome




Ex.No. 4 (a)    Sorting(String)

Aim:   To Sort a given list of names in ascending/alphabetical order
Algorithm:
Step 1: Start
Step 2: Get the # of Strings as input
Step3: Read all the strings one by one and store it in a string array
 
Step4: Repeat step3 until it reaches the # last element count
Step5: Using compareTo() function, compare the elements and return the sorted array
Step6: Print the Sorted array
Step7: Stop

/* Sorting  (String) */
import java.lang.*;
import java.io.*;
public class sorting{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter how many strings to be sorted");
int n=Integer.parseInt(br.readLine());
String x[]=new String[n];
System.out.println("Enter the "+n+"Strings");
for(int i=0;i<n;i++)
{
x[i]=br.readLine();
}
String s=new String();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(x[i].compareTo(x[j])<0)
{
s=x[i];
x[i]=x[j];
x[j]=s;
}
}
}
System.out.println("*****String in alphabetical order*****\n");
for(int i=0;i<n;i++)
{
System.out.println(x[i]);
}
}
}


Output:
Enter the 10Strings
alpha
omega
gamma
thero
nero
opera
jack
jill
french
oil
*****String in alphabetical order*****

alpha
french
gamma
jack
jill
nero
oil
omega
opera
thero


Ex.No.4(b)          File Information
Aim: To read a file name from the user and display its information whether it exists, writable, its type and its length in bytes.
Algorithm:
Step1: Start
Step2: Using ‘File’ command get the filename with its location from the user
Step3: If the file exists, display” File Exists” else “Not Exists”
Step4: If the file is readable, display”File is readable” else “Not Readable”
Step5: If the file is writable, diplay “File is Writable” else “Not Writable”
Step6: Display its location on the disk
Step7: Display its length in bytes
Step8: Stop
Note: Run the program using the following command
       java filename d:\bca\filename.java


/* File Information */
import java.io.*;
class fileinfo
{
public static void main(String ar[])
{
File f1 = new File("e:/BCA/fileinfo.java");
System.out.println(f1.exists());
System.out.println(f1.canRead());
System.out.println(f1.canWrite());
System.out.println(f1.isFile());
System.out.println(f1.isDirectory());
System.out.println(f1.length());
}
}





Output:
E:\BCA>java fileinfo E:BCA\palindrome.java
false
false
false
false
false
0
E:\BCA>javac fileinfo.java
E:\bca>java fileinfo E:BCA\fileinfo.java
true
true
true
true
false
347


Ex.No. 4 ( c)      Line Number before each Line
Aim: To read a file and display it on the screen with a line number before each line
Algorithm :
Step1: Start
Step2: In the ‘try’ block using LineNumberReader() get the line number and store it in an array
Step3: Print the previously stored line number adding up the text line by line using thisLine
Step4: Repeat the process till the control reaches the last string count
Step5: In the ‘catch’ block , I/O exception display the “Error”
Step6: Stop
Note: Run the program using the following command
       java filename d:\bca\filename.java


/* Line Number before each Line */
import java.io.*;
class linum
{
public static void main(String args[])
{
String thisline;
for(int i=0;i<args.length;i++)
{
try
{
LineNumberReader br=new LineNumberReader(new FileReader(args[i]));
while((thisline=br.readLine())!=null)
{
System.out.println(br.getLineNumber()+"."+thisline);
}
}
catch(IOException e)
{
System.out.println("error:"+e);
}
}
}
}



Output:   E:\BCA>java linum E:BCA\linum.java
1.import java.io.*;
2.class linum
3.{
4.public static void main(String args[])
5.{
6.String thisline;
7.for(int i=0;i<args.length;i++)
8.{
9.try
10.{
11.LineNumberReader b=new LineNumberReader(new FileReader(args[i]));
12.while((thisline=b.readLine())!=null)
13.{
14.System.out.println(b.getLineNumber()+"."+thisline);
15.}
16.}
17.catch(IOException e)
18.{
19.System.out.println("error:"+e);
20.}
21.}
22.}
23.}



Ex.No.4(d)      Number of characters, lines and words in a Text File
Aim: To display # of characters, lines & words in a text file
Algorithm:
Step1: Start
Step2: Initialize the variables and counter to 0
Step3: While the input line = NULL, increment by1 & add it to previous index value
Step4: Repeat step3, until value equals to zero
Step5: While input is less than length(), add whitespace
Step6: Finally add them both and print the result
Step7: Stop
Note: Run the program using the following command
       java filename d:\bca\filename.java


/* Number of characters, lines and words in a text file*/
import java.io.*;
public class newclass
{
public static void main(String args[])throws IOException
{
long n=0,nw=0, nc=0;
String line;
BufferedReader br=new BufferedReader(new FileReader(args[0]));
while((line=br.readLine())!=null)
{
n++;
nc=nc+line.length();
int i =0;
boolean pspace=true;
while(i<line.length())
{
char c=line.charAt(i++);
boolean space=Character.isWhitespace(c);
if(pspace&&!space)
nw++;
pspace=space;
}
}
System.out.println("Number of characters"+nc);
System.out.println("Number of words"+nw);
System.out.println("Number of  lines"+n);
}
}

  
Output:
E:\BCA>java newclass E:\BCA\newclass.java
Number of characters532
Number of words53
Number of  lines28




Ex.no. 5     Shopping List Using Vector
Aim: To accept a shopping list of 5 items from the command line and store them in a vector and accomplish to add an item at specific location, at the end, to delete an item, to print the contents of the vector in a hierarchical order
Algorithm:
Step1: Start
Step2:  Initialize vector list and its relevant variables to accept the list of items
Step3: Using addElement() class of java.util add each element to the string array
Step4: Give the choice to the user, whether to add, delete or print the array
If it is add, add the element using insertElementAt()
If it is to delelte, delete the item using removeElement()
If it is to add at the end of the location, use addElement()
To print use vectorlist, elementAt()
Step5: Stop


/* Shopping List Using Vector */
import java.util.*;
import java.io.*;
class menudriven
{
public static void main(String args[])
{
Vector itemList = new Vector();
String str,item;
int i,j,len,choice,pos;
len=args.length;
for(i=0;i<len;i++)
itemList.addElement(args[i]);
while(true)
{
System.out.println("\n\n*****Shopping List*****\n");
System.out.println("Enter your Choice");
System.out.println("1.Add Item at the specified Location");
System.out.println("2.Add Item at the end of the list");
System.out.println("3.Print Vector List");
System.out.println("4.Delete Item");
System.out.println("5.Exit");
System.out.flush();
try{
BufferedReader obj= new BufferedReader(new InputStreamReader(System.in));
str=obj.readLine();
choice=Integer.parseInt(str);
switch(choice)
{
case 1:
System.out.println("Enter the item to insert:");
System.out.flush();
item=obj.readLine();
System.out.println("Enter the position to insert item:");
str=obj.readLine();
pos=Integer.parseInt(str);
itemList.insertElementAt(item,pos-1);
break;
case 2:
System.out.println("Enter the item to insert:");
System.out.flush();
item=obj.readLine();
itemList.addElement(item);
break;
case 3:
len=itemList.size();
System.out.println("\n****Item Display****\n");
for(i=0;i<len;i++)
{
System.out.print((i+1)+")"+itemList.elementAt(i)+"\n");
}
break;
case 4:
System.out.println("Enter the Item you want to delete");
str=obj.readLine();
itemList.removeElement(str);//string is not needed to convert object type as it is already
break;

case 5:
System.out.println("\n\n Thank you! Come Again");
System.exit(i);
break;

default:
System.out.println("\n Invalid Choice\n Try again\n");
}
}

catch(Exception e)
{}
}
}
}

Output:
E:\BCA>java menudriven
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
1
Enter the item to insert:
Maggie
Enter the position to insert item:
1
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
1
Enter the item to insert:
SoyMilk
Enter the position to insert item:
1
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
3
****Item Display****
1)SoyMilk
2)Maggie
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
1
Enter the item to insert:
Egg
Enter the position to insert item:
2
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
3
****Item Display****
1)SoyMilk
2)Egg
3)Maggie
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
1
Enter the item to insert:
Candle
Enter the position to insert item:
3
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
3
****Item Display****
1)SoyMilk
2)Egg
3)Candle
4)Maggie
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
2
Enter the item to insert:
Soap
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
3
****Item Display****
1)SoyMilk
2)Egg
3)Candle
4)Maggie
5)Soap
****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
4
Enter the Item you want to delete
SoyMilk
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
3
****Item Display****
1)Egg
2)Candle
3)Maggie
4)Soap
*****Shopping List*****
Enter your Choice
1.Add Item at the specified Location
2.Add Item at the end of the list
3.Print Vector List
4.Delete Item
5.Exit
5
 Thank you! Come Again


Ex.No.6(a)          Simple message using Applet
Aim: To display a simple message using Applet.
Algorithm:
Step1: Start
Step2: Set  the string to be displayed  as “Welcome Applet”
Step3: using drawString(), setColor(), drawLine() from  java.applet & java.awt packages give the color attributes
Step4: Display the applet using “AppletViewer”
Step5: Stop

/* Simple message using Applet */
import java.awt.*;
import java.applet.*;
public class colapp extends Applet
{
public void paint(Graphics g)
{
String s="Welcome Applet";
g.drawString(s,150,100);
g.setColor(Color.red);
g.drawLine(10,10,100,10);
g.setColor(Color.blue);
g.drawLine(100,10,100,100);
g.setColor(Color.green);
g.drawLine(10,10,100,100);
}
}
/*<applet code="colapp" width=200 height=200>
</applet>*/

Output:
E:\BCA>appletviewer colapp.java





Ex.No. 6(b)  Factorial of a number using Applet
Aim: To develop an applet that receives an integer in the text field  and compute its factorial value and returns it in another field when the button named “Compute” is clicked.
Algorithm:
Step1: Start
Step2: Design two text boxes, a label and a button
Step3: Get the input value to find factorial
Step4: Name the button as “Compute”
Step5: Using ActionListener(), get the actionPerformed, read the input and calculate its factorial
Step6: Return the value in another text box
Step7: Stop



/* Factorial of a number using Applet*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class fact extends Applet implements ActionListener
{
 int n;
TextField t1,t2;
Label l1;
Button b;
public void init()
{
l1=new Label("Enter n value",Label.LEFT);
t1=new TextField(20);
b=new Button("Compute");
t2=new TextField(20);
add(l1);
add(t1);
add(b);
add(t2);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
 String s1=t1.getText();
int f=1;
int n=Integer.parseInt(s1);
for(int i=1;i<=n;i++)
f=f*i;
String s="Factorial Value="+f;
t2.setText(s);
}
}
/*<applet code="fact" width=300 height=300>
</applet>*/


Output:













Ex.No.7(a)            Handling Mouse Events
Aim: To handle various mouse events and display them on an applet
Algorithm:
Step1: Start
Step2: Add MouseListener & MouseMotionListener
Step3:  Using drawstring display the message inside the applet window on the various events below
Step3: Perform various mouse events on the applet window
When the mouse is entered into the applet window display “Mouse Entered”
When the mouse is clicked inside the applet window display”Mouse Clicked”
When the mouse is exited out of the applet window display”Mouse Exited”
When the mouse is pressed inside the applet window, display”Mouse Pressed”
When the mouse is dragged inside the applet window display”Mouse dragged”
When the mouse is released display”Mouse released”
Step4: Stop

 
/*  Handling Mouse Events */
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class Mouseevents extends Applet implements MouseListener,MouseMotionListener
{
String msg="";
int x=0,y=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=10;
y=20;
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=10;
y=20;
msg="mouse entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=10;
y=20;
msg="mouse exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="*";
showStatus("dragging mouse at"+x+","+y);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("moving mouse at"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
/*<applet code="Mouseevents"width=200 height=100>
</applet>*/

Output: 



 








Ex.No.7(b)   Multithreading
Aim: To create 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. 
Algorithm:
Step1: Start
Step2: Initialize a thread and String to display a message
Step3: Display the first message “Good morning” and using Thread.sleep() freeze the current thread until the counting loop completes (i.e every 1 second)
Step4: Display the second message” Hello” and call in Thread.sleep() until every 2 secs
Step5: Display the third message” Welcome” and wait for 3 secs
Step6: Repeat the step one by one until the user presses Ctrl + c to stop the loop
Step7: Stop


 
/* Multithreading */
class mt implements Runnable
{
Thread t;
String s;
int r;
mt(String ss, int tt)
{
t=new Thread(this, ss);
s=ss;
r=tt;
t.start();
}
public void run()
{
for(; ;)
{
System.out.println(s);
try
{
Thread.sleep(r);
}
catch(Exception e)
{
}
}
}
}
class ab2
{
public static void main(String ar[])
{
mt t1=new mt("good morning",1000);
mt t2=new mt("hello",2000);
mt t3=new mt("welcome",3000);
}}



Output:
E:\BCA>java multi
good morning
welcome
hello
good morning
hello
good morning
welcome
good morning
hello
good morning
good morning
welcome
hello
good morning
good morning
hello
good morning
welcome
good morning
hello

Ex.No.7( c)    Producer- consumer problem using Inter Thread Communication
Aim: To implement producer consumer problem using the concept of inter thread communication/message passing technique
Algorithm:
Step1: Start
Step2:  Encounter # of slots in the buffer
Step3:  Generate an item to put into the producer buffer
Step4: Using wait() ,wait until the producer produces the item
Step5: Using the notify() ,notify the consumer class to consume the item produced from the producer in the buffer
Step6: Continue the process until the user presses Ctrl+c
Step7: Stop


/*  Producer- consumer problem using Inter Thread Communication */
class Q
{
boolean valueSet=false;
int n;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception is:"+e);
}
System.out.println("got:"+n);
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println
("\n Exception in put:"+e);
}
this.n=n;
valueSet=true;
System.out.println("\nput:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
q.get();
}
}
class ProdConsDemo
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("\n press ctrl+c to stop");
}
}















Output:
E:/BCA>java ProdConsDemo
Put:0
Put:0
Put:0
Put:0
Put:0
Put:0

Put:0
Put:0

Put:0
Put:0
Got 0
-------------------
got:15
got:15
got:15
got:15
got:15
got:15
got:15
got:15
got:15




Ex.No.8                     Exception Handling
Aim:  To perform integer divisions with user interface using Exception .
Algorithm:
Step1: Start

Step2: Design three text fields in which the user gives two inputs to divide and in the third text field the result is displayed
Step3:  The quotient is returned in the third text box after “Divide button” is clicked
Step4:  If one or two of the inputs is not in number format, display “Numberformat Exception”
Step5: If the input is 0 display “Arithmetic Exception” in message box
Step6: Stop


/* Exception Handling */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Div extends Applet implements ActionListener
{
String msg;
TextField num1,num2,res;
Label l1,l2,l3;
Button div;
public void init()
{
l1=new Label("Number 1");
l2=new Label("Number 2");
l3=new Label("result");
num1=new TextField(10);
num2=new TextField(10);
res=new TextField(10);
div=new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("DIV"))
{
String s1=num1.getText();
String s2=num2.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(s2);
if(num2==0)
{
try
{
System.out.println(" ");
}
catch(Exception e)
{
System.out.println("Arithemetic Exception"+e);
}
msg="Arithemetic Exception";
repaint();
}
else if((num1<0)||(num2<0))
{
try
{
System.out.println("");
}
catch(Exception e)
{
System.out.println("NumberFormat"+e);
}
msg="NumberFormatException";
repaint();
}
else
{
int num3=num1/num2;
res.setText(String.valueOf(num3));
}
}
}
public void paint(Graphics g)
{
g.drawString(msg,30,70);
}
}

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

 
Output:




Ex.No.9(a)          Client / Server Application
Aim:  To perform  a simple client/server application  where the client sends data to a server & the server receives the data, uses it to produce a result, and then sends the result back to the client & the client displays the result on the console. 
Algorithm:
Client Program:
Step1: Start
Step2:  Implement the socket and port number using the java.net package
Step3:  Get the radius from the user to send to the server
Step4:  Retrieve the output from the server using getOutputStream()
Step5:  Print the area of circle
Step6: Stop
Server Program:

Step1: Start
Step2: Implement the socket and port number using the java.net package
Step3: Wait for the client request
Step4: Accept the socket from client using InputStreamReader()
Step5: Calculate with the received radius using the formula for area of circle i.e πr2
Step6: Return the value to the client using PrintStream()
Step7: Stop

 
/* Client / Server Application */
Client program:
import java.io.*;
import java.net.*;
class Client
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",8080);
BufferedReader br;
String str;
System.out.println("enter the radius to send the server");
br=new BufferedReader(new InputStreamReader(System.in));
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(br.readLine());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Area of circle:"+str);
ps.close();
br.close();
}
}

Server Program:
import java.io.*;
import java.net.*;
class Server
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(8080);
System.out.println("wait for client request");
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
String str;
str=br.readLine();
System.out.println("recieved radius");
double r=Double.parseDouble(str);
double area=3.14*r*r;
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(area));
ps.close();
br.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println("exception occur at:"+e.toString());
}
}
}



























Output:
Server side:
D:\bca>javac server.java
D:\bca>java Server
wait for client request
recieved radius

Client side:
D:\bca>javac client.java
D:\bca>java Client
enter the radius to send the server
10
Area of circle:314.0



Ex.No.9(b)   Draw lines, rectangles and ovals using JApplet
Aim: To develop an applet that allows the user to draw lines, rectangles and ovals.
Algorithm:
Step1: Start
Step2:  Using java.applet.Applet and Graphics(_) call the functions
Call in drawLine() to draw a line
Call drawRect() to draw a rectangle
Call fillRect() to draw a color filled rectangle
Call drawOval() to draw an oval
Call fillOval() to fill the oval
Step3: Stop

/* Draw lines, rectangles and ovals using JApplet */
import java.awt.*;
import java.applet.Applet;
public class DrawShapes extends Applet
{
public void paint(Graphics g)
{
g.drawLine(40,30,200,30);
g.drawRect(40,60,70,40);
g.fillRect(140,60,70,40);
g.drawOval(40,120,70,40);
g.fillOval(140,120,70,40);
}
}
/*<applet code="DrawShapes.class" height=500 width=500></applet>*/











Output:





Ex.No.10 (a)                    Abstract Class
Aim:  To create an abstract class to return the # of sides in the given geometrical figures using numberOfSides()
Algorithm:
Step1: Start
Step2:  Create an abstract class and declare the numberOfSides()
Step3:  create Trapezoid class extending the abstract class and return its # of sides
Step4: Create Triangle class extending the abstract class and return its # of sides
Step5: Create  Hexagon class extending the abstract class and return its # of sides
Step6:    Display the result
Step7: Stop

/* Abstract Class */
abstract class Shapes{
abstract void numberOfSides();
}
class Trapezoid extends Shapes{
void numberOfSides(){
System.out.println("Number of sides for Trapezoid is 5");
}
}
class Triangle extends Shapes{
void numberOfSides(){
System.out.println("Number of sides for triangle is 3");
}
}
class Hexagon extends Shapes{
void numberOfSides()
{
System.out.println("Number of sides for Hexagon is 6");
}
}
class Abstractclass
{
public static void main(String[] args)
{
Shapes s;
s=new Trapezoid();
s.numberOfSides();
s=new Triangle();
s.numberOfSides();
s=new Hexagon();
s.numberOfSides();
}
}













Output:
E:\BCA>java Abstractclass
Number of sides for Trapezoid is 5
Number of sides for triangle is 3
Number of sides for Hexagon is 6



Ex.10(b)             Display the table using JTable component
Aim:  To display the table using JTable component.
Algorithm:
Step1: Start
Step2: Using javax.swing &  JTable component  create a table
Step3:  Give four  fields, “NAME”, “Roll #” , “Dept” and “Percentage of Marks”
Step4: Give all the input in a string array
Step5: Add Scroll panel, Borderlayout and content panel using java Table
Step6: Print the table in the applet
Step7: Stop


 
/* Display the table using JTable component */
import java.awt.*;
import javax.swing.*;
public class Table1 extends JApplet
{
public void init()
{
Container con=getContentPane();
BorderLayout b=new BorderLayout();
con.setLayout(b);
final String[] colHeads={"Name","RollNumber","Dept","Percentage"};
final String[][] data={{"Hari","0501","BCA","75.05%"},{"Ajay","0341","MCA","90.78%"},{"vijaya","0401","CS","70.05%"},{"Mani","0402","IT","90.12%"},{"Lakshmi","0201","BCA","80.12%"},{"Prabu","1214","cseIT","80.05%"}};
JTable table1=new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll=new JScrollPane(table1,v,h);
con.add(scroll);
}
}
 /*<applet code="Table1.class" height=600 width=600> </applet> */










Output: