You are on page 1of 51

unit 2:Derived Syntactical constructs in Java

1]What is difference between array and vectors? Explain any 2 methods of vector with example

Vector
class methods :

1 ) void addElement(Object obj)

Adds the specified component to the end of this vector, increasing its size by one.

2) int capacity()

Returns the current capacity of this vector.

3) void clear()

Removes all of the elements from this Vector.

4) boolean contains(Object elem)

Tests if the specified object is a component in this vector.

5) void copyInto(Object[] anArray)

Copies the components of this vector into the specified array.

6) Object elementAt(int index)

Returns the component at the specified index.

7) boolean equals(Object o)
Compares the specified Object with this Vector for equality.

8) int indexOf(Object elem)

Searches for the first occurence of the given argument, testing for equality using the equals
method.

9) void insertElementAt(Object obj, int index)

Inserts the specified object as a component in this vector at the specified index.

10) boolean removeElement(Object obj)

Removes the first (lowest-indexed) occurrence of the argument from this vector.

11) void removeElementAt(int index)

removeElementAt(int index)

12) int size()

Returns the number of components in this vector.

2] What is constructor? Demonstrate the use of parameterized constructor with suitable

example.

• A constructor is a special method which initializes an object immediately upon creation.

• It has the same name as class name in which it resides and it is syntactically similar to any
method.

• When a constructor is not defined, java executes a default constructor which initializes all
numeric members to zero and other types to null or spaces.

• Once defined, constructor is automatically called immediately after the object is created
before new operator completes.

• Constructors do not have return value, but they don‟t require „void‟ as implicit data type as
data type of class constructor is the class type itself.

Eg :

class Rect

int length, breadth;


Rect() //constructor

length=4;

breadth=5;

public static void main(String args[])

Rect r = new Rect();

System.out.println(“Area : ” +(r.length*r.breadth));

Output :

Area : 20

• Parameterized constructor :

When constructor method is defined with parameters inside it, different value sets can be
provided to different constructor with the same name.

Example:

class Rect

int length, breadth;

Rect(int l, int b) // parameterized constructor

length=l;

breadth=b;

public static void main(String args[])

{
Rect r = new Rect(4,5); // constructor with parameters

Rect r1 = new Rect(6,7);

System.out.println(“Area : ” +(r.length*r.breadth));

System.out.println(“Area : ” +(r1.length*r1.breadth));

Output :

Area : 20

Area : 42.

3] Explain use of following methods:

1) indexOf()

2) charAt()

3) substring()

4) replace()

1. indexOf():

int indexOf(int ch): Returns the index within this string of the first occurrence of the

specified character.

int indexOf(int ch, int fromIndex): Returns the index within this string of the first

occurrence of the specified character, starting the search at the specified index.

int indexOf(String str): Returns the index within this string of the first occurrence of the

specified substring.

int indexOf(String str, int fromIndex): Returns the index within this string of the first

occurrence of the specified substring, starting at the specified index.

2. charAt():

char charAt(int index): Returns the char value at the specified index.

3. substring():
String substring(int beginIndex): Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex): Returns a new string that is a substring of

this string. The substring begins at the specified beginIndex and extends to the character

at index endIndex - 1

4. replace():

String replace(char oldChar, char newChar): Returns a new string resulting from

replacing all occurrences of oldChar in this string with newChar.

4] What is garbage collection and finalize method in Java?

Garbage collection - The objects are dynamically allocated in java by the use of the

new operator. The objects which are no longer in use are to be destroyed and the

memory should be released for later reallocation. Java, unlike C++, handles

deallocation of memory automatically. This technique is called garbage collection.

When no references to an object exist, that object is assumed to be no longer needed,

and the memory occupied by the object can be reclaimed. Garbage collection occurs

sporadically during the execution of programs. It will not occur just because one or

more objects exist that are no longer used. Different run-time implementations will

take varying approaches to garbage collection.

finalize() method: -sometimes an object will need to perform some action when it is

destroyed. Eg. If an object holding some non java resources such as file handle or

window character font, then before the object is garbage collected these resources

should be freed. To handle such situations java provide a mechanism called

finalization. In finalization, specific actions that are to be done when an object is

garbage collected can be defined. To add finalizer to a class define the finalize()

