Professional Documents
Culture Documents
1]What is difference between array and vectors? Explain any 2 methods of vector with example
Vector
class methods :
Adds the specified component to the end of this vector, increasing its size by one.
2) int capacity()
3) void clear()
7) boolean equals(Object o)
Compares the specified Object with this Vector for equality.
Searches for the first occurence of the given argument, testing for equality using the equals
method.
Inserts the specified object as a component in this vector at the specified index.
Removes the first (lowest-indexed) occurrence of the argument from this vector.
removeElementAt(int index)
example.
• 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
length=4;
breadth=5;
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
length=l;
breadth=b;
{
Rect r = new Rect(4,5); // constructor with parameters
System.out.println(“Area : ” +(r.length*r.breadth));
System.out.println(“Area : ” +(r1.length*r1.breadth));
Output :
Area : 20
Area : 42.
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
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
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
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
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
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:
//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()
empid=Integer.parseInt(obj.readLine());
name=obj.readLine();
salary=Double.parseDouble(obj.readLine());
}
void show()
}}
classEmpDetails{
e[i].getdata();
e[i].show();
}}
6] Define wrapper class. Give the following wrapper class methods with syntax and use:
8] Write a program to accept a number as command line argument and print the number is
even or odd.
public class oe
{
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.
i. elementAt ()
ii. addElement ()
iii. removeElement ()
Adds the specified component to the end of this vector, increasing its size by one.
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
import java.util.*;
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));
v.size());
}}
12] What is constructor? Describe the use of parameterized constructor with suitable
example.
Constructor:
creation.
It has the same name as class name in which it resides and it is syntactically similar to
any method.
initializes all numeric members to zero and other types to null or spaces.
Constructors do not have return value, but they don‟t require “void” as implicit data
Parameterized constructor:
Example:
class Rect
length=l;
breadth=b;
}
public static void main(String args[])
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
(i) length()
(ii) charAt()
(iii) CompareTo()
1. length():
System.out.println(str);
System.out.println(str.length()); // Returns 5
2. charAt():
System.out.println(s.charAt(2) ); // returns D
3. compareTo():
or
There are two variants of this method. First method compares this String to another
System.out.println(result);
System.out.println(result);
15]Explain following methods of string class with their syntax and suitable example.
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.
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
Example:
16]Write a program to implement a vector class and its method for adding and removing
import java.io.*;
import java.lang.*;
import java.util.*;
class vector2
{
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
• 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
• Once defined, constructor is automatically called immediately after the object is created
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
length=l;
breadth=b;
}
}
for it?
objects, which are no longer in use can be freed for further use.
management.
General Form :
example
20]What are the access control parameters? Explain the concept
available to any other class in the same package. Visible to all class in
its package.
E.g:
boolean processOrder()
return true;
Private access modifier is the most restrictive access level. Class and
Examples:
// ...
Protected access gives the subclass a chance to use the helper method
E.g
The following parent class uses protected access control, to allow its
{}
Example:
{}
21]What is :
(i) addElement() :
Syntax :
addElement(Object);
Example :
v.addElement(new Integer(10));
It will add Integer object with value 10 at the end of the Vector object
‘v’.
vector.
Syntax :
elementAt(index);
Example :
v.elementAt(3);
importjava.util.*;
import java.io.*;
class Vect {
v.addElement(new Integer(5));
v.addElement(new Integer(10));
v.addElement(new Float(5.0));
v.addElement(new Float(6.7));
int n=0;
InputStreamReader(System.in));
for(int i = 0; i <v.size();i++) {
try {
n = Integer.parseInt(b.readLine());
} catch(Exception e) {
System.out.println("Exception caught!"+e);
will be removed");
v.removeElementAt(n);
for(int i = 0; i<v.size();i++) {
System.out.println(v.elementAt(i));
example:
(i) substring()
(ii)replace()
(i) substring():
Syntax:
String substring(intstartindex)
(OR)
String substring(intstartindex,intendindex)
the stopping point. The string returned all the characters from the
Example :
System.out.println(("Welcome”.substring(3)); //come
System.out.println(("Welcome”.substring(3,5));//co
(ii) replace():
Example:
Java.
Garbage collection:
objects, which are no longer in use can be freed for further use.
memory management.
statement
Example:
public class A
int p;
A()
{
p = 0;
class Test
the object.
General Form :
}
25]What is the use of ArrayList class? State any two methods with
lists are created with an initial size. When this size is exceeded, the
2.boolean add(Object o)
booleanaddAll(Collection c)
this list, in the order that they are returned by the specified
collection is null.
Inserts all of the elements in the specified collection into this list,
4. void clear()
Removes all of the elements from this list. 6. Object clone()
5. boolean contains(Object o)
formally, returns true if and only if this list contains at least one
6. void ensureCapacity(intminCapacity)
8. intindexOf(Object o)
Returns the index in this list of the first occurrence of the specified
9. intlastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified
Removes from this List all of the elements whose index is between
Replaces the element at the specified position in this list with the
null.
correct order; the runtime type of the returned array is that of the
specified array.
16.void trimToSize()
size.
26]Write any two methods of array list class with their syntax.
list
list.
the list
(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
lexicographically.
System.out.println(result);
(ii) equalsIgnoreCase( ):
This method compares the two given strings on the basis of content of
Example:
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
ored.
s not same.
Use :
Float wrapper class is used to wrap primitive data type float value
in an object.
Methods :
object as float.
of calling object.
otherwise false.
1. private
2. default
3. protected
4. public
Example:
class test
System.out.println("Hello java");
}
}
testobj=new test();
}.
In this example, we have created two classes test and test1. test
anywhere.\
Example :
class test
System.out.println("Hello java");
System.out.println(obj.data);
obj.show();
Example :
test.java
packagemypack;
System.out.println("Hello java");
test1.java
importmypack.test;
test1obj=new test1();
obj.show();
}
}
Example :
test.java
packagemypack;
System.out.println("Hello java");
test1.java
importmypack.test;
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;
(System.in));
void getdata()
try
bookid=Integer.parseInt(br.readLine());
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
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();
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));
}}
Ans: addElement(): Adds the specified component to the end of the vector,
Example:
v.addElement("Apple");
v.addElement(10);
Syntax: insertElementAt(item,n)
Example: v.insertElementAt(“Orange”,3)
This keyword:
object.
called upon.
Example1
class Test
int a;
int b;
{
this.a = a;
this.b = b;
void display()
object.display();
class Test {
void display()
this.show();
void show() {
class Concats
( OR )
class Concats
String s3=s1.concat(s2);
}
36]Give four differences between strings and string buffer class.
1) addElement()
2) insertElementAt()
Syntax : addElement(Object);
at 2nd position.
data type.
Types of Array
Multidimensional Array
Syntax:
For example:
Initialization
array_name[row_index][column_index] = value;
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 –
System.out.println();
Output:
12
3 4
39]Explain constructor with its type, Give example of parameterized
constructor.
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:
different values.
class Student
int roll_no;
String name;
Student(int r, String n)
roll_no = r;
name=n;
}
void display()
System.out.println("Name is : "+name);
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]
programs run on the JVM, objects are created on the heap, which is a
But in Java, the programmer need not to care for all those objects
destroying unreachableobjects.
object.
Syntax :
//code ;
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
Example
class Demo{