Friday 10 May 2013

CS2309 JAVALAB RECORD ONLY PROGRAM

EX NO: 01                          PRINT HELLO WORLD
DATE:


SOURCE CODE

class helloword
{
public static void main(String args[])
{

System.out.println("helloworld");
}
}




EX NO: 02                      ADDITION OF TWO NUMBERS
DATE:


SOURCE CODE

class value
{
public static void main(String args[])
{
int a=5,b=6,c;
c=a+b;
System.out.println("c="+c);
}
}




EX NO: 03             PROGRAM USING SCANNER
DATE:


SOURCE CODE

import java.util.Scanner;

class GetInputFromUser
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;

      Scanner in = new Scanner(System.in);

      System.out.println("Enter a string");
      s = in.nextLine();
      System.out.println("You entered string "+s);

      System.out.println("Enter an integer");
      a = in.nextInt();
      System.out.println("You entered integer "+a);

      System.out.println("Enter a float");
      b = in.nextFloat();
      System.out.println("You entered float "+b);  
   }
}



EX NO: 04         CLASS AND OBJECT IN JAVA-REAL TIME
DATE:

SOURCE CODE

class tamilnadu
{
int a,b;
tamilnadu()
{
a=0;
b=0;
}
void TRICHY(int x,int y)
{
a=x;
b=y;
}
void SALEM()
{
System.out.println("the valus of a="+a);
System.out.println("the valus of b="+b);

}
}

class CHENNAI
{
public static void main(String args[])
{
tamilnadu sat=new tamilnadu();
sat.TRICHY(2,3);
sat.SALEM();
}
}


EX NO: 05                CLASS AND OBJECT IN JAVA-TEXT BOOK
DATE:


SOURCE CODE


class rectangle
{
int length,width;
rectangle()
{
length=0;
width=0;
}
void getdata(int x,int y)
{
length=x;
width=y;
}
int getarea()
{
int area1;
area1=length*width;
return (area1);
}
}

class rectarea
{
public static void main(String args[])
{
rectangle rect1=new rectangle();
rectangle rect2=new rectangle();
 rect1.length=2;
 rect1.width=3;
int area2;
area2=rect1.length* rect1.width;

rect2.getdata(4,5);
int area3;
area3=rect2.getarea();
System.out.println("area2="+area2);
System.out.println("area3="+area3);
}
}
EX NO: 06                      STATIC VARIABLE PROGRAM
DATE:

SOURCE CODE:

class flower
{
static int flower;
int rose;

flower()
{
flower+=1;
rose+=1;
System.out.println("flower="+flower);
System.out.println("Rose="+rose);
}

public static void main(String args[])
{
flower f1=new flower();
flower f2=new flower();
flower f3=new flower();

}
}



EX NO: 07                             PROGRAM FOR FORLOOP
DATE:



The Syntax for the For Loop: 
  for( initialization; termination; increment)
  {
  statements;
  }
SOURCE CODE:
public class  ForLoop
{
  public static void main(String[] args)
{
  for(int i = 1;i <= 5;i++)
{
  for(int j = 1;j <= i;j++)
{
  System.out.print(i);
}
  System.out.println();
}
}

}



EX NO: 08   SINGLE, MULTILEVEL AND HIERARCHICAL INHERITANCE
DATE:

SOURCE CODE-1:

 class A
  {
          int i=10,j=20;
          void xyz()
          {
                  System.out.println(i+j);
          }
          void lmn()
          {
                  System.out.println("lmn");
         }
  }
  class B extends A
  {
          int k=40,l=45;
          void abc()
          {
                  System.out.println(i+j+k);
                  lmn();
          }
  }
  class C extends B
  {
  }
  class Inherit
  {
          public static void main(String args[])
          {
          C a1= new C();
          a1.abc();
          }
  }

SOURCE CODE-2:


class Aves
{
    public void nature()
    {
       System.out.println("Generally, Aves fly");
    }
}
class Bird extends Aves
{
    public void eat()
    {
       System.out.println("Eats to live");
    }
}
public class Parrot extends Bird
{
    public void food()
    {
       System.out.println("Parrot eats seeds and fruits");
    }
    public static void main(String args[])
    {
       Parrot p1 = new Parrot();
       p1.food();                        // calling its own
       p1.eat();                        // calling super class Bird method
       p1.nature();                     // calling super class Aves method
    }



EX NO: 09   POLYMORPHISM/MULTIPLE INHERITANCE/DYNAMIC BINDING (PMD)
DATE:

SOURCE CODE:

interface vehicle
{
int numberofwheels();
String vehicletype();
}
class car implements vehicle
{
public int numberofwheels()
{
return 4;
}
public String vehicletype()
{
return "car";
}
}
class autorickshaw implements vehicle
{
public int numberofwheels()
{
return 3;
}
public String vehicletype()
{
return "Autorickshaw";
}
}
public class polyvehicle
{
public static void main(String args[])
{
vehicle ve;
ve=new car();
System.out.println("VehicleType:"+ve.vehicletype());
System.out.println("numberOfWheels:"+ve.numberofwheels());
ve=new autorickshaw();
System.out.println("VehicleType:"+ve.vehicletype());
System.out.println("numberOfWheels:"+ve.numberofwheels());
}
}


EX NO: 10               ARRAY PROGRAM)
DATE:



SOURCE CODE:

class array
{
public static void main(String args[])
{
int number[]=new int[4];
number[0]=50;
number[1]=35;
number[2]=40;
number[3]=58;

int n=number.length;
System.out.println("given list");
for(int i=0;i<n;i++)
{
System.out.println(""+number[i]);
}
System.out.println("\n");
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]>number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
System.out.println("sorted list");
for(int i=0;i<n;i++)
{
System.out.println(""+number[i]);
}
System.out.println("");
}
}



EX NO: 11              STRING PROGRAM
DATE:

SOURCE CODE:


class string
{
static String name[]={"chennai","a","b","salem"};
public static void main(String args[])
{
int size=name.length;
String temp=null;

for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i])<0)
{
 temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}

for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}

}
}



EX NO: 12                             RATIONAL NUMBERS
DATE:

SOURCE CODE

import java.util.Scanner;
class rational_main
{
 /** Class that contains the main function
      */

public static void main(String args[])
{
  /** Create an instance of "rational" class
    * to call the function in it.
    */

 rational x = new rational();

 //To get input from user

 Scanner s = new Scanner(System.in);
 int a,b;
 System.out.println("\n Enter the Numerator and Denominator:");
 a = s.nextInt();
 b = s.nextInt();

 x.efficient_rep(a,b);
}
}
public class rational
{

/** Rational number class
 * To give an efficient representation of user's input rational number
 * For ex: 500/1000 to be displayed as 1/2
 */

public void efficient_rep(int a, int b)
{

 int x=b;
 if(a<b)
   x=a;
 /** Assume x = smallest among a and b
   * Divide the numerator and denominator by x, x-1, x-2... until
   * both of them cannot be divided further
   */

 for(int i=x;i>=2;i--)
 {
   if(a%i==0 && b%i==0)
   {
    a=a/i;
    b=b/i;
   }
 }
 System.out.println(a + "/" + b);
 }
}




EX NO: 13                              DATE CLASS IN JAVA
DATE:




SOURCE CODE


import java.util.Date;

class MyDate extends Date
{
 private static final long serialVersionUID = 1L;
 int day    = super.getDay();
 int date    = super.getDate();
 int year    = super.getYear();
 int month    = super.getMonth();
 int hours    = super.getHours();
 int minutes   = super.getMinutes();
 int seconds   = super.getSeconds();
 long time    = super.getTime();
 int timezoneOffset = super.getTimezoneOffset();
 public int getDay()     {return day;}
 public int getDate()    {return date;}
 public int getYear()    {return year+1900;}
 public int getMonth()    {return month+1;}
 public int getHours()    {return hours;}
 public int getMinutes()    {return minutes;}
 public int getSeconds()    {return seconds;}
 public int getTimezoneOffset()  {return timezoneOffset;}
 public long getTime()    {return time;}
 public void setDay(int day)   {this.day   = day;}
 public void setDate(int date)  {this.date   = date;}
 public void setTime(Long time)  {this.time   = time;}
 public void setYear(int year)   {this.year   = year;}
 public void setHours(int hours)  {this.hours  = hours;}
 public void setMonth(int month)  {this.month  = month;}
 public void setMinutes(int minutes) {this.minutes  = minutes;}
 public void setSeconds(int seconds) {this.seconds  = seconds;}
 public void setTimezoneOffset(int timezoneOffset){this.timezoneOffset = timezoneOffset;}
public String toString()
 {
  String date = this.getDate()+"/"+this.getMonth()+"/"+this.getYear();
  String time = this.getHours()+":"+this.getMinutes()+":"+this.getSeconds();
  return date+"  "+time;
 }
}

public class DateImpl
{
 public static void main(String args[])
 {
  MyDate date1 = new MyDate();
  System.out.println("Date  : "+date1.getDate());
  System.out.println("Month : "+date1.getMonth());
  System.out.println("Year  : "+date1.getYear());
  System.out.println("Hour  : "+date1.getHours());
  System.out.println("Minutes : "+date1.getMinutes());
  System.out.println("Secs  : "+date1.getSeconds());
  System.out.println(date1);
 }
}