method. The java run-time calls this method whenever it is about to recycle an object.
Inside the finalize() method, the actions that are to be performed before an object is to

be destroyed, can be defined. Before an object is freed, the java run-time calls the

finalize() method on the object. The general form of the finalize() method is:

protected void finalize()

//finalization code

5] Define a class ‘employee’ with data members empid, name and salary. Accept data for five
objects using Array of objects and print it.

import java.io.*;

class employee

int empid;

String name;

double salary;

void getdata()

BufferedReader obj = new BufferedReader (new InputStreamReader(System.in));

System.out.print("Enter Emp number : ");

empid=Integer.parseInt(obj.readLine());

System.out.print("Enter Emp Name : ");

name=obj.readLine();

System.out.print("Enter Emp Salary : ");

salary=Double.parseDouble(obj.readLine());
}

void show()

System.out.println("Emp ID : " + empid);

System.out.println(“Name : " + name);

System.out.println(“Salary : " + salary);

}}

classEmpDetails{

public static void main(String args[])

{employee e[] = new employee[5];

for(inti=0; i<5; i++){

e[i] = new employee();

e[i].getdata();

System.out.println(" Employee Details are : ");

for(inti=0; i<5; i++)

e[i].show();

}}

6] Define wrapper class. Give the following wrapper class methods with syntax and use:

1) To convert integer number to string.

2) To convert numeric string to integer number.

3) To convert object numbers to primitive numbers using typevalue() method


7] Differentiate vector and array with any 4 points

8] Write a program to accept a number as command line argument and print the number is
even or odd.

public class oe
{

public static void main(String key[])

int x=Integer.parseInt(key[0]);

if (x%2 ==0)

System.out.println("Even Number");

else

System.out.println("Odd Number");

}}}

9] Compare string class and StringBuffer class with any four points.

10] Explain following methods of vector class:

i. elementAt ()

ii. addElement ()

iii. removeElement ()

1) Object elementAt(int index)


Returns the component at the specified index.

2) void addElement(Object obj)

Adds the specified component to the end of this vector, increasing its size by one.

3) boolean removeElement(Object obj)

Removes the first (lowest-indexed) occurrence of the argument from this

11] Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10,

20). Remove element at 3rd and 4th position. Insert new element at 3rd position. Display

the original and current size of vector.

import java.util.*;

public class VectorDemo

public static void main(String args[])

Vector v = new Vector();

v.addElement(new Integer(10));

v.addElement(new Integer(20));

v.addElement(new Integer(30));

v.addElement(new Integer(40));

v.addElement(new Integer(10));

v.addElement(new Integer(20));

System.out println(v.size());// display original size

v.removeElementAt(2); // remove 3rd element

v.removeElementAt(3); // remove 4th element

v.insertElementAt(11,2) // new element inserted at 3rd position

System.out.println("Size of vector after insert delete operations: " +

v.size());
}}

12] What is constructor? Describe the use of parameterized constructor with suitable

example.

Constructor:

A constructor is a special method which initializes an object immediately upon

creation.

It has the same name as class name in which it resides and it is syntactically similar to

any method.

When a constructor is not defined, java executes a default constructor which

initializes all numeric members to zero and other types to null or spaces.

Once defined, constructor is automatically called immediately after the object is

created before new operator completes.

Constructors do not have return value, but they don‟t require “void” as implicit data

type as data type of class constructor is the class type itself.

Parameterized constructor:

It is used to pass the values while creating the objects

Example:

class Rect

int length, breadth;

Rect(int l, int b) // parameterized constructor

length=l;

breadth=b;

}
public static void main(String args[])

Rect r = new Rect(4,5); // constructor with parameters

Rect r1 = new Rect(6,7);

System.out.println(“Area : ” +(r.length*r.breadth));

System.out.println(“Area : ” +(r1.length*r1.breadth));

}}

13]What is difference between array and vector? Explain elementAt( ) and addElement( )
method

14]Describe the following string class methods with examples :

(i) length()

(ii) charAt()

(iii) CompareTo()
1. length():

Syntax: int length()

It is used to return length of given string in integer.

Eg. String str=”INDIA”

System.out.println(str);

System.out.println(str.length()); // Returns 5

