Few simple questions on Java with solutions

Embed Size (px)

Citation preview

  • 7/30/2019 Few simple questions on Java with solutions

    1/21

  • 7/30/2019 Few simple questions on Java with solutions

    2/21

    1)What is Vector? How is it different from an array? Explain any5 Methods of Vector.

    Ans: Vector in Java is a dynamic array which can hold anynumber of objects of any type. The objects dont have to behomogeneous. Arrays can be easily implemented as vectors.

    Vectors can be declared in 2 ways:

    import java.util.Vector; // importing vector class

    Vector v = new Vector(); // vector with no initial size

    Vector v = new Vector(size); // initial size declared

    // v is of type Vector, size is of type int

    Thus, the initial size of a Vector may/may not be specified. Thedifferences between vectors and arrays are as follows:

    i) It is not compulsory to specify the initial size of a vector(compulsory for array).

    ii) Vectors store data in the form of objects, which means thatsimple data types have to be converted into objects if

    needed. This conversion is not required in arrays.

    iii) Vectors are more convenient to use than arrays.iv) Vectors are dynamic in size, while arrays are not.v) We can add/remove any element of a vector at any time.

    This cant be done in an array.

    Some of the methods of the Vector class are:

    i) addElement(item) - Adds the item specified as the lastelement of the vector

    ii) elementAt(n) Returns the name of the nth objectiii) insertElementat(item,n) Inserts the item at nth positioniv) removeElement(item) Removes the specified item from

    the list

  • 7/30/2019 Few simple questions on Java with solutions

    3/21

    v) size( ) - Returns the number of objects present in thelist

    EXAMPLE

    import java.util.Vector;

    class C

    {

    public static void main(String args[]){

    Vector v = new Vector();

    int length = args.length;int i;

    for(i=0; i

  • 7/30/2019 Few simple questions on Java with solutions

    4/21

    The syntax for dynamically declaring a string is:String s = new String(asd); // string s stores value asd

    We can create an array of strings by using the syntax:String s[] = new String[size];

    The String class has many methods to help in string manipulation.Some of them are:

    i) toLowerCase( ) Converts the string to all lowercaseii) toUpperCase( ) Converts the string to all uppercaseiii) length( ) Returns the length of the stringiv) substring(n) Gives substring starting from the nth characterv) replace(x, y) Replaces all appearances ofx withyEXAMPLE

    class StringMethods

    {public static void main(String args[])

    {

    String s = new String("String Demo);

    System.out.println(s.toLowerCase());

    System.out.println(s.toUpperCase());System.out.println(+s.length());

    System.out.println(s.substring(7));System.out.println(s.replace( i,o));

    }

    }

    /*

    OUTPUT:string demo

    STRING DEMO

    11DemoStrong Demo

    */

  • 7/30/2019 Few simple questions on Java with solutions

    5/21

    3) Explain Java Exception Handling with suitable examples.Ans: An exception is a condition that is caused by a run - timeerror in the program. When the Java interpreter encounters an

    error such as dividing by zero, it creates an exception objectand throws it, thereby managing the run time error. Javaexceptions can be built-in or user-defined. Some of the built-inexceptions are:

    ArithmeticException ArrayIndexOutOfBoundsException ClassNotFoundException FileNotFoundException IOException

    Handling such exceptions involves the usage of 5 keywords,namely: try to check the exception - condition catch to take action on encountering exception(s) throw to throw a custom exception throws to prepare a class for handling exceptions finally to handle an exception which was tried but not

    caught

    Example:import java.lang.Exception;import java.io.*;

    class A extends Exception

    {

    A(String message){

    super(message);

    }}

    class B{

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

    {BufferedReader a = new BufferedReader(new InputStreamReader(System.in));

    int x = Integer.parseInt(a.readLine( ));

  • 7/30/2019 Few simple questions on Java with solutions

    6/21

    try

    {if(x

  • 7/30/2019 Few simple questions on Java with solutions

    7/21

    the exceptions that the method might throw. If more thanone exception is on the list, we can use commas to separatethem. Example:

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

    iii) Thefinally keyword is used to handle an exception that isgenerated in a try block, but is not caught by catchstatements. This block should be added after the try block orafter the last catch block. Thefinally block alwaysexecutes, whether or not an exception has occured. Thus, ithelps in handling operations like closing files, releasingsystem resources, etc. Example:

    finally { System.out.println(Finally always executes!); }

    Sample Program:import java.lang.Exception;

    import java.io.*;

    class A extends Exception

    {

    A(String message){

    super(message);}}

    class B

    {

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

    {BufferedReader a = new BufferedReader(new InputStreamReader(System.in));

    int x = Integer.parseInt(a.readLine( ));

    try

    {

    if(x

  • 7/30/2019 Few simple questions on Java with solutions

    8/21

    {

    System.out.println(Exception caught!);System.out.println(obj.getMessage( ));

    }

    finally{ System.out.println(This is final); }

    } // end of main()

    } // end of class

    /*

    OUTPUT:

    -1

    Exception caught!Number less than zero!

    This is final*/

    5) What is an interface? Explain with a suitable example.

    Ans:An interface is a collection of abstract methods. It has methods andvariables, similar to class. But unlike class, an interface defines only

    abstract methods and final fields. This means that interfaces do notspecify any code to implement these methods, and data fieldscontain only constants. Hence, it is the responsibility of the classwhich implements an interface, to define the code forimplementation of these methods. The syntax for declaring aninterface is:

    interface I

    {

    static final type var_name = value;

    return_type method_name(parameter_list);

    }

    Interface supports all types of inheritance, especially MultipleInheritance. It can beextended by another interface, or can beimplemented by a class.

  • 7/30/2019 Few simple questions on Java with solutions

    9/21

    Sample Program:interface area

    {

    final static float pi = 3.14f;float compute(float x, float y);

    }

    class rectangle implements area

    {

    public float compute(float x, float y){ return(x*y); }

    }

    class circle implements area

    {public float compute(float x, float y){ return(pi*x*x); }

    }

    class C

    {

    public static void main(String args[])

    {rectangle r = new rectangle();

    circle c = new circle();

    area a;area = r;

    System.out.println(Area of rectangle = +a.compute(10,15));

    area=c;System.out.println(Area of circle = +a.compute(10,0);

    }

    }

    /*OUTPUT:

    Area of rectangle = 150

    Area of circle = 314*/

  • 7/30/2019 Few simple questions on Java with solutions

    10/21

    6)Describe (i)Function over-riding (ii) Abstract methods andclasses

    Ans:i)

    Method over-riding is a feature of OOP by which the methodof a sub-class shows an added/changed behaviour in thesuper-class. i.e., an object of the sub-class responds to thesame method, but has a different behavior when thatmethod is called. The rules to be followed while over-ridinga method of the parent-class with the child-class are:

    The return type, method name, and parameter list must beidentical.

    The access specifier must be at least that of the parent. Forexample, if the parent method is public, the child must bepublic. If the parent method is protected, the child must beprotected or public.

    The overriding exception should not throw more exceptionsthan the parent.

    Example:class parent

    {int p;

    parent(int p)

    { this.p=p; }void display( )

    { System.out.println(Parent p = +p); }

    }

    class child extends parent

    {int c;

    child(int p, int c){parent(p);

    this.c=c;

    }

    void display( ){

    System.out.println(Parent p = +p);

  • 7/30/2019 Few simple questions on Java with solutions

    11/21

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

    }}

    class override

    {

    public static void main(String args[ ]){

    child one = new child(5,10);one.display( );

    }

    }

    /*

    OUTPUT:parent p = 5

    child c = 10

    */

    In the above example, the display( ) method invokedbelongs to the child class, since the display( ) of the parentclass is over-ridden.

    ii) In Java, we can indicate that a method must always beredefined in a subclass, thus making over-ridingcompulsory. This is done using the abstract keyword in the

    method definition. Example:

    abstract class shape

    {

    abstract void draw();

    }

    When a class contains one or more abstract methods, itshould also be declaredabstract. The rules to be followedwhile using an abstract class are:

    We cannot use abstract classes to instantiate objectsdirectly.

  • 7/30/2019 Few simple questions on Java with solutions

    12/21

    The abstract methods of an abstract class must bedefined in its subclass.

    We cannot declare abstract constructors or abstractstatic methods.

    7)Explain the uses ofsuper keyword.Ans: Every object has a reference to itself called the thisreference, and there are situations where a class needs toexplicitly use thethis reference when referring to its fields ormethods. Similarly, a class can use the super keyword toexplicitly refer to a field or method that is inherited from aparent. The keywordsuper is hence a child objects referenceto its parent object, and thus, whenever a sub-class needs torefer to its immediate super-class, it can do so by usingsuperkeyword. Thesuper keyword has 2 uses:

    To call a constructor of the super-class. The syntax is:super(parameter-list);Here, parameter-list specifies the parameters needed by theconstructor in the super-class. super( ) must always be the first

    statement executed inside a subclass constructor.

    To access a member of the super-class that has been hidden bya member of the sub-class. The syntax for this is:super.memberHere, member can refer to a method or an instance-variable.

    Example for calling constructor:

    class box{

    private double length, breadth, height;

    box(box b)

    { height = b.height; length = b.length; }

    box(double l, double b, double h)

  • 7/30/2019 Few simple questions on Java with solutions

    13/21

    { length = l; breadth = b; height = h; }

    box( )

    { length = -1; breadth = -1; }

    box(double side){ length = breadth = height = side; }

    double volume( )

    { return length*breadth*height; }

    }

    class boxweight extends box

    {double weight;

    boxweight(boxweight b){ weight = b.weight; }

    boxweight(double l, double b, double h, double m){ super(l,b,h); weight = m; }

    boxweight( )

    { super( ); weight = -1; }

    class C

    {public static void main(String args[])

    {

    boxweight one = new boxweight(1.0,2.0,3.0,4.0);boxweight two = new boxweight( );

    double vol;

    vol=one.volume();System.out.println(+vol);

    System.out.println(+one.weight);

    vol=two.volume();

    System.out.println(+vol);

    System.out.println(+two.weight);}

    }

  • 7/30/2019 Few simple questions on Java with solutions

    14/21

    /*

    OUTPUT:6.0

    4.0

    -1.0

    -1.0*/

    Example for calling super class:

    class A

    {

    int i;}

    class B extends A

    {int i;

    B(int a, int b)

    { super.i = a; i = b; }

    void show()

    {

    System.out.println(I in superclass: +super.i);

    System.out.println(in subclass: +i);} // end of show( )

    } // end of class B

    class C

    {

    public static void main(String args[ ]){

    B b = new B( );

    b.show( );

    } //end of main( )} // end of class C

    /*OUTPUT:

    i in superclass: 1

    in subclass: 2*/

  • 7/30/2019 Few simple questions on Java with solutions

    15/21

    8)Explain life-cycle of a thread.Ans:The lifecycle of a thread involves the following states:i) Newborn stateii) Runnable stateiii) Running stateiv) Blocked statev) Dead stateA thread is always in one of these states. It can move from onestate to another via a variety of ways as shown:

    i) Newborn state When we create a thread object, the threadis born and is said to be in this state. The thread is not yetscheduled for running, and only the following things can bedone to it:o Schedule it for running using the start() methodo Kill it using the stop() methodIf we try using any other method at this stage, an exceptionwill be thrown.

    ii) Runnable state Here, the thread is ready for execution andis waiting for the availability of the processor. If all threadshave equal priority, then they are given time slots forexecution in first come, first serve manner. If we want athread to transfers control to another thread of equalpriority before its turn comes, we can do so by using the

    yield() method.

  • 7/30/2019 Few simple questions on Java with solutions

    16/21

    iii) Running state Here, the processor has given its time to thethread for execution. The thread runs until it relinquishescontrol on its own or is replaced by a higher priority thread.Such a thread transfers its control when:

    o It has been suspended using suspend() thread. This canbe revived using resume() thread at a later time.

    o It has been made to sleep using sleep(time) method. Thethread will re-enter the runnable state as soon as thistime period elapses.

    o It has been told to wait using wait() method. This can bemade to run again using notify() method.

    iv) Blocked state Here, the thread is prevented from enteringthe runnable and running states. This happens when thethread is suspended, sleeping or waiting.

    v) Dead state A running thread naturally completes its lifewhen it has completed executing its run() method. It canalso be killed by using the stop() method on it at any state.

    9)Explain life cycle of an Applet.Ans: Every Java applet inherits a set of default behaviours from

    the Applet class. As a result, when an applet is loaded, it undergoes aseries of changes in its state as shown:

  • 7/30/2019 Few simple questions on Java with solutions

    17/21

    The applet states include:

    i) Born or Initialization state An applet enters this statewhen it is first loaded by calling the init() method of Appletclass. At this stage, the following things can be done to it:o Create objects needed by the appleto Set up initial valueso Load images or fontso Set up coloursInitialization is done only once in the life cycle of anapplet.

    ii) Running state An applet enters this state when the systemcalls the start() method of Applet class, automatically after

    initialization, or manually when in idle state. Unlike theinit() method, the start() method can be called any numberof times.

    iii) Idle state An applet enters this stage when it stops running,automatically when we leave the page containing theapplet, or manually when we call the stop() method. If we

  • 7/30/2019 Few simple questions on Java with solutions

    18/21

    use a thread to run an applet, we MUST use stop() method toterminate the thread.

    iv) Dead or Destroyed state An applet enters this stage when itis removed from memory, automatically by invoking thedestroy() method, or manually when we quit the browser.Like init(), the destroy() method can be called only once inthe life-cycle of an applet.

    10) Write codes to draw the following applets:i) Smiley:

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

    /*

    */

    public class smiley extends Applet

    {

    public void paint(Graphics g){

    g.drawOval(0,0,200,200);

    g.drawOval(40,40,50,50);g.drawOval(120,40,50,50);

  • 7/30/2019 Few simple questions on Java with solutions

    19/21

    g.fillOval(52,65,25,25);

    g.fillOval(132,65,25,25);g.drawLine(100,75,100,125);

    g.drawArc(30,30,140,140,225,90);

    }

    }

    ii) House:

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

    /*

    */

    public class house extends Applet

    {

    public void paint(Graphics g){

    g.drawRect(100,100,400,200);

    g.drawLine(200,100,200,300);g.drawLine(100,100,150,50);

    g.drawLine(150,50,200,100);

    g.drawLine(450,50,500,100);

    g.drawLine(150,50,450,50);g.drawRect(325,200,50,100);

    }

    }

  • 7/30/2019 Few simple questions on Java with solutions

    20/21

    iii) 6 point star:

    import java.awt.*;

    import java.applet.*;/*

    */

    public class star extends Applet{

    public void paint(Graphics g)

    {g.drawLine(200,100,500,100);

    g.drawLine(500,100,350,260);

    g.drawLine(350,260,200,100);

    g.drawLine(200,225,500,225);g.drawLine(500,225,350,65);

    g.drawLine(350,65,200,225);

    }}

  • 7/30/2019 Few simple questions on Java with solutions

    21/21

    iv) RAIT:

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

    /*

    */

    public class rait extends Applet

    {

    public void paint(Graphics g){

    g.drawLine(10,10,10,50);

    g.drawRect(10,10,20,20);g.drawLine(10,30,30,50);g.drawLine(49,10,40,50);

    g.drawLine(49,10,60,50);

    g.drawLine(70,10,90,10);g.drawLine(70,50,90,50);

    g.drawLine(80,10,80,50);

    g.drawLine(100,10,120,10);g.drawLine(110,10,110,50);

    g.drawLine(45,30,53,30);

    }}

    DDDooonnneee BBByyy:::

    JJJaaannnggg BBBooogggooo