EX NO: 14                      IMPLEMENTATION OF STACK ADT
DATE:


SOURCE CODE


/**
 * Array-based implementation of the stack.
*/
 class ArrayStack implements Stack {
   
    private Object [ ] theArray;
    private int        topOfStack;   
    private static final int DEFAULT_CAPACITY = 10;

     /**
     * Construct the stack.
     */
    public ArrayStack( ) {
        theArray = new Object[ DEFAULT_CAPACITY ];
        topOfStack = -1;
    }
   
    /**
     * Test if the stack is logically empty.
     * @return true if empty, false otherwise.
     */
    public boolean isEmpty( ) {
        return topOfStack == -1;
    }
   
    /**
     * Make the stack logically empty.
     */
    public void makeEmpty( ) {
        topOfStack = -1;
    }
   
    /**
     * Get the most recently inserted item in the stack.
     * Does not alter the stack.
     * @return the most recently inserted item in the stack.
     * @throws UnderflowException if the stack is empty.
     */
    public Object top( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "ArrayStack top" );
        return theArray[ topOfStack ];
    }
   
    /**
     * Remove the most recently inserted item from the stack.
     * @throws UnderflowException if the stack is empty.
     */
    public void pop( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "ArrayStack pop" );
        topOfStack--;
    }
   
    /**
     * Return and remove the most recently inserted item
     * from the stack.
     * @return the most recently inserted item in the stack.
     * @throws Underflow if the stack is empty.
     */
    public Object topAndPop( ) {
        if( isEmpty( ) )
        throw new UnderflowException( "ArrayStack topAndPop" );
        return theArray[ topOfStack-- ];
    }
   
    /**
     * Insert a new item into the stack.
     * @param x the item to insert.
     */
    public void push( Object x ) {
        if( topOfStack + 1 == theArray.length )
            doubleArray( );
        theArray[ ++topOfStack ] = x;
    }
   
    /**
     * Internal method to extend theArray.
     */
    private void doubleArray( ) {
        Object [ ] newArray;
       
        newArray = new Object[ theArray.length * 2 ];
        for( int i = 0; i < theArray.length; i++ )
            newArray[ i ] = theArray[ i ];
        theArray = newArray;
    }
   
   
   
   
}


//ListStack class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void push( x )         --> Insert x
// void pop( )            --> Remove most recently inserted item
// Object top( )          --> Return most recently inserted item
// Object topAndPop( )    --> Return and remove most recent item
// boolean isEmpty( )     --> Return true if empty; else false
// void makeEmpty( )      --> Remove all items
// ******************ERRORS********************************
// top, pop, or topAndPop on empty stack

/**
 * List-based implementation of the stack.
*/
class LinkedListStack implements Stack {
    /**
     * Construct the stack.
     */
    public LinkedListStack( ) {
        topOfStack = null;
    }

    /**
     * Test if the stack is logically empty.
     * @return true if empty, false otherwise.
     */
    public boolean isEmpty( ) {
        return topOfStack == null;
    }

    /**
     * Make the stack logically empty.
     */
    public void makeEmpty( ) {
        topOfStack = null;
    }

    /**
     * Insert a new item into the stack.
     * @param x the item to insert.
     */
    public void push( Object x ) {
        topOfStack = new ListNode( x, topOfStack );
    }

    /**
     * Remove the most recently inserted item from the stack.
     * @throws UnderflowException if the stack is empty.
     */
    public void pop( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "ListStack pop" );
        topOfStack = topOfStack.next;
    }

    /**
     * Get the most recently inserted item in the stack.
     * Does not alter the stack.
     * @return the most recently inserted item in the stack.
     * @throws UnderflowException if the stack is empty.
     */
    public Object top( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "ListStack top" );
        return topOfStack.element;
    }

    /**
     * Return and remove the most recently inserted item
     * from the stack.
     * @return the most recently inserted item in the stack.
     * @throws UnderflowException if the stack is empty.
     */
    public Object topAndPop( ) {
        if( isEmpty( ) )
            throw new UnderflowException( "ListStack topAndPop" );

        Object topItem = topOfStack.element;
        topOfStack = topOfStack.next;
        return topItem;
    }

    private ListNode topOfStack;

}


class ListNode {
    public Object   element;
    public ListNode next;

    // Constructors
    public ListNode( Object theElement ) {
        this( theElement, null );
    }