2. charAt():

Syntax: char charAt(int position)

The charAt() will obtain a character from specified position .

Eg. String s=”INDIA”

System.out.println(s.charAt(2) ); // returns D

3. compareTo():

Syntax: int compareTo(Object o)

or

int compareTo(String anotherString)

There are two variants of this method. First method compares this String to another

Object and second method compares two strings lexicographically.

Eg. String str1 = "Strings are immutable";

String str2 = "Strings are immutable";

String str3 = "Integers are not immutable";

int result = str1.compareTo( str2 );

System.out.println(result);

result = str2.compareTo( str3 );

System.out.println(result);

15]Explain following methods of string class with their syntax and suitable example.

i) substring () ii) replace ()


i) substring()

Syntax:

String substring(intstartindex)

Startindex specifies the index at which the substring will begin. It will returns a copy of the

substring that begins at startindex and runs to the end of the invoking string

String substring(intstartindex,intendindex)

Here startindex specifies the beginning index,andendindex specifies the stopping point. The

string returned all the characters from the beginning index, upto, but not including ,the ending

index.

String Str = new String("Welcome");

System.out.println(Str.substring(3)); //come

System.out.println(Str.substring(3,5));//co

ii) replace()

This method returns a new string resulting from replacing all occurrences of oldChar in this

string with newChar.

Syntax: String replace(char original,char replacement)

S2=S1.replace(„x‟,‟y‟); - Replaces all appearance of „x‟ with „y‟.

Example:

String Str = new String("Welcome”);

System.out.println(Str.replace('o', 'T')); // WelcTme

16]Write a program to implement a vector class and its method for adding and removing

elements. After remove display remaining list.

import java.io.*;

import java.lang.*;

import java.util.*;

class vector2
{

public static void main(String args[])

vector v=new vector();

Integer s1=new Integer(1);

Integer s2=new Integer(2);

String s3=new String("fy");

String s4=new String("sy");

Character s5=new Character('a');

Character s6=new Character('b');

Float s7=new Float(1.1f);

Float s8=new Float(1.2f);

v.addElement(s1);

v.addElement(s2);

v.addElement(s3);

v.addElement(s4);

v.addElement(s5);

v.addElement(s6);

v.addElement(s7);

v.addElement(s8);

System.out.println(v);

v.removeElement(s2);

v.removeElementAt(4);

System.out.println(v);

}
17]Define constructor. Explain parameterized constructor with example

CONSTRUCTOR

A constructor is a special member which initializes an object immediately upon creation.

• It has the same name as class name in which it resides and it is syntactically similar to any

method.

• When a constructor is not defined, java executes a default constructor which initializes all

numeric members to zero and other types to null or spaces.

• Once defined, constructor is automatically called immediately after the object is created

before new operator completes.

Parameterized constructor: When constructor method is defined with parameters inside it,

different value sets can be provided to different constructor with the same name.

Example

ClassRect

int length, breadth;

Rect(int l, int b) // parameterized constructor

length=l;

breadth=b;

public static void main(String args[])

Rect r = new Rect(4,5); // constructor with parameters

Rect r1 = new Rect(6,7);

System.out.println(“Area : ” +(r.length*r.breadth)); // o/p Area : 20

System.out.println(“Area : ” +(r1.length*r1.breadth)); // o/p Area : 42

}
}

18]How garbage collection is done in Java? Which methods are used

for it?

 Garbage collection is a process in which the memory allocated to

objects, which are no longer in use can be freed for further use.

 Garbage collector runs either synchronously when system is out of

memory or asynchronously when system is idle.

 In Javalang.Object.finalize() is called by garbage collector on an

object when garbage collection determines that there are no more

reference to the object.

A subclass it is performed automatically. So it provides better memory

management.

Method used for Garbage Collection:

The java.override the finalize method to dispose of system

resources or to perform other cleanup.

General Form :

protected void finalize()

{ // finalization code here

19]What is the difference between vector and array? Give suitable

example
20]What are the access control parameters? Explain the concept

with suitable example.

Java provides a number of access modifiers to set access levels for

classes, variables, methods and constructors.

1) Default Access Modifier - No keyword:

A variable or method declared without any access control modifier is

available to any other class in the same package. Visible to all class in

