practical 21

Upload: surmeet88

Post on 08-Apr-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Practical 21

    1/36

    6. Write a program to find an integer between 1 and 100, which has largest number ofdivisors. It should also print number of divisors. In case there are more than one such

    integers, program need to print any one.class Divisors

    {

    public static void main(String args[])

    {int maxd=0,maxc=0,oc;

    for(int i=2;i

  • 8/7/2019 Practical 21

    2/36

    7. Define an interface with two methods:-

    a. void push(int item);b. int pop();define two classes which implement this interface:-

    (i) Static stack with fixed size.(ii) Dynamic stack whose size can be extended dynamically.

    Ans:

    interface IntStack

    {

    int pop();

    void push(int item);

    }

    class FixedStack implements IntStack

    {private int stck[];

    private int tos;

    FixedStack(int size)

    {stck=new int[size];

    tos=-1;}

    public void push(int item){

    if(tos==stck.length-1)

    {System.out.println("Stack is full");

    }

    else

    {

    stck[++tos]=item;

    }

    }

    public int pop()

    {

    if(tos

  • 8/7/2019 Practical 21

    3/36

    }class DynStack implements IntStack

    {private int stck[];

    private int tos;

    DynStack(int size){

    stck=new int[size];

    tos=-1;

    }

    public void push(int item)

    {

    if(tos==stck.length-1)

    {

    int temp[]=new int[stck.length * 2];

    for(int i=0;i

  • 8/7/2019 Practical 21

    4/36

    {f1.push(i);

    d1.push(i+2);}

    System.out.println("Fixed stack");

    for(i=0;i

  • 8/7/2019 Practical 21

    5/36

    8. Write a program to create an applet, which displays a square of dimension 10 at the position where

    a mouse click occurs.

    Ans.

    import java.applet.*;

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

    /*

    */

    public class SquareMouse extends Applet{

    int mouseX=0,mouseY=0,d=0;public void init()

    {addMouseListener(new MouseAdapter()

    {

    public void mouseClicked(MouseEvent me)

    {

    mouseX=me.getX();

    mouseY=me.getY();

    d=10;

    repaint();

    }

    });}

    public void paint(Graphics g){

    g.drawRect(mouseX,mouseY,d,d);}

    }

  • 8/7/2019 Practical 21

    6/36

    OUTPUT

  • 8/7/2019 Practical 21

    7/36

    9. Define a class Employee. Write a program to serialize the objects of class Employee.

    Ans.

    import java.io.*;

    public class SerializationTask{

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

    try {System.out.println("\nSerializing\n");

    Employee emp_ser1=new Employee(12311,"John",20000);

    Employee emp_ser2=new Employee(13011,"Ram",25000);

    System.out.println("Emp1 "+emp_ser1);System.out.println("Emp2 "+emp_ser2);

    FileOutputStream fos= new FileOutputStream("emprec");

    ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(emp_ser1);oos.writeObject(emp_ser2);

    oos.flush();oos.close();

    }

    catch(Exception e)

    { System.out.println("Exception during serialization");

    System.exit(0);

    }

    try

    {

    System.out.println("\nDeserializing\n");Employee emp_dser1,emp_dser2;

    FileInputStream fis= new FileInputStream("emprec");

    ObjectInputStream ois=new ObjectInputStream(fis);

    emp_dser1=(Employee)ois.readObject();

    emp_dser2=(Employee)ois.readObject();ois.close();

    System.out.println("Emp1 "+emp_dser1);System.out.println("Emp2 "+emp_dser2);

    }catch(Exception e)

    {

    System.out.println("Exception during deserialization");System.exit(0);

    }

    }

    }

    class Employee implements Serializable

    {

    String s;

    int i;

  • 8/7/2019 Practical 21

    8/36

    double d;

    public Employee(int i,String s,double d){

    this.i=i;

    this.s=s;

    this.d=d;}

    public String toString()

    {

    return "i=" + i +"; s="+s+"; d="+d;

    }

    }

    OUTPUT

  • 8/7/2019 Practical 21

    9/36

    10. Write to implement word count utility, which should display the count of characters, words and

    lines. Input can be a disk file or data read from console.

    Ans.

    import java.io.*;

    class lnrdemo3

    {public static long numChar = 0;public static long numLine = 0;

    public static long numWords = 0;private static long wordcount(String line)

    {

    long numWords1 = 0;

    int index = 0;boolean prevWhiteSpace = true;

    while(index < line.length())

    {

    char c = line.charAt(index++);boolean currWhiteSpace = Character.isWhitespace(c);

    if(prevWhiteSpace && !currWhiteSpace){

    numWords1++;

    }

    prevWhiteSpace = currWhiteSpace;}

    return numWords1;}

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

    {

    int ch;String choice;

    BufferedReader in = new BufferedReader(newInputStreamReader(System.in));

    System.out.print("Enter 1: to Read from file or 2 from

    console: ");

    choice = in.readLine();ch = Integer.parseInt(choice);

    System.out.println();switch (ch)

    {case 1: System.out.print(" pass the file name: ");

    BufferedReader ini = new BufferedReader(new

    InputStreamReader(System.in));String str = ini.readLine();File file = new File(str);

    FileReader f = new FileReader(file);BufferedReader brObj = new BufferedReader(f);

    String line;

    try{

    while ((line = brObj.readLine()) != null)

  • 8/7/2019 Practical 21

    10/36

    {

    numChar += line.length();numWords += wordcount(line);

    numLine++;}

    System.out.println();System.out.println("File Name: " + str);

    brObj.close();

    }catch (Exception e){

    brObj.close();System.out.println(e);

    }

    break;

    case 2: BufferedReader inc = new BufferedReader(newInputStreamReader(System.in));

    String line1;

    System.out.println("pass the Paragragh to read");

    System.out.println("enter Q/q when input is over");

    try{

    do

    {

    line1=inc.readLine();numChar += line1.length();

    numWords += wordcount(line1);numLine++;

    }

    while (!line1.toLowerCase().equals("q"));

    numChar--;numWords--;

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

    }

    catch (Exception e)

    {System.out.println(e);

    }break;

    default:System.out.print("Entered wrong choice");}

    System.out.println("Number of characters: " + numChar);

    System.out.println("Number of words: " + numWords);System.out.println("Number of Lines: " + numLine);

    }

    }

  • 8/7/2019 Practical 21

    11/36

    The Output is:

  • 8/7/2019 Practical 21

    12/36

    11. Write a program to create two packages p1 and p2.

    Define three classes in p1:

    i. P1oneinstance variables of type int: a (no access modifier), b (private), c (protected), d (public)

    ii. P1two (subclass of P1one)iii. P1three (not a subclass of P1one)

    Define two classes in p2:

    i. P2one (subclass of P1one)ii. P2two (not a subclass of P1one)

    Demonstrate the access of four instance variables a, b, c, d of the class P1one in all of these classes.

    Ans.

    package p1;

    public class P1one

    {

    int a=1;

    private int b=2;

    protected int c=3;

    public int d=4;

    public P1one()

    {

    System.out.println("P1one contructor");

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

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

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

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

    }

    }

    package p1;

    class P1two extends P1one

  • 8/7/2019 Practical 21

    13/36

    {

    P1two()

    {

    System.out.println("P1two constructor");

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

    //System.out.println("b= "+b);

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

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

    }

    }

    package p1;

    class P1three

    {

    P1three()

    {

    P1one p=new P1one();

    System.out.println("P1three constructor");

    System.out.println("a= "+p.a);

    //System.out.println("b= "+p.b);

    System.out.println("c= "+p.c);

    System.out.println("d= "+p.d);

    }

    }

    package p1;

    public class Accessor

    {

  • 8/7/2019 Practical 21

    14/36

    public static void main(String args[])

    {

    P1one ob1=new P1one();

    P1two ob2=new P1two();

    P1three ob3=new P1three();

    }

    }

    OUTPUT

    Program

    package p2;

    class P2one extends p1.P1one

    {

    P2one()

    {

    System.out.println("P2one constructor");

    //System.out.println("a= "+a);

    //System.out.println("b= "+b);

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

  • 8/7/2019 Practical 21

    15/36

  • 8/7/2019 Practical 21

    16/36

    12. WAP for implementing TCP Client-Server program.

    import java.io.*;

    import java.net.*;

    public class EchoServer {

    /** Our server-side rendezvous socket */

    protected ServerSocket sock;

    /** The port number to use by default */

    public final static int ECHOPORT = 8040;

    /** Flag to control debugging */

    protected boolean debug = true;

    /** main: construct and run */

    public static void main(String[] argv) {

    new EchoServer(ECHOPORT).handle();

    }

    /** Construct an EchoServer on the given port number */

    public EchoServer(int port) {

    try {

    sock = new ServerSocket(port);

    } catch (IOException e) {

    System.err.println("I/O error in setup");

    System.err.println(e);

    System.exit(1);

    }

    }

    /** This handles the connections */

    protected void handle( ) {

  • 8/7/2019 Practical 21

    17/36

    Socket ios = null;

    BufferedReader is = null;

    PrintWriter os = null;

    while (true) {

    try {

    ios = sock.accept( );

    System.err.println("Accepted from " +

    ios.getInetAddress().getHostName());

    is = new BufferedReader(

    new InputStreamReader(ios.getInputStream()));

    os = new PrintWriter(new OutputStreamWriter(

    ios.getOutputStream()),true);

    String echoLine;

    while ((echoLine=is.readLine())!=null) {

    System.err.println("Read " + echoLine);

    os.print(echoLine + "\r\n");

    os.flush();

    System.err.println("Wrote " + echoLine);

    }

    System.err.println("All done!");

    } catch (IOException e) {

    System.err.println(e);

    } finally {

    try {

    if (is != null)

    is.close( );

  • 8/7/2019 Practical 21

    18/36

    if (os != null)

    os.close( );

    if (ios != null)

    ios.close( );

    } catch (IOException e) {

    System.err.println("IO Error in close");

    }

    }

    }

    }}

    import java.io.*;import java.net.*;

    public class EchoClientOneLine {

    /** What we send across the net */

    String mesg = "Hello across the net";

    public static void main(String[] argv) {

    if (argv.length == 0)

    new EchoClientOneLine( ).converse("localhost");

    else

    new EchoClientOneLine( ).converse(argv[0]);

    }

    /** Hold one conversation across the net */

    protected void converse(String hostName) {

  • 8/7/2019 Practical 21

    19/36

    try {

    Socket sock = new Socket(hostName, 8040); // echo server.

    BufferedReader is = new BufferedReader(new

    InputStreamReader(sock.getInputStream( )));

    PrintWriter os = new PrintWriter(sock.getOutputStream( ), true);

    os.print(mesg + "\r\n");

    os.flush( );

    String reply = is.readLine( );

    System.out.println("Sent \"" + mesg + "\"");

    System.out.println("Got \"" + reply + "\"");

    } catch (IOException e) {

    System.err.println(e);

    }

    }

    }

    OUTPUT

  • 8/7/2019 Practical 21

    20/36

  • 8/7/2019 Practical 21

    21/36

    13. WAP for implementing UDP Client-Server program.

    UDP Sender

    import java.io.*;

    import java.net.*;

    /*** This class sends the specified text as a datagram to the

    * specified port of the specified host.

    **/

    public class UDPSend {

    public static final String usage =

    "Usage: java UDPSend ...\n" +

    " or: java UDPSend -f ";

    public static void main(String args[ ]) {

    try {// Check the number of arguments

    if (args.length < 3)throw new IllegalArgumentException("Wrong number of args");

    // Parse the argumentsString host = args[0];

    int port = Integer.parseInt(args[1]);

    // Figure out the message to send.

    byte[ ] message;

    String msg = args[2];

    for (int i = 3; i < args.length; i++) msg += " " + args[i];

    // Convert the message to bytes using UTF-8 encoding

    message = msg.getBytes("UTF-8");

    // Get the internet address of the specified host

    InetAddress address = InetAddress.getByName(host);

    // Initialize a datagram packet with data and address

    DatagramPacket packet = new DatagramPacket(message, message.length,

    address, port);

    // Create a datagram socket, send the packet through it, close it.DatagramSocket dsocket = new DatagramSocket( );

    dsocket.send(packet);dsocket.close( );

    }

    catch (Exception e) {System.err.println(e);System.err.println(usage);

    }

    }}

  • 8/7/2019 Practical 21

    22/36

    UDP Reciver

    import java.io.*;

    import java.net.*;

    /**

    * This program waits to receive datagrams sent to the specified port.

    * When it receives one, it displays the sending host and prints the

    * contents of the datagram as a string. Then it loops and waits again.

    **/

    public class UDPReceive {

    public static final String usage = "Usage: java UDPReceive ";

    public static void main(String args[ ]) {

    try {

    if (args.length != 1)throw new IllegalArgumentException("Wrong number of args");

    // Get the port from the command line

    int port = Integer.parseInt(args[0]);

    // Create a socket to listen on the port.DatagramSocket dsocket = new DatagramSocket(port);

    // Create a buffer to read datagrams into. If anyone sends us a

    // packet containing more than will fit into this buffer, the

    // excess will simply be discarded!

    byte[ ] buffer = new byte[2048];

    // Create a packet to receive data into the buffer

    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    // Now loop forever, waiting to receive packets and printing them.

    for(;;) {

    // Wait to receive a datagram

    dsocket.receive(packet);

    // Decode the bytes of the packet to characters, using the// UTF-8(UNICODE TRANSFORMATION FORMAT)

    //encoding, and then display those characters.

    String msg = new String(buffer, 0, packet.getLength( ),"UTF-8");System.out.println(packet.getAddress( ).getHostName( ) +": " + msg);

    // Reset the length of the packet before reusing it.

    packet.setLength(buffer.length);

    }

    }

  • 8/7/2019 Practical 21

    23/36

    catch (Exception e) {System.err.println(e);

    System.err.println(usage);}

    }

    }

    OUTPUT

  • 8/7/2019 Practical 21

    24/36

    14. Write a program to display a frame containing text area. It should be possible to format the text by

    choosing its font name, style and font size. Font names should be given in a list box, font styles incheck boxes and font size in a text field.

    import java.awt.*;

    import java.awt.event.*;

    class format extends Frame implements ItemListener

    {

    TextArea a1;

    TextField t1;

    List l1;

    Checkbox c1,c2;GraphicsEnvironment g;

    String f[];int i;

    Panel p1,p2,p3;Label font,style,size;

    format()

    {

    g=GraphicsEnvironment.getLocalGraphicsEnvironment();

    f=g.getAvailableFontFamilyNames();

    setBackground(Color.yellow);

    setSize(600,600);

    setTitle("Font Frame");

    l1=new List();

    font=new Label("FONT NAME");

    size=new Label("FONT SIZE");

    style=new Label("FONT STYLE");t1=new TextField(15);

    a1=new TextArea(2,15);c1 = new Checkbox("Italic");

    c2 = new Checkbox("Bold");for(i=0;i

  • 8/7/2019 Practical 21

    25/36

    font.setBounds(10,10,100,20);

    size.setBounds(270,10,100,20);

    style.setBounds(10,10,250,20);

    p1.setBounds(30,50,400,200);p2.setBounds(430,40,180,200);

    p3.setBounds(10,210,580,400);

    p1.add(l1);

    p1.add(font);

    p1.add(t1);

    p1.add(size);

    p2.add(style);

    p3.add(a1);

    p2.add(c1);p2.add(c2);

    add(p1);

    add(p2);add(p3);

    setVisible(true);l1.addItemListener(this);

    t1.addFocusListener(new focus(this));

    c1.addItemListener(this);

    c2.addItemListener(this);

    }

    public static void main(String args[])

    {

    format f=new format();

    }

    public void itemStateChanged(ItemEvent ie)

    {

    set();}

    public void set()

    {

    if(c2.getState() && !c1.getState())a1.setFont(newFont(f[l1.getSelectedIndex()],Font.BOLD,Integer.parseInt(t1.getText())));

    else

    if(!c2.getState() && c1.getState())

    a1.setFont(new

    Font(f[l1.getSelectedIndex()],Font.ITALIC,Integer.parseInt(t1.getText())));

    else

    if(c2.getState() && c1.getState())

  • 8/7/2019 Practical 21

    26/36

    a1.setFont(new Font (f[l1.getSelectedIndex()], Font.ITALIC |Font.BOLD,

    Integer.parseInt(t1.getText())));else

    a1.setFont(new

    Font(f[l1.getSelectedIndex()],Font.PLAIN,Integer.parseInt(t1.getText())));

    }}

    class focus extends FocusAdapter

    {

    format f1;

    public focus(format f)

    {

    f1=f;

    }

    public void focusLost(FocusEvent e){

    String s = f1.t1.getText();for(int i=0;i

  • 8/7/2019 Practical 21

    27/36

    OUTPUT

  • 8/7/2019 Practical 21

    28/36

    15. Define a class to check DateFormatException. Define another class Day whichencapsulates the features of day. This class should contain following methods:-

    void advance(int n) advances the date currently set by a specified number of days. Forexample, d.advance(100) changes d to a date 100 days later.

    import java.text.ParseException;

    import java.text.SimpleDateFormat;import java.util.Date;

    import java.io.*;

    import java.util.Calendar;

    // This program creates a custom exception type.

    class DATEFORMATEXCEPTION extends Exception

    {

    private int flag;

    DATEFORMATEXCEPTION (int flag)

    {

    this.flag = flag;

    }public String toString()

    {

    if (flag==1)return "Entered Day is Not Correct";

    else if (flag == 2)

    return "Entered month is Not Correct";

    else

    return "Entered year is Not Correct";

    }

    }

    class ValidationExp2

    {

    static void compute(int day, int month, int year)throws DATEFORMATEXCEPTION

    {

    if (year > 3010 || year < 1900)

    throw new DATEFORMATEXCEPTION(3);else if (month > 12 || month < 1)

    throw new DATEFORMATEXCEPTION(2);else if ((month == 4 || month == 6 || month == 9 || month == 11) && (day > 30

    || day < 1))

    throw new DATEFORMATEXCEPTION(1);else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||month == 10 || month == 12) && (day > 31 || day < 1))

    throw new DATEFORMATEXCEPTION(1);

    else if (month == 2)

    {

    if (((year % 4 != 0) && (year % 400 != 0 && year % 100 != 0)) &&

    (day > 28 || day < 1))

    throw new DATEFORMATEXCEPTION(1);

  • 8/7/2019 Practical 21

    29/36

    else if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0 &&year % 100 == 0)) && (day > 29 || day < 1))

    throw new DATEFORMATEXCEPTION(1);

    }

    }static void advance(Date date)throws IOException

    {

    String str1;

    BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));

    System.out.print("Enter number of days to increment: ");

    str1 = in.readLine();

    int day = Integer.parseInt(str1);

    Calendar cal = Calendar.getInstance();

    cal.setTime(date);

    cal.add(Calendar.DATE, day);

    date = cal.getTime();System.out.println("Date :- " + date);

    }

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

    {

    String pattern = "dd:MM:yy";

    String str, str1;

    SimpleDateFormat sdf = new SimpleDateFormat();

    BufferedReader in = new BufferedReader(new

    InputStreamReader(System.in));

    System.out.print("day: ");

    str1 = in.readLine();

    int day = Integer.parseInt(str1);

    str = str1;

    System.out.print("month: ");

    str1 = in.readLine();int month = Integer.parseInt(str1);

    str = str + ":" + str1;

    System.out.print("year: ");str1 = in.readLine();

    int year = Integer.parseInt(str1);

    str = str + ":" + str1;

    try

    {

    sdf.applyPattern(pattern);

  • 8/7/2019 Practical 21

    30/36

    compute(day, month, year);Date date = sdf.parse(str);

    System.out.println("Date :- " + date);advance(date);

    }catch (DATEFORMATEXCEPTION e)

    {

    System.out.println("Caught " + e);

    }

    catch (ParseException e)

    {

    System.out.println("Wrong date format");

    e.printStackTrace();

    }

    }

    }

    output

    C:\java>javac ValidationExp2.java

    C:\java>java ValidationExp2

    day: 23

    month: 3

    year: 2004

    Date :- Tue Mar 23 00:00:00 GMT+05:30 2004

    Enter number of days to increment: 100

    Date :- Thu Jul 01 00:00:00 GMT+05:30 2004

    C:\java>java ValidationExp2

    day: 31

    month: 2year: 2004

    Caught Entered Day is Not Correct

  • 8/7/2019 Practical 21

    31/36

    16. Define a class Result to describe the result of students. Create a subclass SportResults. Define an

    interface Display which includesfollowing methods:

    Display student personal detailsDisplay students' academic result

    Display students' sport result

    abstract class display

    {public abstract void personal(String s,int r,String a);public abstract void academic(int m1,int m2,int m3);

    public abstract void sportresult(String r);}

    abstract class result extends display

    {

    public void personal(String name,int roll,String adrs){

    System.out.println("Name "+name+"\nRoll no "+roll+"\nAddress "+adrs);

    }

    public void academic(int m10,int m12,int mg){

    System.out.println("10 Marks "+m10+"\n12 Marks "+m12+"\nGraduation Marks"+mg);

    }

    }

    class sportresult extends result{

    public void sportresult(String r){

    System.out.println("Result in footBall "+r);

    }

    }

    class test{

    public static void main(String a[]){

    sportresult o= new sportresult();

    o.personal("Sam",1,"Delhi");

    o.academic(78,80,83);o.sportresult("Winner");

    }}

    Output :Name Sam

    Roll no 1

    Address Delhi 10 Marks 7812 Marks 80Graduation Marks 83 Result in footBall Winner

  • 8/7/2019 Practical 21

    32/36

    17. Write a program which generates following types of exceptions. Demonstrate how theseexceptions are handled.

    ArithmeticExceotionArrayIndexOutOfBoundsException

    ArrayStoreException

    ClassCastException

    NegativeArraySizeExceptionNullPointerException

    NumberFormatException

    import java.io.*;

    class exception

    {

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

    {

    int ch=0;BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    System.out.print("");System.out.println(" Press 1 for Airthmetic Exception");

    System.out.println(" Press 2 for Arrary Index out of Bound Exception");System.out.println(" Press 3 for Array store Exception");

    System.out.println(" Press 4 for Class Cast exception");System.out.println(" Press 5 for Negative Array Size Exception");

    System.out.println(" Press 6 for Null Pointer Exception");

    System.out.println(" Press 7 for Number Format Exception");

    System.out.println("");

    while(ch!=8)

    {

    System.out.println("Enter your choice : ");

    ch=Integer.parseInt(br.readLine());

    switch(ch)

    {

    case 1:

    {

    try

    {int a=0;

    int b=56/a;}

    catch(ArithmeticException e)

    { System.out.println("Divide By zero: "+e);}

    break;

    }

    case 2:

    {

    try

  • 8/7/2019 Practical 21

    33/36

    {int a[]=new int[10];

    a[20]=4;}

    catch(ArrayIndexOutOfBoundsException a)

    {

    System.out.println("Array out of bound exception: "+a);}

    break;

    }

    case 3:

    {

    try

    {

    Object x[] = new String[3];

    x[0] = new Integer(0);}

    catch(ArrayStoreException a){

    System.out.println("Array store exception: "+a);}

    break;}

    case 4:

    {

    try

    {

    Object x = new Integer(0);

    System.out.println((String)x);

    }

    catch(ClassCastException c)

    {

    System.out.println("class cast exception "+c);

    }

    break;}

    case 5:

    {

    try{int arr[]=new int[-6];

    arr[-1]=6;

    }

    catch(NegativeArraySizeException n)

    {

    System.out.println("Negative Array Size Exception: "+n);

    }

  • 8/7/2019 Practical 21

    34/36

    break;}

    case 6:

    {

    try

    {throw new NullPointerException();

    }

    catch(NullPointerException n)

    {

    System.out.println("Null Pointer exception: "+n);

    }

    break;

    }

    case 7:{

    try{

    String s1 = "abc";int i = Integer.parseInt(s1);

    }catch(NumberFormatException n)

    {

    System.out.println("Number format exception: "+n);

    }

    break;

    }

    }

    }

    }

    }

  • 8/7/2019 Practical 21

    35/36

    The output is:D:\practicals\Java\Demo\Exception>javac exception.java

    D:\practicals\Java\Demo\Exception>java exceptionPress 1 for Airthmetic Exception

    Press 2 for Arrary Index out of Bound Exception

    Press 3 for Array store Exception

    Press 4 for Class Cast exceptionPress 5 for Negative Array Size Exception

    Press 6 for Null Pointer Exception

    Press 7 for Number Format Exception

    Enter your choice :

    1

    Divide By zero: java.lang.ArithmeticException: / by zero

    Enter your choice :

    2

    Array out of bound exception: java.lang.ArrayIndexOutOfBoundsException: 20Enter your choice :

    3Array store exception: java.lang.ArrayStoreException: java.lang.Integer

    Enter your choice :4

    class cast exception java.lang.ClassCastException: java.lang.Integer cannot be cast tojava.lang.String

    Enter your choice :

    5

    Negative Array Size Exception: java.lang.NegativeArraySizeException

    Enter your choice :

    6

    Null Pointer exception: java.lang.NullPointerException

    Enter your choice :

    7

    Number format exception: java.lang.NumberFormatException: For input string: "abc"

    Enter your choice :

    8

  • 8/7/2019 Practical 21

    36/36