    public ListNode( Object theElement, ListNode n ) {
        element = theElement;
        next    = n;
    }
}


 interface Stack {
    /**
     * Insert a new item into the stack.
     * @param x the item to insert.
     */
    void    push( Object x );

    /**
     * Remove the most recently inserted item from the stack.
     * @exception UnderflowException if the stack is empty.
     */
    void    pop( );

    /**
     * Get the most recently inserted item in the stack.
     * Does not alter the stack.
     * @return the most recently inserted item in the stack.
     * @exception UnderflowException if the stack is empty.
     */
    Object  top( );


    /**
     * Return and remove the most recently inserted item
     * from the stack.
     * @return the most recently inserted item in the stack.
     * @exception UnderflowException if the stack is empty.
     */
    Object  topAndPop( );

    /**
     * Test if the stack is logically empty.
     * @return true if empty, false otherwise.
     */
    boolean isEmpty( );

    /**
     * Make the stack logically empty.
     */
    void    makeEmpty( );


}


public class StackTester {

    public static void main(String[] args) {

        System.out.println("******************************************");
        System.out.println("Stack using Array & Linked List example");
        System.out.println("******************************************");

        ArrayStack arrayStack = new ArrayStack();
        arrayStack.push(new String("a"));
        arrayStack.push(new String("b"));
        arrayStack.push(new String("c"));
        System.out.println("Stack[using array] elements -> a, b, c");
        System.out.println("Stack LIFO and POP -> "+arrayStack.topAndPop());
        System.out.println("Stack LIFO -> "+arrayStack.top());
        arrayStack.pop();       
        try{
            arrayStack.pop();
            arrayStack.topAndPop();
        }catch(RuntimeException rte){
            System.err.println("Exception occured while POP operation is happened on Stack[by using array]");
        }
        System.out.println("\n\n******************************");
        System.out.println("Stack using Linked List example");
        System.out.println("******************************");

        LinkedListStack linkedListStack = new LinkedListStack();
        linkedListStack.push(new Integer(10));
        linkedListStack.push(new Integer(20));
        linkedListStack.push(new Integer(30));
        linkedListStack.push(new Integer(40));
        System.out.println("Stack[using linked list] elements -> 10, 20, 30, 40");
        System.out.println("Stack TOP ->"+linkedListStack.top());
        linkedListStack.pop();       
        System.out.println("Stack TOP after POP ->"+linkedListStack.top());
        linkedListStack.pop();
        linkedListStack.pop();
        linkedListStack.pop();
        try{
            linkedListStack.pop();
        }catch(RuntimeException rte){
            System.err.println("Exception occured while POP operation is happened on Stack[by using linked list]");
        }


    }
}


/**
 * Exception class for access in empty containers
 * such as stacks, queues, and priority queues.
 * @author Ramkumar
 */
class UnderflowException extends RuntimeException {
    /**
     * Construct this exception object.
     * @param message the error message.
     */
    public UnderflowException( String message ) {
        super( message );
    }
}



EX NO: 15                      LISP LIST IN JAVA
DATE:


SOURCE CODE:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class LispImpl
{
 Scanner sc = new Scanner(System.in);
 List consList = new ArrayList();
 public void cons()
 {
  System.out.println("Enter the Cons Element");
  System.out.println("Format --->[addr,value1,value2,...]");
  String cons = sc.next().trim();
  if(cons.indexOf("[") == 0 && cons.indexOf("]") == cons.length()-1)
  {
   cons = cons.substring(1,cons.length()-1);
   String[] consElements = cons.split(",");
   if(consElements.length>2)
   {
    try
    {
     Integer.parseInt(consElements[0]);
     List list = new LinkedList();
     for(int i = 0 ;i< consElements.length;i++)
     {
      list.add(consElements[i]);
     }
     consList.add(consList.size(),list);
    }
    catch(Exception e)
    {
     e.printStackTrace();
     System.out.println("Error : Content of Address Part of Register should be Numeric" );
    }
    }
   else
    System.out.println("Error :  No Contents of Decrement part Register Found");
  }
  else
  {
   System.out.println("Conses format is not correct");
  }
 }
 public void car()
 {
  System.out.println("Enter index of the Conses Element");
  try
  {
   int consIndex = sc.nextInt();
   List cons = (List)consList.get(consIndex);
   System.out.println("Car of given ConsIndex : "+cons.get(0));
  
  }
  catch(IndexOutOfBoundsException e)
  {
   System.out.println("No Conses found");
  }
  catch(Exception e)
  {
   System.out.println("Error : Conses index should be Numeric" );
  }
 }
 public void cdr()
 {
  System.out.println("Enter index of the Conses Element");
  try
  {
   int consIndex = sc.nextInt();
   List cons = (List)consList.get(consIndex);
   System.out.print("Cdr of given ConsIndex : [");
   String cdr = "";
   for(int i = 0;i<cons.size();i++)
    cdr = cdr+","+cons.get(i);
   System.out.println(cdr.substring(1,cdr.length())+"]");
  
  
  }
  catch(IndexOutOfBoundsException e)
  {
   System.out.println("No Conses found");
  }
  catch(Exception e)
  {
   System.out.println("Error : Conses index should be Numeric" );
  }
 }
 public void defaultMsg()
 {
  System.out.println("****************************");
  System.out.println("Enter 1 to do cons operation");
  System.out.println("Enter 2 to do car operation");
  System.out.println("Enter 3 to do cdr operation");
  System.out.println("Enter 4 to exit");
  System.out.println("****************************");
 }
 public static void main(String args[])
 {
  LispImpl lisp = new LispImpl();
  int i = 0;
  lisp.defaultMsg();
  while(true)
  {
   Scanner sc = new Scanner(System.in);
   try
   {
    i = sc.nextInt();
   }
   catch(Exception e)
   {
    System.out.println("Numeric values are allowed here");
   }
   switch(i)
   {
    case 1:
      lisp.cons();
      lisp.defaultMsg();
      break;
    case 2:
      lisp.car();
      lisp.defaultMsg();
      break;
    case 3:
      lisp.cdr();
      lisp.defaultMsg();
      break;
    case 4:
      System.exit(0);
      break;
    default:
      System.out.println("Enter numbers between 0 and 4");
    
   }
  }
 }
}