its package.
E.g:

Variables and methods can be declared without any modifiers, as in

the following Examples:

String version = "1.5.1";

boolean processOrder()

return true;

2) Private Access Modifier - private:

Methods, Variables and Constructors that are declared private can

only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and

interfaces cannot be private.

Using the private modifier is the main way that an object

encapsulates itself and hide data from the outside world.

Examples:

private String format;

private void get() { }

3) Public Access Modifier - public:

A class, method, constructor, interface etc declared public can be

accessed from any other class. Therefore fields, methods, blocks

declared inside a public class can be accessed from any class

belonging to the Java Universe.

However if the public class we are trying to access is in a different

package, then the public class still need to be imported.

Because of class inheritance, all public methods and variables of a

class are inherited by its subclasses.


Examples:

public double pi = 3.14;

public static void main(String[] arguments)

// ...

4) Protected Access Modifier - protected:

Variables, methods and constructors which are declared protected in a

super class can be accessed only by the subclasses in other package or

any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and

interfaces. Methods, fields can be declared protected, however

methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method

or variable, while preventing a nonrelated class from trying to use it.

E.g

The following parent class uses protected access control, to allow its

child class override

protected void show( )

{}

5) private protected: Variables, methods which are declared

protected in a super class can be accessed only by the subclasses in

same package. It means visible to class and its subclasses.

Example:

private protected void show( )

{}
21]What is :

(i) AddElement() &

(ii) ElementAt() command in vector

(i) addElement() :

It is a method from Vector Class.

It is used to add an object at the end of the Vector.

Syntax :

addElement(Object);

Example :

If v is the Vector object ,

v.addElement(new Integer(10));

It will add Integer object with value 10 at the end of the Vector object

‘v’.

(ii) elementAt() command in vector:

It is a Vector class method.

It is used to access element or object from a specified position in a

vector.

Syntax :

elementAt(index);

Example :

If v is the Vector object ,

v.elementAt(3);

It will return element at position 3 from Vector object ‘v’

22]Write a program to add 2 integer, 2 string and 2 float objects to

a vector. Remove element specified by user and display the list.

importjava.util.*;
import java.io.*;

