Top Banner

of 96

Java Lab.doc

Apr 03, 2018

Download

Documents

Naveen Nataraj
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/28/2019 Java Lab.doc

    1/96

    JAVA LAB

    1

  • 7/28/2019 Java Lab.doc

    2/96

    Aim:

    To write a program in Java with the following:

    (i) Develop a Rational number class.

    (ii) Use JavaDoc comments for documentation

    (iii) Implementation should use efficient representation for a rational number,

    i.e. (500/1000) should be represented as (1/2).

    Algorithm:

    1. Start the program.

    2. Declare a class called Rational and invoke a function called gcd(a,b).

    3. Find out the reminder when a is divided by b and pass it as a parameter to the function.

    4. Create an object for the class and declare the required string and integer variables.

    5. Create an object of class DataInputStream .Read thenumbers through the ReadLine()

    method into the object.

    6. Convert the input accepted into Integers through the parseInt method and store them in

    variables a and b.

    7. Store the value returned by the function GCD in variable8. Divide a by l and b by l and store them in variables x and y.

    9. Stop the Program.

    Program:

    import java.util.*;

    public class RationalClass

    {

    private int numerator;

    private int denominator;

    public RationalClass(int numerator,int denominator)

    {

    if(denominator==0)

    {

    throw new RuntimeException("Denominator is zero");

    }

    int g=gcd(numerator,denominator);

    2

    Ex.No:1RATIONAL NUMBER CLASS IN JAVADate:

  • 7/28/2019 Java Lab.doc

    3/96

    if(g==1)

    {

    System.out.println("No Common Divisor for Numerator and Denominator");

    this.numerator=numerator;

    this.denominator=denominator;

    }

    else

    {

    this.numerator=numerator/g;

    this.denominator=denominator/g;

    }

    }

    public String display()

    {

    return numerator+"/"+denominator;

    }

    private static int gcd(int n,int d)

    {

    if(d==0)

    return n;

    else

    return gcd(d,n%d);

    }

    public static void main(String[] args)

    {

    Scanner input=new Scanner(System.in);

    System.out.print("Enter Numerator : ");

    int numerator=input.nextInt();

    System.out.print("Enter Denominator : ");

    int denominator=input.nextInt();

    RationalClass rational = new RationalClass(numerator,denominator);

    String str=rational.display();

    System.out.println("Efficient Representation for the rational number :" +str); } }

    3

  • 7/28/2019 Java Lab.doc

    4/96

    Output:

    SUPPLEMENTARY PROGRAMS:

    1. Develop the Java program to reverse String in Java without using API functions?

    2. Develop the Java program to print Fibonacci series upto 100?

    3. Develop the Java program to Java program to find if a number is prime number or not?

    4. Develop the Java program to check if a number is Armstrong or not (Eg. 371 is Armstrong

    Number [33+73 +13 = 371])?

    5. Develop the Java program to print following structure in Java

    *

    ***

    *****

    ***

    *

    If the user input data in 5.

    Viva Questions:

    1. Define Package ?

    2. What are the main application of Package ?

    3. Code to get the user input dynamically?

    4. What is CommandLine Arguments ?

    5. Explain the features of Java Language ?

    4

  • 7/28/2019 Java Lab.doc

    5/96

    Result:

    Thus the above program was executed and verified successfully.

    Aim:

    To develop Date class in Java similar to the one available in java.util package. UseJavaDoc comments for documentation.

    Algorithm:

    1. Start the program.

    2. Declare a class called Date example and create an object called date.

    3. Display the Date and Time through these objects with the Methods in Date Class.

    4. Declare two objects called start time and end time for this class.

    5. Create another object called changed object and display the changed time with

    the calculation 24L*60L*60L*1000L.

    6. In the main function create object for the class Date and display the time and date

    accordingly.

    7. Stop the program.

    Program:

    import java.text.*;

    import java.util.*;

    /**

    *Class DateFormatDemo formats the date and time by using java.text package

    */

    public class DateFormatDemo

    {

    public static void main(String args[])

    {

    /**

    * @see java.util package

    */

    Date date=new Date();

    5

    Ex.No:2DATE CLASS IN JAVADate:

  • 7/28/2019 Java Lab.doc

    6/96

    /**

    * @see java.text package

    */

    DateFormat df;

    System.out.println("Current Date and Time - Available in java.util Package:");

    System.out.println("-------------------------------------------------------");

    System.out.println(date);

    System.out.println();

    System.out.println("Formatted Date - Using DateFormat Class from java.text Package:");

    System.out.println("---------------------------------------------------------------");

    df=DateFormat.getDateInstance(DateFormat.DEFAULT);

    System.out.println("Default Date Format:"+df.format(date));

    df=DateFormat.getDateInstance(DateFormat.SHORT);

    System.out.println("Date In Short Format:"+df.format(date));

    df=DateFormat.getDateInstance(DateFormat.MEDIUM);

    System.out.println("Date In Medium Format:"+df.format(date));

    df=DateFormat.getDateInstance(DateFormat.LONG);

    System.out.println("Date In Long Format:"+df.format(date));

    df=DateFormat.getDateInstance(DateFormat.FULL);

    System.out.println("Date In Full Format:"+df.format(date));

    System.out.println();

    System.out.println("Formatted Time - Using DateFormat Class from java.text Package:");

    System.out.println("---------------------------------------------------------------");

    df=DateFormat.getTimeInstance(DateFormat.DEFAULT);

    System.out.println("Default Time Format:"+df.format(date));

    df=DateFormat.getTimeInstance(DateFormat.SHORT);

    System.out.println("Time In Short Format:"+df.format(date));

    df=DateFormat.getTimeInstance(DateFormat.MEDIUM);

    System.out.println("Time In Medium Format:"+df.format(date));

    df=DateFormat.getTimeInstance(DateFormat.LONG);

    System.out.println("Time In Long Format:"+df.format(date));

    df=DateFormat.getTimeInstance(DateFormat.FULL);

    System.out.println("Time In Full Format:"+df.format(date));

    System.out.println();

    6

  • 7/28/2019 Java Lab.doc

    7/96

    System.out.println("Formatted Date and Time - Using SimpleDateFormat Class from java.text

    Package:");

    System.out.println("------------------------------------------------------------------------------");

    /**

    * @see java.text package

    */

    SimpleDateFormat sdf;

    sdf=new SimpleDateFormat("dd MMM yyyy hh:mm:sss:S E w D zzz");

    System.out.println(sdf.format(date));

    }

    }

    7

  • 7/28/2019 Java Lab.doc

    8/96

    Output:

    Supplementary Programs:

    1. Develop Calendar class in Java similar to the one available in java.util package

    2. Develop timezone class in Java similar to the one available in java.util package

    3. Develop Random class in Java similar to the one available in java.util package

    Viva Questions:

    1. What is the use of JavaDoc comments ?

    8

  • 7/28/2019 Java Lab.doc

    9/96

    2. Define some other methods under object java.text?

    3. Define some other methods under object java.util ?

    4. What is syntax for getDateInstance() function and its application ?

    5. What is the main purpose of using java.text object ?

    Result:

    Thus the above program was executed and verified successfully.

    Aim:

    To implement Lisp-like list in Java that performs the basic operations such as 'car', 'cdr',

    and 'cons'.

    Algorithm:

    1. Start the program.

    2. Create a node of a list having data part and link part.

    3. Create a menu having the following choices : insert, car, cdr, adjoin and

    display.

    4. Read the choice from the user and call the respective methods.

    5. Create another class which implements the same interface to implement the concept of

    stack through linked list.

    6. Car class will return the first node data.

    7. CDR will return the entire node (data part) in the list except the first node.

    8. Stop the program.

    Program:

    import java.util.*;

    class Lisp

    9

    Ex.No:3LISP-LIKE LIST IN JAVADate:

  • 7/28/2019 Java Lab.doc

    10/96

    {

    public Vector car(Vector v)

    {

    Vector elt=new Vector();

    elt.addElement(v.elementAt(0));

    return elt;

    }

    public Vector cdr(Vector v)

    {

    Vector elt=new Vector();

    for(int i=1;i

  • 7/28/2019 Java Lab.doc

    11/96

    1. Define Lisp list?

    2. What are the available operations in Lisp list?

    3. What is the function to check whether the object is empty or not?

    Result:

    Thus the above program was executed and verified successfully.

    return elt;

    }

    public Vector cons(int x, Vector v)

    {

    v.insertElementAt(x,0);

    return v;

    }}

    class LispOperation

    {

    public static void main(String[] args)

    {

    Lisp L=new Lisp();

    Vector v=new Vector(4,1);

    v.addElement(3);

    v.addElement(0);

    v.addElement(2);

    v.addElement(5);

    System.out.println("Basic Lisp Operations");

    System.out.println("---------------------");

    System.out.println("The Elements of the List are:"+v);

    System.out.println("Lisp Operation-CAR:"+L.car(v));

    11

  • 7/28/2019 Java Lab.doc

    12/96

    System.out.println("Lisp Operation-CDR:"+L.cdr(v));

    System.out.println("Elements of the List After CONS:"+L.cons(9,v));

    }

    }

    12

  • 7/28/2019 Java Lab.doc

    13/96

    13

  • 7/28/2019 Java Lab.doc

    14/96

    14

  • 7/28/2019 Java Lab.doc

    15/96

    Aim:

    To Design a Java interface for ADT Stack with the following:

    (i) Develop a class that implement this interface.

    (ii)Provide necessary exception handling in the implementation.

    Algorithm:

    1. Start the program.

    2. Create an interface which consists of three methods namely PUSH, POP and

    DISPLAY

    3. Create a class which implements the above interface to implement the concept of

    stack through Array

    4. Define all the methods of the interface to push any element, to pop the top element

    and to display the elements present in the stack.

    5. Create another class which implements the same interface to implement the concept

    of stack through linked list.

    6. Repeat STEP 5 for the above said class also.

    7. In the main class, get the choice from the user to choose whether array

    implementation or linked list implementation of the stack.

    8. Call the methods appropriately according to the choices made by the user in the

    previous step.

    9. Repeat step 7 and step 8 until the user stops his/her execution

    10. Stop the Program

    15

    Ex.No:4JAVA INTERFACE FOR ADT STACKDate:

  • 7/28/2019 Java Lab.doc

    16/96

    Program:

    import java.io.*;

    import java.util.*;

    interface stackInterface

    {

    int n=50;

    public void pop();

    16

  • 7/28/2019 Java Lab.doc

    17/96

    public void push();

    public void display();

    }

    class stack implements stackInterface

    {

    int arr[]=new int[n];

    int top=-1;

    Scanner in=new Scanner(System.in);

    public void push()

    {

    try

    {

    System.out.println("Enter The Element of Stack");

    int elt=in.nextInt();

    arr[++top]=elt;

    }

    catch (Exception e)

    {

    System.out.println("e");

    }

    }

    public void pop()

    {

    int pop=arr[top];

    top--;

    System.out.println("Popped Element Is:"+pop);

    17

  • 7/28/2019 Java Lab.doc

    18/96

    }

    public void display()

    {

    if(top

  • 7/28/2019 Java Lab.doc

    19/96

    else

    {

    19

  • 7/28/2019 Java Lab.doc

    20/96

    String str=" ";

    for(int i=0;i

  • 7/28/2019 Java Lab.doc

    21/96

    1. Design a Java interface for ADT Queue .

    2. Design a Java interface for ADT Linked List.

    Viva Questions:

    1. Define stack and the operations performed in stack?

    2. Define queue and the operations performed in stack?

    3. Define linked list and the operations performed in stack?

    4. Define interface? What are the advantages of using interfaces in program?

    5. How will you initialize arrays?

    Result:

    Thus the above program was executed and verified successfully.

    21

  • 7/28/2019 Java Lab.doc

    22/96

    break;

    case 4:

    System.exit(0);

    }

    }

    while(no

  • 7/28/2019 Java Lab.doc

    23/96

    23

  • 7/28/2019 Java Lab.doc

    24/96

    24

  • 7/28/2019 Java Lab.doc

    25/96

    25

  • 7/28/2019 Java Lab.doc

    26/96

    26

  • 7/28/2019 Java Lab.doc

    27/96

    Aim:

    To design a vehicle class hierarchy in Java that demonstrates the concept of polymorphism.

    Algorithm:

    1. Start the program.

    2. Create an abstract class named vehicle with abstract method Display and a concrete

    method Input.

    3. Define the input method by prompting the user to enter the values for name, owner,

    type, number, engine capacity, seating capacity for the vehicle; all the inputs taken in

    the form string.

    4. Extend three classes namely twowheeler , threewheeler , fourwheeler from the base

    class.

    5. Define the method display under the class VehicleDemo by displaying all the entered

    values.

    6. Repeat step 5 for the class VehicleDemo.

    27

    Ex.No:5VEHICLE CLASS HIERARCHY IN JAVADate:

  • 7/28/2019 Java Lab.doc

    28/96

    7. Extend the input method for the class Vehicle by taking in the value of wheeling

    capacity for the vehicle in the form of string.

    8. In the main method create a reference for the abstract class and create a switch case to

    perform operations on the opted class.

    9. Under each class create a switch case to either enter the data or to display the transport

    report.

    10. Repeat the main menu on the user's choice.

    11. Create array of objects under each class and call the methods by assigning the values of

    the created objects to the reference object, to show polymorphism.

    12. Stop the program.

    28

  • 7/28/2019 Java Lab.doc

    29/96

    Program:

    import java.io.*;

    class Vehicle

    {

    String regno;

    int model;

    Vehicle(String r, int m)

    {

    regno=r;

    model=m;

    }

    void display()

    {

    System.out.println("Registration Number:"+regno);

    System.out.println("Model Number:"+model);

    }

    }

    class Twowheeler extends Vehicle

    {

    29

  • 7/28/2019 Java Lab.doc

    30/96

    int wheel;

    Twowheeler(String r,int m,int n)

    {

    super(r,m);

    wheel=n;

    }

    void display()

    {

    System.out.println("Vehicle : Two Wheeler");

    System.out.println("=====================");

    super.display();

    System.out.println("Number of Wheels:"+wheel+"\n");

    }

    }

    class Threewheeler extends Vehicle

    30

  • 7/28/2019 Java Lab.doc

    31/96

    {

    int leaf;

    Threewheeler(String r,int m,int n)

    {

    super(r,m);

    leaf=n;

    }

    void display()

    {

    System.out.println("Vehicle : Three Wheeler");

    System.out.println("=======================");

    super.display();

    System.out.println("Number of Leaf:"+leaf+"\n");

    }

    }

    class Fourwheeler extends Vehicle

    {

    int leaf;

    Fourwheeler(String r,int m,int n)

    31

  • 7/28/2019 Java Lab.doc

    32/96

  • 7/28/2019 Java Lab.doc

    33/96

    E

    VIVA QUESTIONS:

    1. Define Inheritance?

    2. What are the types of inheritance?

    3. How is multiple inheritances achieved in java?

    4. What is Inheritance Hierarchy?

    5. What is the use of super keyword?

    Result:

    Thus the above program was executed and verified successfully.

    {

    Twowheeler two=new Twowheeler("TN75 9843", 2011,2);

    Threewheeler three=new Threewheeler("TN30 8766", 2010,3);

    Fourwheeler four=new Fourwheeler("TN15 2630",2009,4);

    two.display();

    three.display();

    four.display();

    }

    }

    33

    Arts En .

    B.Sc BCA BE CSE BE ECE

  • 7/28/2019 Java Lab.doc

    34/96

    34

  • 7/28/2019 Java Lab.doc

    35/96

    35

  • 7/28/2019 Java Lab.doc

    36/96

    36

  • 7/28/2019 Java Lab.doc

    37/96

    Aim:

    To write a program in java to demonstrate object serialization with the following:

    (i) Design classes for Currency, Rupee, and Dollar.(ii) Write a program that randomly generates Rupee and Dollar objects and write them into a file

    using object serialization.(iii) Write another program to read that file.

    (iv) Convert to Rupee if it reads a Dollar and leave the value if it reads a Rupee.

    Algorithm For writeobj.java :

    1. Start the program.

    2. Create a class named currency that implements the serializable interface and also it is

    the base class for rupee and dollar classes.

    3. Create an object for ObjectOutputStream to open a file in write mode using

    FileOutputStream.

    4. Read the user choice to enter rupee or dollar amount.

    37

    Ex.No:6

    OBJECT SERIALIZATIONDate:

  • 7/28/2019 Java Lab.doc

    38/96

    5. Generate random numbers as the value of rupee or dollar.

    6. If choice is rupee then, append "Rs" to the value generated, else if choice is

    dollar append "$" to the value generated.

    7. Display the appended String and also write it into the file opened using the

    writeObject() method.

    8. Stop the program

    Algorithm For readobj.java:

    1. Start the program.

    2. Create a class named currency that implements the serializable interface and also it

    is the base class for rupee and dollar classes.

    3. Create an object for ObjectInputStream to open the file created in program1 in read

    mode using FileInputStream.

    4. If the file does not exist or if it is empty show exceptions.

    5. While the End of file is not reached, do the following...

    (i) If the value read is a dollar convert into rupee and print to the user otherwise

    print the rupee as such.

    6. End the program.

    38

  • 7/28/2019 Java Lab.doc

    39/96

    Program:

    writeObj.java

    import java.io.*;

    import java.util.*;

    abstract class Currency implements Serializable

    {

    protected double money;

    public abstract double getValue();

    public abstract String printObj();

    public Currency(double money)

    {

    this.money=money;

    }

    }

    class Dollar extends Currency

    {

    public Dollar(int money)

    39

  • 7/28/2019 Java Lab.doc

    40/96

  • 7/28/2019 Java Lab.doc

    41/96

    super(amount);

    }

    41

  • 7/28/2019 Java Lab.doc

    42/96

    public double getValue()

    {

    return this.money;

    }

    public String printObj()

    {

    String object="Object Name : Rupee \nINR : Rs "+getValue()+"\n";

    return object;

    }

    }

    public class writeObj

    {

    public static void main(String[] args) throws FileNotFoundException,IOException

    {

    FileOutputStream fos=new FileOutputStream("currencyInfo.txt");

    ObjectOutputStream oos=new ObjectOutputStream(fos);

    Random rand=new Random();

    for(int i=0;i

  • 7/28/2019 Java Lab.doc

    43/96

    1. Write a program in java to demonstrate object serialization with the following

    a. Create Gold Price list dynamically and write them into a file using objectserialization.

    b. Write another program to read that file.

    2. Write a program in java to demonstrate object serialization with the following

    a. Create a Company share list dynamically and write them into a file using objectserialization.b. Write another program to read that file.

    Viva Questions:

    1. What is Serialization?

    2. What is the need of Serialization?

    3. Other than Serialization what are the different approach to make object Serializable?

    4. What happens if the object to be serialized includes the references to other serializable

    objects and to other non-serializable objects?

    5. If a class is serializable but its superclass in not , what will be the state of the instance

    variables inherited from super class after deserialization?

    6. Does the order in which the value of the transient variables and the state of the object using

    the defaultWriteObject() method are saved during serialization matter?

    7. How can one customize the Serialization process? or What is the purpose of implementing

    the writeObject() and readObject() method?

    Result:

    Thus the above program was executed and verified successfully.

    43

  • 7/28/2019 Java Lab.doc

    44/96

    readObj.java

    import java.io.*;

    public class readObj

    {

    public static void main(String[] args) throws IOException,ClassNotFoundException

    {

    Currency currency=null;

    FileInputStream fis=new FileInputStream("currencyInfo.txt");

    ObjectInputStream ois=new ObjectInputStream(fis);

    while((currency=(Currency)ois.readObject())!=null)

    {

    System.out.println(currency.printObj());

    }

    ois.close();

    }

    }

    44

  • 7/28/2019 Java Lab.doc

    45/96

    45

  • 7/28/2019 Java Lab.doc

    46/96

    46

  • 7/28/2019 Java Lab.doc

    47/96

    47

    Ex.No:7 SCIENTIFIC CALCULATOR IN JAVADate:

  • 7/28/2019 Java Lab.doc

    48/96

  • 7/28/2019 Java Lab.doc

    49/96

    add(panel);

    pack();

    }

    }

    49

  • 7/28/2019 Java Lab.doc

    50/96

    class CalcPanel extends JPanel

    {

    JButton display;

    JPanel panel;

    double result;

    String lastcmd;

    boolean start;

    public CalcPanel()

    {

    setLayout(new BorderLayout());

    result=0;

    lastcmd="=";

    start=true;

    display=new JButton("0");

    display.setEnabled(false);

    add(display,BorderLayout.NORTH);

    ActionListener insert=new InsertAction();

    ActionListener cmd=new CommandAction();

    panel=new JPanel();

    panel.setLayout(new GridLayout(5,4));

    addButton("1",insert);

    addButton("2",insert);

    addButton("3",insert);

    addButton("/",cmd);

    addButton("4",insert);

    addButton("5",insert);

    addButton("6",insert);

    addButton("*",cmd);

    addButton("7",insert);

    addButton("8",insert);

    50

  • 7/28/2019 Java Lab.doc

    51/96

  • 7/28/2019 Java Lab.doc

    52/96

    addButton("pow",cmd);

    addButton("+",cmd);

    addButton("sin",insert);

    addButton("cos",insert);

    addButton("tan",insert);

    addButton("=",cmd);

    add(panel, BorderLayout.CENTER);

    }

    private void addButton(String label,ActionListener listener)

    {

    JButton button=new JButton(label);

    button.addActionListener(listener);

    panel.add(button);

    }

    private class InsertAction implements ActionListener

    {

    public void actionPerformed(ActionEvent ae)

    {

    String input=ae.getActionCommand();

    if(start==true)

    {

    display.setText("");

    start=false;

    }

    if(input.equals("sin"))

    {

    Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;

    display.setText(""+Math.sin(angle));

    }

    else if(input.equals("cos"))

    52

  • 7/28/2019 Java Lab.doc

    53/96

  • 7/28/2019 Java Lab.doc

    54/96

    else if(input.equals("tan"))

    {

    Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;

    display.setText(""+Math.tan(angle));

    }

    else

    display.setText(display.getText()+input);

    }

    }

    private class CommandAction implements ActionListener

    {

    public void actionPerformed(ActionEvent ae)

    {

    String command=ae.getActionCommand();

    if(start==true)

    {

    if(command.equals("-"))

    {

    display.setText(command);

    start=false;

    }

    else

    lastcmd=command;

    }

    else

    {

    calc(Double.parseDouble(display.getText()));

    lastcmd=command;

    start=true;

    }

    Output:

    54

  • 7/28/2019 Java Lab.doc

    55/96

  • 7/28/2019 Java Lab.doc

    56/96

    Thus the above program was executed and verified successfully.

    }

    }

    public void calc(double x)

    {

    if(lastcmd.equals("+"))

    result=result+x;

    else if(lastcmd.equals("-"))

    result=result-x;

    else if(lastcmd.equals("*"))

    result=result*x;

    else if(lastcmd.equals("/"))

    result=result/x;

    else if(lastcmd.equals("="))

    result=x;

    else if(lastcmd.equals("pow"))

    {

    double powval=1.0;

    for(double i=0.0;i

  • 7/28/2019 Java Lab.doc

    57/96

    57

  • 7/28/2019 Java Lab.doc

    58/96

    58

  • 7/28/2019 Java Lab.doc

    59/96

    59

    Ex.No:8MULTITHREADING IN JAVADate:

  • 7/28/2019 Java Lab.doc

    60/96

    Aim:

    To write a multi-threaded Java program to print all numbers below 100,000 that are both

    prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a

    thread that generates prime numbers below 100,000 and writes them into a pipe.

    Design another thread that generates fibonacci numbers and writes them to another

    pipe. The main thread should read both the pipes to identify numbers common to

    both.

    Algorithm:

    1. Start the program.

    2. Design a thread that generates prime numbers below 100,000 and writes them

    into a pipe.

    3. Design another thread that generates fibonacci numbers and writes them to another

    pipe.

    4. Design a main thread should read both the pipes to identify numbers common to both

    prime and Fibonacci and print all the numbers common to both prime and Fibonacci.

    5. Stop the program.

    Program:

    import java.util.*;

    import java.io.*;

    class Fibonacci extends Thread

    {

    private PipedWriter out=new PipedWriter();

    public PipedWriter getPipedWriter()

    {

    return out;

    }

    public void run()

    {

    60

  • 7/28/2019 Java Lab.doc

    61/96

    Thread t=Thread.currentThread();

    t.setName("Fibonacci");

    System.out.println(t.getName()+" Thread started...");

    61

  • 7/28/2019 Java Lab.doc

    62/96

    int fibo=0,fibo1=0,fibo2=1;

    while(true)

    {

    try

    {

    fibo=fibo1+fibo2;

    if(fibo>100000)

    {

    out.close();

    break;

    }

    out.write(fibo);

    sleep(1000);

    }

    catch(Exception e)

    {

    System.out.println("Exception:"+e);

    }

    fibo1=fibo2;

    fibo2=fibo;

    }

    System.out.println(t.getName()+" Thread exiting...");

    }

    }

    class Prime extends Thread

    {

    private PipedWriter out1=new PipedWriter();

    public PipedWriter getPipedWriter()

    {

    return out1;

    }

    62

  • 7/28/2019 Java Lab.doc

    63/96

    public void run()

    {

    Thread t=Thread.currentThread();

    63

  • 7/28/2019 Java Lab.doc

    64/96

    t.setName("Prime");

    System.out.println(t.getName() +" Thread Started...");

    int prime=1;

    while(true)

    {

    try

    {

    if(prime>100000)

    {

    out1.close();

    break;

    }

    if(isPrime(prime))

    out1.write(prime);

    prime++;

    sleep(0);

    }

    catch(Exception e)

    {

    System.out.println(t.getName()+" Thread exiting...");

    System.exit(0);

    }

    }

    }

    public boolean isPrime(int n)

    {

    int m=(int)Math.round(Math.sqrt(n));

    if(n==1||n==2)

    return true;

    for(int i=2;i

  • 7/28/2019 Java Lab.doc

    65/96

    Supplementary Programs:

    1. Write a multi-threaded Java program implementing the watch mechanism. Create Thread for

    seconds, minutes, hours, date, day, month and display the details correspondingly.

    2. Write a java program to print the alphabets between sequence of numbers using multithreading

    concepts.

    Viva Questions:

    1. Define Thread? What are the advantages of using Threads?

    2. What are the methods available in Thread and explain its purpose?

    3. Difference between thread and process?

    4. What is context switching in multi-threading?

    5. Difference between deadlock and livelock, deadlock and starvation?

    6. What thread-scheduling algorithm is used in Java?

    7. How do you handle un-handled exception in thread?

    Result:

    Thus the above program was executed and verified successfully.

    65

  • 7/28/2019 Java Lab.doc

    66/96

    return false;

    return true;

    }

    }

    public class MultiThreadDemo

    {

    public static void main(String[] args)throws Exception

    {

    Thread t=Thread.currentThread();

    t.setName("Main");

    System.out.println(t.getName()+" Thread Started...");

    Fibonacci fibObj=new Fibonacci();

    Prime primeObj=new Prime();

    PipedReader pr=new PipedReader(fibObj.getPipedWriter());

    PipedReader pr1=new PipedReader(primeObj.getPipedWriter());

    fibObj.start();

    primeObj.start();

    int fib=pr.read(),prm=pr1.read();

    System.out.println("The numbers common to PRIME and FIBONACCI:");

    while((fib!=-1)&&(prm!=-1))

    {

    while(prm

  • 7/28/2019 Java Lab.doc

    67/96

    67

  • 7/28/2019 Java Lab.doc

    68/96

    68

  • 7/28/2019 Java Lab.doc

    69/96

    69

  • 7/28/2019 Java Lab.doc

    70/96

    Aim:

    To develop a simple OPAC system for library using event-driven programming paradigmsof Java.Use JDBC to connect to a back-end database.

    Algorithm:

    1. Start the program.

    2. Create a Master Database1 (Book Details) having the following fields: BookNo. , Book

    Name, Author, No. of pages, Name of Publisher, Cost.

    3. Create a Master Database2(User Details) having the following fields : UserID,

    Department

    4. Create a Transaction Database having the following fields: UserID,Book No., Date of

    Renewal / Date of Return, Fine

    5. Create a panel consisting of buttons ADD, UPDATE, DELETE. Associate these button

    actions with listeners(with Master Database 1)

    6. Create a panel consisting of buttons ADD, UPDATE, DELETE. Associate these button

    actions with listeners(with Master Database 2)

    7. Create another panel consisting of buttons UserID, BookID, Return/Renewal, Fine.

    8. Associate these buttons with listeners (with Transaction Database).

    9. Stop the program.

    Program:

    import java.sql.*;

    import java.awt.*;

    import java.awt.event.*;

    import javax.swing.*;

    import javax.swing.table.*;

    public class OpacSystem implements ActionListener

    {

    JRadioButton author=new JRadioButton("Search By Author");

    JRadioButton book=new JRadioButton("Search by Book");

    JTextField txt=new JTextField(30);JLabel label=new JLabel("Enter Search Key");

    70

    Ex.No:9OPAC SYSTEM USING JAVADate:

  • 7/28/2019 Java Lab.doc

    71/96

    71

  • 7/28/2019 Java Lab.doc

    72/96

    JButton search=new JButton("SEARCH");

    JFrame frame=new JFrame();

    JTable table;

    DefaultTableModel model;

    String query="select*from opacTab";

    public OpacSystem()

    {

    frame.setTitle("OPAC SYSTEM");

    frame.setSize(800,500);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setLayout(new BorderLayout());

    JPanel p1=new JPanel();

    p1.setLayout(new FlowLayout());

    p1.add(label);

    p1.add(txt);

    ButtonGroup bg=new ButtonGroup();

    bg.add(author);

    bg.add(book);

    JPanel p2=new JPanel();

    p2.setLayout(new FlowLayout());

    p2.add(author);

    p2.add(book);

    p2.add(search);

    search.addActionListener(this);

    JPanel p3=new JPanel();

    p3.setLayout(new BorderLayout());

    p3.add(p1,BorderLayout.NORTH);

    p3.add(p2,BorderLayout.CENTER);

    frame.add(p3,BorderLayout.NORTH);

    addTable(query);

    frame.setVisible(true);

    }

    public void addTable(String str)

    {

    72

  • 7/28/2019 Java Lab.doc

    73/96

    73

  • 7/28/2019 Java Lab.doc

    74/96

    try

    {

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    Connection con=DriverManager.getConnection("jdbc:odbc:opacDS");

    Statement stmt=con.createStatement();

    ResultSet rs=stmt.executeQuery(str);

    ResultSetMetaData rsmd=rs.getMetaData();

    int cols=rsmd.getColumnCount();

    model=new DefaultTableModel(1,cols);

    table=new JTable(model);

    String[] tabledata=new String[cols];

    int i=0;

    while(i

  • 7/28/2019 Java Lab.doc

    75/96

    Output:

    Supplementary Program:1. Using JDBC create the even-driven programming for student mark entry.

    2. Using JDBC create the even-driven programming to create, view and alter employee

    profile.

    Viva Questions:

    1. What is JDBC?

    2. What are the main steps in java to make JDBC connectivity?

    3. Does the JDBC-ODBC Bridge support multiple concurrent open statements per

    connection?

    4. Explain the JDBC Architecture?

    5. What are the main components of JDBC?

    6. Code to call the query / stored procedure from JDBC?

    75

  • 7/28/2019 Java Lab.doc

    76/96

    7. Code to set the JDBC Connection with the Database server?

    Result:

    Thus the above program was executed and verified successfully.if(author.isSelected())

    query="select*from opacTab where AUTHOR like '"+txt.getText()+"%'";

    if(book.isSelected())

    query="select*from opacTab where BOOK like '"+txt.getText()+"%'";

    while(model.getRowCount()>0)

    model.removeRow(0);

    frame.remove(table);

    addTable(query);

    }

    public static void main(String[] args)

    {

    OpacSystem os=new OpacSystem();

    }

    }

    76

  • 7/28/2019 Java Lab.doc

    77/96

    77

  • 7/28/2019 Java Lab.doc

    78/96

    78

  • 7/28/2019 Java Lab.doc

    79/96

    79

  • 7/28/2019 Java Lab.doc

    80/96

    Aim:

    To develop a multi-threaded echo server and a corresponding GUI client in Java.

    Algorithm for Server:

    1. Start the program.

    2. Establish the connection of socket.

    3. Assign the local Protocol address to the socket.

    4. Move the socket from closed to listener state and provide maximum no. of Connections.

    5. Create a new socket connection using client address.

    6. Read the data from the socket.

    7. Write the data into socket.

    8. Close the socket.

    9. Stop the program.

    Program:

    EchoServer.java

    import java.io.*;

    import java.net.*;

    public class EchoServer

    {

    public static void main(String [] args)

    {

    System.out.println("Server Started....");

    try

    {

    ServerSocket ss=new ServerSocket(300);

    while(true)

    {

    Socket s= ss.accept();

    Thread t = new ThreadedServer(s);

    t.start();

    80

    Ex.No:10MULTI-THREADED ECHO SERVERDate:

  • 7/28/2019 Java Lab.doc

    81/96

  • 7/28/2019 Java Lab.doc

    82/96

    }

    }

    catch(Exception e)

    {

    System.out.println("Error: " + e);

    }

    }

    }

    class ThreadedServer extends Thread

    {

    Socket soc;

    public ThreadedServer(Socket soc)

    {

    this.soc=soc;

    }

    public void run()

    {

    try

    {

    BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream()));

    PrintWriter out=new PrintWriter(soc.getOutputStream());

    String str=in.readLine();

    System.out.println("Message From Client:"+str);

    out.flush();

    out.println("Message To Client:"+str);

    out.flush();

    }

    catch(Exception e)

    {

    System.out.println("Exception:"+e);

    }

    }

    }

    82

  • 7/28/2019 Java Lab.doc

    83/96

    Output:

    Server:

    Client:

    EchoClient.java

    83

  • 7/28/2019 Java Lab.doc

    84/96

    import java.net.*;

    import java.io.*;

    import javax.swing.*;

    import java.awt.*;

    import java.awt.event.*;

    class EchoClient extends JFrame

    {

    JTextArea ta;

    JTextField msg;

    JPanel panel;

    JScrollPane scroll;

    JButton b1=new JButton("Close");

    JButton b2=new JButton("Send");

    JLabel l1=new JLabel("Echo Client GUI");

    Container c;

    EchoClient()

    {

    c=getContentPane();

    setSize(300,470);

    setTitle("GUI Client");

    panel=new JPanel();

    msg=new JTextField(20);

    panel.setLayout(new FlowLayout(FlowLayout.CENTER));

    ta=new JTextArea(20,20);

    scroll=new JScrollPane(ta);

    panel.add(l1);

    panel.add(ta);

    panel.add(msg);

    panel.add(b2);

    panel.add(b1);

    c.add(panel);

    b2.addActionListener(new ActionListener()

    {

    84

  • 7/28/2019 Java Lab.doc

    85/96

    Supplementary Program:

    1. Develop the Multiuser chat application using java

    2. Develop the echo server and a corresponding GUI client for transferring the files.

    Viva Questions:

    1. Define Socket? What is the purpose of using Socket?

    2. Name the seven layers of the OSI Model and describe them briefly?

    3. What are some advantages and disadvantages of Java Sockets?

    4. What are the functions available in "java.net" package?

    5. What is the functionality of "flush" function?

    6. Define Exception handling? Why we ned to use Exception handling in our code? Syntax for

    try catch exception?

    7. What are the functions available in "java.awt.event" package?

    8. What is the function used to send the message to server / other client?

    Result:

    85

  • 7/28/2019 Java Lab.doc

    86/96

    Thus the above program was executed and verified successfully.

    public void actionPerformed(ActionEvent ae)

    {

    try

    {

    Socket s=new Socket("localhost",300);

    BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));

    PrintWriter out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

    out.println(msg.getText());

    out.flush();

    String temp =ta.getText();

    if(temp.equalsIgnoreCase("quit"))

    {

    System.exit(0);

    }

    msg.setText("");

    ta.append("\n"+in.readLine());

    }

    catch (IOException e)

    {

    ta.setText("Exception:"+e);

    } }

    } );

    b1.addActionListener(new ActionListener()

    {

    public void actionPerformed(ActionEvent e){

    System.exit(0);

    } } ); }

    public static void main(String args[])

    {

    EchoClient frame=new EchoClient();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setVisible(true);

    86

  • 7/28/2019 Java Lab.doc

    87/96

    } }

    87

  • 7/28/2019 Java Lab.doc

    88/96

    88

  • 7/28/2019 Java Lab.doc

    89/96

    Additional Viva Questions:

    1. What are the OOP Principles?

    2. What is Encapsulation?

    3. What is Polymorphism?

    4. What is Inheritance?

    5. What are the features of Java Language?

    6. What is the need for Java Language?

    7. What is platform independency?

    8. What is Architecture Neutral?

    9. How Java supports platform independency?

    10. Why Java is important to Internet?

    11. What are the types of programs Java can handle?

    12. What is an applet program?

    13. Compare Application and Applet.

    14. What are the advantages of Java Language?

    15. Give the contents of Java Environment (JDK).

    16. Give any 4 differences between C and Java.

    17. Give any 4 differences between C++ and Java.

    18. What are the different types of comment symbols in Java?

    19. What are the data types supported in Java?

    20. What is the difference between a char in C/C++ and char in Java?

    21. How is a constant defined in Java?

    22. What is the use of final keyword?

    89

  • 7/28/2019 Java Lab.doc

    90/96

  • 7/28/2019 Java Lab.doc

    91/96

    46. What is method overloading?

    47. What is a String in Java?

    48. What is the difference between a String in Java and String in C/C++?

    49. Name a few String methods.

    50. What is the difference between Concat method and + operator to join strings?

    51. What is String Buffer?

    52. How does String class differ from the String Buffer class?

    53. Name some methods available under String Buffer class.

    54. Output of some expressions using String methods.

    55. How will you initialize arrays?

    56. What is arraycopy method? Explain with syntax.

    57. What are the methods under Util.Arrays?

    58. Use the array sort method to sort the given array.

    59. Give the syntax for array fill operation.

    60. What is vector? How is it different from an array?

    61. What is the constraint for using vectors?

    62. What is wrapper class?

    63. What are the different access specifiers available in Java?

    64. What is the default access specifier in Java?

    65. What is a package in Java?

    66. Name some Java API Packages.

    67. Name some JavaDoc Comments.

    68. What is CommandLine Arguments.

    91

  • 7/28/2019 Java Lab.doc

    92/96

  • 7/28/2019 Java Lab.doc

    93/96

    92. Differentiate overloading and overriding.

    93. Define polymorphism.

    94. Differentiate static binding and dynamic binding.

    95. When will a class be declared as final?

    96. When will a method be declared final?

    97. What is an abstract class?

    98. What is the need for abstract classes?

    99. Explain about protected visibility control.

    100. What are the methods under "object" class / java.lang.Object.

    101. Explain toString method of object class.

    102. What is reflection?

    103. What are the uses of reflection in Java.

    104. How will you create an instance of Class.

    105. What are the methods under reflection used to analyze the capabilities of

    classes?

    106. How to create arrays dynamically using reflection package.

    107. Define an interface.

    108. What is the need for an interface?

    109. What are the properties of an interface?

    110. Differentiate Abstract classes and interface.

    111. What is object cloning?

    112. Differentiate cloning and copying.

    113. Differentiate shallow copy and deep copy in cloning.

    114. Does Inheritance removes any fields/or methods of super class?

    93

  • 7/28/2019 Java Lab.doc

    94/96

    115. Mention the use of final keyword.

    116. What is nested class? Mention its types.

    117. What is inner class?

    118. What is the need for inner classes?

    119. What are the rules for inner class?

    120. What is local inner class and anonymous inner class? Give their advantages.

    121. Write the advantages and disadvantages of static nested class.

    122. Define proxies.

    123. Write the application of proxies.

    124. What are the properties of proxy classes?

    125. Draw the inheritance hierarchy for the frame and component classes in AWT and

    Swing.

    126. What are the advantages of using swing over awt?

    127. How do achieve special fonts for your text? Give example.

    128. Give the syntax of drawImage() and copyArea() methods.

    129. What is Adapter class?

    130. Draw the AWT event Hierarchy.

    131. What are the swing components?

    132. What are the methods under Action Interface.

    133. What are the methods under WindowListener Interface.

    134. What is the difference between Swing and AWT?

    135. What is generic programming?

    136. What are Checked and UnChecked Exception?

    137. What are checked exceptions?

    94

  • 7/28/2019 Java Lab.doc

    95/96

    138. What are runtime exceptions?

    139. What is the difference between error and an exception?

    140. What classes of exceptions may be caught by a catch clause?.

    141. If I want an object of my class to be thrown as an exception object, what should I

    do?

    142. How to create custom exceptions?

    143. What are the different ways to handle exceptions?

    144. What is the purpose of the finally clause of a try-catch-finally statement?

    145. What is the basic difference between the 2 approaches to exception handling.Is it necessary that each try block must be followed by a catch block?

    146. How does Java handle integer overflows and underflows?

    147. Explain generic classes and methods.

    148. Explain exception hierarchy.

    149. What are the advantages of Generic Programming?

    150. Explain the different ways to handle exceptions.

    151. How Java handle overflows and underflows?

    152. Describe synchronization in respect to multithreading.

    153. Explain different way of using thread?

    154. What is synchronization and why is it important?

    155. When a thread is created and started, what is its initial state?

    156. What are synchronized methods and synchronized statements?

    157. What is daemon thread and which method is used to create the daemon thread?

    158. What method must be implemented by all threads?

    159. What kind of thread is the Garbage collector thread?

    95

  • 7/28/2019 Java Lab.doc

    96/96

    160. What is a daemon thread?

    161. What is a thread?

    162. What is the algorithm used in Thread scheduling?

    163. What are the different level lockings using the synchronization keyword?

    164. What are the ways in which you can instantiate a thread?

    165. What are the states of a thread?

    166. What are the threads will start, when you start the java program?

    167. What are the different identifier states of a Thread?

    168. Why do threads block on I/O?

    169. What is synchronization and why is it important?