EX NO: 16                      POLYMORPHISM
DATE:

SOURCECODE:


//This is the class that will be inherited
class Vehicle
{
    public int doors;
    public int seats;
    public int wheels;
    Vehicle()
    {
    wheels=4;
        doors=4;
    seats=4;
    }
}
//This class inherits Vehicle.java
class Car extends Vehicle
{
    public String toString()
    {
    return "This car has "+seats+" Seats, "+doors+" Doors "+
        "and "+wheels+" wheels.";
    }
}
//This class inherits Vehicle.java
class MotorCycle extends Vehicle
{
    MotorCycle()
    {
    wheels=2;
        doors=0;
    seats=1;
    }
    void setSeats(int num)
    {
    seats=num;
    }
    public String toString()
    {
    return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+
        "and "+wheels+" wheels.";
    }
}
//This class inherits Vehicle.java
class Truck extends Vehicle
{
    boolean isPickup;
    Truck()
    {
    isPickup=true;
    }
    Truck(boolean aPickup)
    {
    this();
    isPickup=aPickup;
    }
    Truck(int doors, int seats, int inWheels, boolean isPickup)
    {
    this.doors=doors;
    this.seats=seats;
    wheels=inWheels;
    this.isPickup=isPickup;
    }
    public String toString()
    {
    return "This "+(isPickup?"pickup":"truck")+
      " has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels.";
    }
}
//This class tests the classes that inherit Vehicle.java
public class VehiclesTest
{
    public static void main(String args[])
    {
    MotorCycle mine = new MotorCycle();
    System.out.println(mine);
    Car mine2 = new Car();
    System.out.println(mine2);
    mine2.doors=2;
    System.out.println(mine2);
    Truck mine3 = new Truck();
    System.out.println(mine3);
    Truck mine4 = new Truck(false);
    mine4.doors=2;
    System.out.println(mine4);

    }
}


EX NO: 17                      OBJECT SERIALIZATION
DATE:


SOURCECODE:

// Currency conversion
import java.io.*;
public class Currency
{
    public static void main(String args[])
    {
        Dollar dr=new Dollar('$',40);
        dr.printDollar();
        Rupee re=new Rupee("Rs.",50);
        re.printRupee();
        try
        {
        File f=new File("rd.txt");
        FileOutputStream fos=new FileOutputStream(f);
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(dr);
        oos.writeObject(re);
        oos.flush();
        oos.close();
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("rd.txt"));
        Dollar d1;
        d1=(Dollar)ois.readObject();
        d1.printDollar();
        Rupee r1;
        r1=(Rupee)ois.readObject();
        r1.printRupee();
        ois.close();
        }
        catch(Exception e)
        {
        }
    }
   
}
class Dollar implements Serializable
{
    private float dol;
    private char sym;

    public Dollar(char sm,float doll)
    {
        sym=sm;
        dol=doll;
    }
    void printDollar()
    {
        System.out.print(sym);
        System.out.println(dol);
    }
}
class Rupee implements Serializable
{
    private String sym;
    private float rs;
    public Rupee(String sm,float rup)
    {
        sym=sm;
        rs=rup;
    }
    void printRupee()
    {
        System.out.print(sym);
        System.out.println(rs);
    }

}