class Vect {

public static void main(String a[]) {

Vector<Object> v = new Vector<Object>();

v.addElement(new Integer(5));

v.addElement(new Integer(10));

v.addElement(new String("String 1"));

v.addElement(new String("String 2"));

v.addElement(new Float(5.0));

v.addElement(new Float(6.7));

int n=0;

BufferedReader b = new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Following are the elements in the vector");

for(int i = 0; i <v.size();i++) {

System.out.println("Element at "+i+ "is "+v.elementAt(i));

System.out.println("Enter the position of the element to be removed");

try {

n = Integer.parseInt(b.readLine());

} catch(Exception e) {

System.out.println("Exception caught!"+e);

System.out.println("The element at "+n +"is "+v.elementAt(n)+"

will be removed");

v.removeElementAt(n);

System.out.println("The following are the elements in the


vector");

for(int i = 0; i<v.size();i++) {

System.out.println(v.elementAt(i));

23]Explain the following methods of string class with syntax and

example:

(i) substring()

(ii)replace()

(Note: Any other example can be considered)

(i) substring():

Syntax:

String substring(intstartindex)

startindex specifies the index at which the substring will begin.It

will returns a copy of the substring that begins at startindex and

runs to the end of the invoking string

(OR)

String substring(intstartindex,intendindex)

Here startindex specifies the beginning index,andendindex specifies

the stopping point. The string returned all the characters from the

beginning index, upto, but not including,the ending index.

Example :

System.out.println(("Welcome”.substring(3)); //come

System.out.println(("Welcome”.substring(3,5));//co
(ii) replace():

This method returns a new string resulting from replacing all

occurrences of oldChar in this string with newChar.

Syntax: String replace(char oldChar, char newChar)

Example:

String Str = new String("Welcome”);

System.out.println(Str.replace('o', 'T')); // WelcTme

24]What is garbage collection in Java? Explain finalize method in

Java.

Garbage collection:

 Garbage collection is a process in which the memory allocated to

objects, which are no longer in use can be freed for further use.

 Garbage collector runs either synchronously when system is out

of memory or asynchronously when system is idle.

 In Java it is performed automatically. So it provides better

memory management.

 A garbage collector can be invoked explicitly by writing

statement

System.gc(); //will call garbage collector.

Example:

public class A

int p;

A()

{
p = 0;

class Test

public static void main(String args[])

A a1= new A();

A a2= new A();

a1=a2; // it deallocates the memory of object a1

Method used for Garbage Collection finalize:

 The java.lang.Object.finalize() is called by garbage collector on

an object when garbage collection determines that there are no

more reference to the object.

 A subclass override the finalize method to dispose of system

resources or to perform other cleanup.

 Inside the finalize() method, the actions that are to be performed

before an object is to be destroyed, can be defined. Before an

object is freed, the java run-time calls the finalize() method on

the object.

General Form :

protected void finalize()

{ // finalization code here

}
25]What is the use of ArrayList class? State any two methods with

their use from ArrayList.

Use of ArrayList class:

1. ArrayList supports dynamic arrays that can grow as needed.

2. ArrayList is a variable-length array of object references. That is,

an ArrayListcan dynamically increase or decrease in size. Array

lists are created with an initial size. When this size is exceeded, the

collection is automatically enlarged. When objects are removed, the

array may be shrunk.

Methods of ArrayList class :

1. void add(int index, Object element)

Inserts the specified element at the specified position index in

this list. Throws IndexOutOfBoundsException if the specified

index is is out of range (index < 0 || index >size()).

2.boolean add(Object o)

Appends the specified element to the end of this list.

booleanaddAll(Collection c)

Appends all of the elements in the specified collection to the end of

this list, in the order that they are returned by the specified

collection's iterator. Throws NullPointerException if the specified

collection is null.

3. booleanaddAll(int index, Collection c)

Inserts all of the elements in the specified collection into this list,

starting at the specified position. Throws NullPointerException if

the specified collection is null.

4. void clear()
Removes all of the elements from this list. 6. Object clone()

Returns a shallow copy of this ArrayList.

5. boolean contains(Object o)

Returns true if this list contains the specified element. More

formally, returns true if and only if this list contains at least one

element e such that (o==null ? e==null : o.equals(e)).

6. void ensureCapacity(intminCapacity)

Increases the capacity of this ArrayList instance, if necessary, to

ensure that it can hold at least the number of elements specified by

the minimum capacity argument.

7. Object get(int index)

Returns the element at the specified position in this list.

Throws IndexOutOfBoundsException if the specified index is is out

of range (index < 0 || index >= size()).

8. intindexOf(Object o)

Returns the index in this list of the first occurrence of the specified

element, or -1 if the List does not contain this element.

9. intlastIndexOf(Object o)

Returns the index in this list of the last occurrence of the specified

element, or -1 if the list does not contain this element.

10. Object remove(int index)

Removes the element at the specified position in this list. Throws

IndexOutOfBoundsException if index out of range (index < 0 ||

index >= size()).

11. protected void removeRange(intfromIndex, inttoIndex)

Removes from this List all of the elements whose index is between

fromIndex, inclusive and toIndex, exclusive.


12. Object set(int index, Object element)

Replaces the element at the specified position in this list with the

specified element. Throws IndexOutOfBoundsException if the

specified index is is out of range (index < 0 || index >= size()).

13. int size()

Returns the number of elements in this list.

14. Object[] toArray()

Returns an array containing all of the elements in this list in the

correct order. Throws NullPointerException if the specified array is

null.

15. Object[] toArray(Object[] a)

Returns an array containing all of the elements in this list in the

correct order; the runtime type of the returned array is that of the

specified array.

16.void trimToSize()

Trims the capacity of this ArrayList instance to be the list's current

size.

26]Write any two methods of array list class with their syntax.

booleanadd(E e): Appends the specified element to the end of this

list

void add(int index, E element) Inserts the specified element at the

specified position in this list.

void clear():Removes all of the elements from this list

Objectclone():Returns a shallow copy of this ArrayList instance

booleancontains(Object o): Returns true if this list contains the


specified element.

Eget(int index): Returns the element at the specified position in this

list.

intindexOf(Object o): Returns the index position of the element in

the list

booleanisEmpty() :Returns true if the list is empty.

intlastIndexOf(Object o): Returns the index of the last occurrence

of the object specified.

boolean remove(Object o): Removes the first occurrence of the

object from the list if it is present.

int size(): returns the number of elements in the list.

27]Describe following string class method with example:

(i) compareTo( )

(ii) equalsIgnoreCase( )

(i) compareTo( ):

Syntax: intcompareTo(Object o)

or

intcompareTo(String anotherString)

There are two variants of this method. First method compares this

String to another Object and second method compares two strings

lexicographically.

Eg. String str1 = "Strings are immutable";

String str2 = "Strings are immutable";

String str3 = "Integers are not immutable";

int result = str1.compareTo( str2 );


System.out.println(result);

result = str2.compareTo( str3 );

System.out.println(result);

(ii) equalsIgnoreCase( ):

public boolean equalsIgnoreCase(String str)

This method compares the two given strings on the basis of content of

the string irrespective of case of the string.

Example:

String s1="javatpoint";

String s2="javatpoint";

String s3="JAVATPOINT";

String s4="python";

System.out.println(s1.equalsIgnoreCase(s2));//true because content an

d case both are same.

System.out.println(s1.equalsIgnoreCase(s3));//true because case is ign

ored.

System.out.println(s1.equalsIgnoreCase(s4));//false because content i

s not same.

28]What is the use of wrapper classes in Java? Explain float

wrapper with its methods.

Use :

Java provides several primitive data types. These include int

(integer values), char (character), double (doubles/decimal values),

and byte (single-byte values). Sometimes the primitive data type

isn't enough and we may have to work with an integer object.

Wrapper class in java provides the mechanism to convert


primitive into object and object into primitive

Float wrapper Class:

Float wrapper class is used to wrap primitive data type float value

in an object.

Methods :

1) floatValue( ) method: It is used to return value of calling

object as float.

2) isInfinite( ) method: True if, value of calling object is

infinite, otherwise false.

3) isNaN( ) method: True if, value of calling object is not a

number, otherwise false.

4) floatToIntBits( ) method: It is used to return IEEE

compatible single precision bit pattern for n.

5) hashCode(float value) method: It is used to find hash code

of calling object.

6) intBitsToFloat(int bits ) method: It is used to return float

of IEEE compatible single precision bit pattern for n.

7) parseFloat( ) method: It is used to return float of a number

