Вы находитесь на странице: 1из 21

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

Ans: Vector in Java is a dynamic array which can hold any number of objects of any type. The objects dont have to be homogeneous. 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. The differences between vectors and arrays are as follows: i) ii) It is not compulsory to specify the initial size of a vector (compulsory for array). Vectors store data in the form of objects, which means that simple data types have to be converted into objects if needed. This conversion is not required in arrays. iii) iv) v) Vectors are more convenient to use than arrays. Vectors are dynamic in size, while arrays are not. 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) ii) iii) iv)

addElement(item) - Adds the item specified as the last


element of the vector elementAt(n) Returns the name of the nth object

insertElementat(item,n) Inserts the item at nth position removeElement(item) Removes the specified item from
the list

v)
EXAMPLE

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


list

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<length; i++) v.addElement(args[i]); v.insertElementAt("asd",1); int n = v.size(); String S[] = new String[n]; v.copyInto(S); System.out.println("Vector elements: "); for(i=0; i<n; i++) System.out.println(S[i]); } } /* OUTPUT: java C qwe zxc Vector elements: qwe asd zxc */

2) Explain String class in Java and give any 5 methods in brief. Ans: A string is a sequence of characters. Strings are not primitive data types in Java, and therefore need to be represented by a class. In Java, strings are implemented by using 2 classes, namely String and StringBuffer. Java string is an object of the String class. It is not a character array, and is not terminated by the NULL character.

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)

ii) iii) iv) v)

toLowerCase( ) Converts the string to all lowercase toUpperCase( ) Converts the string to all uppercase length( ) Returns the length of the string substring(n) Gives substring starting from the nth character replace(x, y) Replaces all appearances of x with y

EXAMPLE 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 11 Demo Strong Demo */

3) Explain Java Exception Handling with suitable examples. Ans: An exception is a condition that is caused by a run - time error in the program. When the Java interpreter encounters an error such as dividing by zero, it creates an exception object and throws it, thereby managing the run time error. Java exceptions can be built-in or user-defined. Some of the built-in exceptions 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( ));

try { if(x<0) throw new A(Number less than zero!); } catch(A obj) { 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 */ 4) Explain keywords throw, throws, finally. Ans: i) The throw keyword is used for exception handling in Java to throw custom exceptions. A throw statement causes the current method to immediately stop executing, much like a return statement, and the exception is thrown to the previous method on the call stack. The throw statement has the following basic format: throw new exception_class(); Here, exception_class can refer to the Exception class itself, or a class that extends Exception.

ii)

The throws keyword is used to make a class expect and prepare to handle exceptions. The throws clause simply lists

the exceptions that the method might throw. If more than one exception is on the list, we can use commas to separate them. Example: public static void main(String args[]) throws IOException, FileNotFoundException

iii)

The finally keyword is used to handle an exception that is generated in a try block, but is not caught by catch statements. This block should be added after the try block or after the last catch block. The finally block always executes, whether or not an exception has occured. Thus, it helps in handling operations like closing files, releasing system 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<0) throw new A(Number less than zero!); } catch(A obj)

{ 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 and variables, similar to class. But unlike class, an interface defines only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods, and data fields contain only constants. Hence, it is the responsibility of the class which implements an interface, to define the code for implementation of these methods. The syntax for declaring an interface is:

interface I { static final type var_name = value; return_type method_name(parameter_list); }


Interface supports all types of inheritance, especially Multiple Inheritance. It can be extended by another interface, or can be implemented by a class.

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 */

6) Describe (i)Function over-riding (ii) Abstract methods and classes Ans: i) Method over-riding is a feature of OOP by which the method of a sub-class shows an added/changed behaviour in the super-class. i.e., an object of the sub-class responds to the same method, but has a different behavior when that method is called. The rules to be followed while over-riding a method of the parent-class with the child-class are: The return type, method name, and parameter list must be identical. The access specifier must be at least that of the parent. For example, if the parent method is public, the child must be public. If the parent method is protected, the child must be protected or public. The overriding exception should not throw more exceptions than 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);

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 invoked belongs to the child class, since the display( ) of the parent class is over-ridden. ii) In Java, we can indicate that a method must always be redefined in a subclass, thus making over-riding compulsory. 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, it should also be declared abstract. The rules to be followed while using an abstract class are: We cannot use abstract classes to instantiate objects directly.