EX NO: 18                      SCIENTIFIC CALCULATOR USING APPLET
DATE:



SOURCE CODE:

import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
   public void init() {
      CalculatorPanel calc=new CalculatorPanel();
      getContentPane().add(calc);
      }
   }

   class CalculatorPanel extends JPanel implements ActionListener {
      JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
      static JTextField result=new JTextField("0",45);
      static String lastCommand=null;
      JOptionPane p=new JOptionPane();
      double preRes=0,secVal=0,res;

      private static void assign(String no)
        {
         if((result.getText()).equals("0"))
            result.setText(no);
          else if(lastCommand=="=")
           {
            result.setText(no);
            lastCommand=null;
           }
          else
            result.setText(result.getText()+no);
         }

      public CalculatorPanel() {
         setLayout(new BorderLayout());
         result.setEditable(false);
         result.setSize(300,200);
         add(result,BorderLayout.NORTH);
         JPanel panel=new JPanel();
         panel.setLayout(new GridLayout(4,4));
         n7=new JButton("7");
         panel.add(n7);
         n7.addActionListener(this);
         n8=new JButton("8");
         panel.add(n8);
         n8.addActionListener(this);
         n9=new JButton("9");
         panel.add(n9);
         n9.addActionListener(this);
         div=new JButton("/");
         panel.add(div);
         div.addActionListener(this);

         n4=new JButton("4");
         panel.add(n4);
         n4.addActionListener(this);
         n5=new JButton("5");
         panel.add(n5);
         n5.addActionListener(this);
         n6=new JButton("6");
         panel.add(n6);
         n6.addActionListener(this);
         mul=new JButton("*");
         panel.add(mul);
         mul.addActionListener(this);
         n1=new JButton("1");
         panel.add(n1);
         n1.addActionListener(this);
         n2=new JButton("2");
         panel.add(n2);
         n2.addActionListener(this);
         n3=new JButton("3");
         panel.add(n3);
         n3.addActionListener(this);
         minus=new JButton("-");
         panel.add(minus);
         minus.addActionListener(this);
         dot=new JButton(".");
         panel.add(dot);
         dot.addActionListener(this);
         n0=new JButton("0");
         panel.add(n0);
         n0.addActionListener(this);
         equal=new JButton("=");
         panel.add(equal);
         equal.addActionListener(this);
         plus=new JButton("+");
         panel.add(plus);
         plus.addActionListener(this);
         add(panel,BorderLayout.CENTER);
      }
      public void actionPerformed(ActionEvent ae)
         {
      if(ae.getSource()==n1) assign("1");
      else if(ae.getSource()==n2) assign("2");
      else if(ae.getSource()==n3) assign("3");
      else if(ae.getSource()==n4) assign("4");
      else if(ae.getSource()==n5) assign("5");
      else if(ae.getSource()==n6) assign("6");
      else if(ae.getSource()==n7) assign("7");
      else if(ae.getSource()==n8) assign("8");
      else if(ae.getSource()==n9) assign("9");
      else if(ae.getSource()==n0) assign("0");
      else if(ae.getSource()==dot)
            {
             if(((result.getText()).indexOf("."))==-1)
                result.setText(result.getText()+".");
           }
      else if(ae.getSource()==minus)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="-";
             result.setText("0");
             }
      else if(ae.getSource()==div)
             {
             preRes=Double.parseDouble(result.getText());
             lastCommand="/";
             result.setText("0");
             }
      else if(ae.getSource()==equal)
             {
             secVal=Double.parseDouble(result.getText());
             if(lastCommand.equals("/"))
                  res=preRes/secVal;
             else if(lastCommand.equals("*"))
                  res=preRes*secVal;
             else if(lastCommand.equals("-"))
                  res=preRes-secVal;
             else if(lastCommand.equals("+"))
                  res=preRes+secVal;
             result.setText(" "+res);
             lastCommand="=";
             }
      else if(ae.getSource()==mul)
             {
              preRes=Double.parseDouble(result.getText());
              lastCommand="*";
              result.setText("0");
              }
      else if(ae.getSource()==plus)
              {
              preRes=Double.parseDouble(result.getText());
              lastCommand="+";
              result.setText("0");
              }

       }
}

Html:

<html>
<title>
</title>
<head>
</head>
<body>
<applet code=Calculator.java height=300 width=200></applet>
</body>
</html>




EX NO: 19                  MULTITHREADING TO PRINT PRIME AND FIBONACCI
DATE:



SOURCE CODE:

import java.io.*;
import java.util.*;
class MyThread1 extends Thread {
private PipedReader pr;

private PipedWriter pw;

MyThread1(PipedReader pr, PipedWriter pw) {
this.pr = pr;
this.pw = pw;
}

public void run() {
try {
int i;
for (i=1;i<10;i++)
{
int j;
for (j=2; j<i; j++)
{
int n = i%j;
if (n==0)
{
break;
}
}
if(i == j)
{
pw.write(i+"\n");
}
}

pw.close();



} catch (IOException e) {
}
}
}

class MyThread2 extends Thread {
private PipedReader pr;
private PipedWriter pw;

MyThread2(PipedReader pr, PipedWriter pw) {
this.pr = pr;
this.pw = pw;
}
public void run() {
try {
int f1, f2 = 1, f3 = 1;
for (int i = 1; i <10; i++) {
pw.write(f3+"\n");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
pw.close();
} catch (IOException e) {
}
}
}
class MultithreadedProgram {
public static void main(String[] args) throws Exception {
ArrayList list1=new ArrayList();
ArrayList list2=new ArrayList();
PipedWriter pw1 = new PipedWriter();
PipedReader pr1 = new PipedReader(pw1);
MyThread1 mt1 = new MyThread1(pr1, pw1);
System.out.println("Prime Numbers: ");
mt1.start();
int item1;
while ((item1 = pr1.read()) != -1){
char ch1=((char) item1);
System.out.print(Character.toString(ch1));
list1.add(Character.toString(ch1));
}
pr1.close();
PipedWriter pw2 = new PipedWriter();
PipedReader pr2 = new PipedReader(pw2);
MyThread2 mt2 = new MyThread2(pr2, pw2);
System.out.println("Fibonacci Numbers: ");
mt2.start();
int item2;
while ((item2 = pr2.read()) != -1){
char ch2=((char) item2);
System.out.print(Character.toString(ch2));
list2.add(Character.toString(ch2));
}
pr2.close();
System.out.println("Elements common to both lists are:");
list1.retainAll(list2);
for(int i=0;i<list1.size();i++){
System.out.print(list1.get(i));
}

}
}



EX NO: 20                          JAVA DATABASE CONNECTIVITY
DATE:


SOURCE CODE:

import java.awt.*;
import java.sql.*;
import sun.jdbc.odbc.*;
import java.lang.*;

public class jdbcp
{
    private Connection mycon;
    private Statement mystmt;

    public static void main(String arg[])
    {
        jdbcp que=new jdbcp();
    }
    public jdbcp()
    {
        try
        {
            connector();
            select();
            closer();
        }
        catch(SQLException e)
        {
            System.err.println("construct"+e);
        }
    }
void connector() throws SQLException
{
    try
    {
       
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        mycon=DriverManager.getConnection("jdbc:odbc:sss");
        mystmt=mycon.createStatement();
    }
    catch(Exception e)
    {
        System.err.println("con"+e);
    }
}
void select() throws SQLException
{
    final String select_sql="select * from login";
    ResultSet res=mystmt.executeQuery(select_sql);
    System.out.println("username"+"\t"+"password");
    System.out.println();
    while(res.next())
    {
        String str=res.getString("username");
        String str1=res.getString("password");
        //int r=res.getInt("password");
        System.err.println(str+"\t\t"+str);
    }
}
void closer() throws SQLException
{
    mycon.close();
}


}





EX NO: 21            MULTI-THREADED ECHO SERVER AND CLIENT
DATE:




// Client Program:-

import java.net.*;
import java.io.*;
class Client
{
    public static void main(String args[])throws IOException
    {
        Socket soc=null;
        String str=null;
        BufferedReader br=null;
        DataOutputStream dos=null;
        BufferedReader kyrd=new BufferedReader(new InputStreamReader(System.in));
        try
        {
            soc=new Socket(InetAddress.getLocalHost(),95);
            br=new BufferedReader(new InputStreamReader(soc.getInputStream()));
            dos=new DataOutputStream(soc.getOutputStream());
        }
        catch(UnknownHostException uhe)
        {
            System.out.println("Unknown Host");
            System.exit(0);
        }
        System.out.println("To start the dialog type the message in this client window \n Type exit to end");
        boolean more=true;
        while(more)
        {
            str=kyrd.readLine();
            dos.writeBytes(str);
            dos.write(13);
            dos.write(10);
            dos.flush();
            String s,s1;
            s=br.readLine();
            System.out.println("From server :"+s);
            if(s.equals("exit"))
                break;
        }
        br.close();
        dos.close();
        soc.close();
    }
}




// Server Program

import java.net.*;
import java.io.*;
class Server
{
    public static void main(String args[])throws IOException
    {
        ServerSocket ss=null;
        try
        {
            ss=new ServerSocket(95);
        }
        catch(IOException ioe)
        {
            System.out.println("Error finding port");
            System.exit(1);
        }
        Socket soc=null;
        try
        {
            soc=ss.accept();
            System.out.println("Connection accepted at :"+soc);
        }
        catch(IOException ioe)
        {
            System.out.println("Server failed to accept");
            System.exit(1);
        }
        DataOutputStream dos=new DataOutputStream(soc.getOutputStream());
        BufferedReader br=new BufferedReader(new InputStreamReader(soc.getInputStream()));
        String s;
        System.out.println("Server waiting for message from tthe client");
        boolean quit=false;
        do
        {
        String msg="";
        s=br.readLine();
        int len=s.length();
        if(s.equals("exit"))
       quit=true;
        for(int i=0;i<len;i++)
        {
         msg=msg+s.charAt(i);
        dos.write((byte)s.charAt(i));
            }
            System.out.println("From client :"+msg);
            dos.write(13);
            dos.write(10);
            dos.flush();
        }while(!quit);
        dos.close();
        soc.close();

    }
}




EX NO: 22                 PACKAGE PROGRAMS
DATE:


SOURCE CODE:

package mypack;

public class Balance
{
String name;
double bal;
public Balance(String n,double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal<0)
System.out.print("--------------->");
System.out.println(name+":$"+bal);
}
}