in a string in radix 10.

8) toString(float f ) method: It is used to find the string

equivalent of a calling object.

9) valueOf(String s) method: It is used to return Float object

that has value specified by str.

10) compare(float f1, float f2) method: It is used to compare

values of two numbers. If it returns a negative value, then,

n1<n2. If it returns a positive value, then, n1>n2. If it

returns 0, then both the numbers are equal.


11) compareTo (float f1) method: It is used to check whether

two numbers are equal, or less than or greater than each

other. If the value returned is less than 0 then, calling

number is less than x. If the value returned is greater than 0

then, calling number is greater than x. If value returned is 0,

then both numbers are equal.

12) equals(Object obj) method: It is used to check whether

two objects are equal. It returns true if objects are equal,

otherwise false.

29]Describe access control specifiers with example.

There are 4 types of java access modifiers:

1. private

2. default

3. protected

4. public

1) private access modifier:

The private access modifier is accessible only within class.

Example:

class test

private int data=40;

private void show()

System.out.println("Hello java");

}
}

public class test1{

public static void main(String args[]){

testobj=new test();

System.out.println(obj.data);//Compile Time Error

obj.show();//Compile Time Error

}.

In this example, we have created two classes test and test1. test

class contains private data member and private method. We are

accessing these private members from outside the class, so there is

compile time error

2) default access specifier:

If you don’t specify any access control specifier, it is default, i.e. it

becomes implicit public and it is accessible within the program

anywhere.\

Example :

class test

int data=40; //default access

void show() // default access

System.out.println("Hello java");

public class test1{

public static void main(String args[]){


testobj=new test();

System.out.println(obj.data);

obj.show();

3) protected access specifier:

The protected access specifier is accessible within package and

outside the package but through inheritance only.

Example :

test.java

packagemypack;

public class test

protected void show()

System.out.println("Hello java");

test1.java

importmypack.test;

class test1 extends test

public static void main(String args[])

test1obj=new test1();

obj.show();

}
}