The abstract methods of an abstract class must be defined in its subclass. We cannot declare abstract constructors or abstract static methods.

7) Explain the uses of super keyword. Ans: Every object has a reference to itself called the this reference, and there are situations where a class needs to explicitly use the this reference when referring to its fields or methods. Similarly, a class can use the super keyword to explicitly refer to a field or method that is inherited from a parent. The keyword super is hence a child objects reference to its parent object, and thus, whenever a sub-class needs to refer to its immediate super-class, it can do so by using super keyword. The super 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 the constructor 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 by a member of the sub-class. The syntax for this is:

super.member
Here, 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)

{ 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); } }

/* 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 */

8) Explain life-cycle of a thread. Ans: The lifecycle of a thread involves the following states: i) Newborn state ii) Runnable state iii) Running state iv) Blocked state v) Dead state A thread is always in one of these states. It can move from one state to another via a variety of ways as shown:

i)

Newborn state When we create a thread object, the thread is born and is said to be in this state. The thread is not yet scheduled for running, and only the following things can be done to it: o Schedule it for running using the start() method o Kill it using the stop() method If we try using any other method at this stage, an exception will be thrown. Runnable state Here, the thread is ready for execution and is waiting for the availability of the processor. If all threads have equal priority, then they are given time slots for execution in first come, first serve manner. If we want a thread to transfers control to another thread of equal priority before its turn comes, we can do so by using the yield() method.

ii)

iii)

Running state Here, the processor has given its time to the thread for execution. The thread runs until it relinquishes control 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 can be revived using resume() thread at a later time. o It has been made to sleep using sleep(time) method. The thread will re-enter the runnable state as soon as this time period elapses. o It has been told to wait using wait() method. This can be made to run again using notify() method.

iv)

Blocked state Here, the thread is prevented from entering the runnable and running states. This happens when the thread is suspended, sleeping or waiting. Dead state A running thread naturally completes its life when it has completed executing its run() method. It can also be killed by using the stop() method on it at any state.

v)

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 a series of changes in its state as shown:

The applet states include: i) Born or Initialization state An applet enters this state when it is first loaded by calling the init() method of Applet class. At this stage, the following things can be done to it: o Create objects needed by the applet o Set up initial values o Load images or fonts o Set up colours Initialization is done only once in the life cycle of an applet. Running state An applet enters this state when the system calls the start() method of Applet class, automatically after initialization, or manually when in idle state. Unlike the init() method, the start() method can be called any number of times. Idle state An applet enters this stage when it stops running, automatically when we leave the page containing the applet, or manually when we call the stop() method. If we

ii)

iii)

use a thread to run an applet, we MUST use stop() method to terminate the thread. iv) Dead or Destroyed state An applet enters this stage when it is removed from memory, automatically by invoking the destroy() method, or manually when we quit the browser. Like init(), the destroy() method can be called only once in the life-cycle of an applet.

10) i)

Write codes to draw the following applets: Smiley:

import java.awt.*; import java.applet.*; /*<applet code=smiley.class height=200 width=400> </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);

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.*; /*<applet code=house.class> </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); } }

iii)

6 point star:

import java.awt.*; import java.applet.*; /*<applet code=star.class> </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); } }

iv)

RAIT:

import java.awt.*; import java.applet.*; /*<applet code=rait.class height=200 width=400> </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); } }

D Do on ne eB By y::

J Ja an ng gB Bo og go o

Вам также может понравиться