package mypack;

public class Balance1
{
String name;
double bal;
public Balance1(String n,double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal<0)
System.out.print("--------------->");
System.out.println(name+":$"+bal);
}
}




import mypack.*;


class TestBalance
{
public static void main(String args[])
{
Balance test=new Balance("ramya",123.88);
Balance1 test1=new Balance1("sathish",124.88);


test.show();
test1.show();
}
}



EX NO: 23                         CREATE FRAME
DATE:




import javax.swing.*;
import java.awt.*;
public class MyFrame {

 public static void main(String[] args) {
 
     JFrame frame = new JFrame("Test Frame");

frame.setSize(400, 300);
         frame.setVisible(true);
 frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);

 }
  
}



EX NO: 24             CREATE BUTTON, LABEL AND TEXTBOX
DATE:

import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;


public class DataEntry1 {



    public static void main(String[] args) {
       
try{

Frame frm=new Frame("DataEntry frame");
        Label lbl = new Label();
        frm.add(lbl);
        frm.setSize(350,200);
        frm.setVisible(true);
        frm.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
           

       

        Panel p = new Panel();
        Panel p1 = new Panel();
            p.setLayout(new GridLayout(4,2));
        Button in=new Button("INSERT");
        in.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
      
       
                System.out.println("welcome to HELLO WORLD1");

                }
            });
       

        p.add(in);
        p1.add(p);
        frm.add(p1,BorderLayout.CENTER);
       
        Button se=new Button("SELECT");
        se.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
      
       
                System.out.println("welcome to HELLO WORD2");

                }
            });
        p.add(se);
        p1.add(p);
        frm.add(p1,BorderLayout.EAST);
   

}
catch (Exception e){}
}

}




EX NO: 25             APPENDICES1- JAVA TUTORIAL FOR BEGINNERS-ONLINE URL
DATE:


URL:
    http://www.roseindia.net/java/beginners/

    http://www.freejavaguide.com/corejava.htm

    http://www.nskinfo.com

    http://www.roseindia.net/java/

    http://www.w3schools.com/js/default.asp

    http://code.geekinterview.com/java/multilevel-inheritance-in-java.html




EX NO: 26                    APPENDICES2- JAVA KEYWORDS
DATE:



URL:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Java Language Keywords
Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.
abstract    continue    for    new    switch
assert***    default    goto*    package    synchronized
boolean    do    if    private    this
break    double    implements    protected    throw
byte    else    import    public    throws
case    enum****    instanceof    return    transient
catch    extends    int    short    try
char    final    interface    static    void
class    finally    long    strictfp**    volatile
const*    float    native    super    while
*         not used
**         added in 1.2
***         added in 1.4
****         added in 5.0



EX NO: 27                 CLASS AND OBJECT IN JAVA-REAL TIME
DATE:


SOURCE CODE:

class tamilnadu
{
int a,b;
tamilnadu()
{
a=0;
b=0;
}
void TRICHY(int x,int y)
{
a=x;
b=y;
}
void SALEM()
{
System.out.println("the valus of a="+a);
System.out.println("the valus of b="+b);

}
}

class CHENNAI
{
public static void main(String args[])
{
tamilnadu sat=new tamilnadu();
sat.TRICHY(2,3);
sat.SALEM();
}
}

No comments:

Post a Comment