4) public access specifier:

The public access specifier is accessible everywhere. It has the

widest scope among all other modifiers.

Example :

test.java

packagemypack;

public class test

public void show()

System.out.println("Hello java");

test1.java

importmypack.test;

class test1 ///inheritance not required

public static void main(String args[])

test1obj=new test1();

obj.show();

}}

30]Define a class ‘Book’ with data members bookid, bookname and price.

Accept data for seven objects using Array of objects and display it.
Ans: import java.lang.*;

import java.io.*;

class Book

String bookname;

int bookid;

int price;

BufferedReader br=new BufferedReader(new InputStreamReader

(System.in));

void getdata()

try

System.out.println("Enter Book ID=");

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

System.out.println("Enter Book Name=");

bookname=br.readLine();

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

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

catch(Exception e)

System.out.println("Error");

void display()

{
System.out.println("Book ID="+bookid);

System.out.println("Book Name="+bookname);

System.out.println("Price="+price);

class bookdata

public static void main(String args[])

Book b[]=new Book[7];

for(int i=0;i<7;i++)

b[i]=new Book();

for(int i=0;i<7;i++)

b[i].getdata();

for(int i=0;i<7;i++)

b[i].display();

31]Write a program to create a vector with seven elements as

(10,30,50,20,40,10,20). Remove elements 3rd and 4th position. Insert new


elements at 3rd position. Display original and current size of vector.

Ans: import java.util.*;

public class VectorDemo

public static void main(String args[])

Vector v = new Vector();

v.addElement(new Integer(10));

v.addElement(new Integer(30));

v.addElement(new Integer(50));

v.addElement(new Integer(20));

v.addElement(new Integer(40));

v.addElement(new Integer(10));

v.addElement(new Integer(20));

System.out println(v.size()); // display original size

v.removeElementAt(2); // remove 3rd element

v.removeElementAt(3); // remove 4th element

v.insertElementAt(11,2) // new element inserted at 3rd position

System.out.println("Size of vector after insert delete operations: " + v.size());

}}

32Differentiate between array and Vector


33]Describe following methods related to vector addElement(),

removeElement() and insertElementAt().

Ans: addElement(): Adds the specified component to the end of the vector,

increasing its size by one.

Syntax: void addElement(Object obj)

Example:

v.addElement("Apple");

v.addElement(10);

removeElement():Removes the specified component from the vector.

Decreasing the size of vector.

Syntax: removeElement(Object obj)


Example: v.removeElement(“Apple”);

insertElementAt():Inserts the item at nth position.

Syntax: insertElementAt(item,n)

Example: v.insertElementAt(“Orange”,3)

34]Explain this keyword with suitable example.

This keyword:

1. Keyword 'this' in Java is a reference variable that refers to the current

object.

2. It can be used to refer current class instance variable

3. It can be used to invoke or initiate current class constructor

4. It can be passed as an argument in the method call

5. It can be passed as argument in the constructor call

6. It can be used to return the current class instance

7. "this" is a reference to the current object, whose method is being

called upon.

8. You can use "this" keyword to avoid naming conflicts in the

method/constructor of your instance/object.

Example1

Using ‘this’ keyword to refer current class instance variables

class Test

int a;

int b;

Test(int a, int b) // Parameterized constructor

{
this.a = a;

this.b = b;

void display()

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

public static void main(String[] args)

Test object = new Test(10, 20);

object.display();

Example 2: Using ‘this’ keyword to invoke current class method

class Test {

void display()

// calling fuction show()

this.show();

System.out.println("Inside display function");

void show() {

System.out.println("Inside show funcion");

public static void main(String args[]) {

Test t1 = new Test();


t1.display();

35]Write a program to add two strings using command line arguments.

class Concats

public static void main(String args[])

String s1=args[0]; //Accept first string command line

String s2=args[1]; //Accept second string command line

String s3= s1+s2;

System.out.println("Concatnated String is : "+s3);

( OR )

class Concats

public static void main(String args[])

String s1=args[0]; //Accept first string command line

String s2=args[1]; //Accept second string command line

String s3=s1.concat(s2);

System.out.println("Concatnated String is : "+s3);

}
36]Give four differences between strings and string buffer class.

37]Explain vector methods:

1) addElement()

2) insertElementAt()

addElement(): It is used to add an object at the end of the Vector.

Syntax : addElement(Object);

Example : v.addElement(new Integer(10)); // add Integer object with value

10 at the end of the Vector object ‘v’.

insertElementAt( ) :Adds element to the vector at the location specified by


the index.

Syntax : void insertElementAt(Object element, int index)

Example: Vector v = new Vector( );

v.insertElementAt(“J”, 2); //insert character object in vector

at 2nd position.

38]Explain two dimensional array in java with example.

An array is a collection of similar type of elements that have a contiguous

memory location. Array is an object which contains elements of a similar

data type.

Types of Array

There are two types of array.

 Single Dimensional Array

 Multidimensional Array

Two – dimensional array is the simplest form of a multidimensional array.

Syntax:

data_type[][] array_name = new data_type[x][y];

For example:

int[][] arr = new int[2][3];

Initialization

array_name[row_index][column_index] = value;

For example: arr[0][0] = 1;

Representation of 2D array in Tabular Format: A two – dimensional array

can be seen as a table with ‘x’ rows and ‘y’ columns where the row number

ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two –

dimensional array ‘x’ with 3 rows and 3 columns is shown below:


int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

System.out.print(arr[i][j] + " ");

System.out.println();

Output:

12

3 4
39]Explain constructor with its type, Give example of parameterized

constructor.

Constructors are used to initialize an object as soon as it is created.

Every time an object is created using the „new‟ keyword, a

constructor is invoked. If no constructor is defined in a class, java

compiler creates a default constructor. Constructors are similar to

methods but with two differences, constructor has the same name as

that of the class and it does not return any value. The types of

constructors are:

1. Default constructor: when the constructor is not defined in the

program, the java compiler creates a constructor. Such a

constructor is called a default constructor.

2. Parametrized constructor: Such constructor are defined in the

program and consists of parameters. Such constructors can be

used to create different objects with data members having

different values.

class Student

int roll_no;

String name;

Student(int r, String n)

roll_no = r;

name=n;

}
void display()

System.out.println("Roll no is: "+roll_no);

System.out.println("Name is : "+name);

public static void main(String a[])

Student s = new Student(20,"ABC");

s.display();

3. No argument constructor- when the defined constructor in the program does not contain any
arguments, then it is called no

argument constructor.

40]
41]

42]Explain in detail garbage collection mechanism in java.

Java garbage collection is the process by which Java programs

perform automatic memory management. Java programs compile to

bytecode that can be run on a Java Virtual Machine. When Java

programs run on the JVM, objects are created on the heap, which is a

portion of memory dedicated to the program. Eventually, some

objects will no longer be needed. The garbage collector finds these

unused objects and deletes them to free up memory. Java garbage

collection is an automatic process.


In C/C++, programmer is responsible for both creation and

destruction of objects. Usually programmer neglects destruction of

useless objects. Due to this negligence, at certain point, for creation

of new objects, sufficient memory may not be available and entire

program will terminate abnormally causing OutOfMemoryErrors.

But in Java, the programmer need not to care for all those objects

which are no longer in use. Garbage collector destroys these objects.

Main objective of Garbage Collector is to free heap memory by

destroying unreachableobjects.

Just before destroying an object, Garbage Collector

calls finalize() method on the object to perform cleanup activities.

Once finalize() method completes, Garbage Collector destroys that

object.

Syntax :

protected void finalize() throws Throwable

//code ;

Based on our requirement, we can override finalize() method for

perform our cleanup activities like closing connection from database

43]How command line argument passed to the java program,

explain with suitable example.

Command line arguments is a methodology which user will give

inputs through the console using commands. Command Line

Argument is information passed to the program when you run the


program. The passed information is stored as a string array in the

main method. Later, you can use the command line arguments in your

program.

Example While running a class Demo, you can specify command line

arguments as

java Demo arg1 arg2 arg3 …

Example

class Demo{

public static void main(String b[]){

System.out.println("Argument one = "+b[0]);

System.out.println("Argument two = "+b[1]);

You might also like