You are on page 1of 66

Core Java Subjective Questions And Answers

Question :
Can a main() method of class be invoked in another class?

Answer:Yes! We can invoke the main() method of one class in another class.
Since main() method is a static method, it can be invoked by using the class name with the
method name.

Q:What is the difference between == & .equals()?

Answer:
The == and eqauls() method, both are used to check the equality of the two strings,
but in the different sense.The Strings eqauls() method put the two strings in the two different
arrays and compare the characters one by one. If all the characters are matched then this
method will
return true otherwise false.The == operator checks wheater the two strings points to
the same the object or not. The == operator checks the bit pattern of the two references.

Question :
What is the difference between abstract class & Interface?
Answer:
Abstract class is a class that can not be instantiated and having zero or more abstract method.
It must be subclassed by other class implementing the abstract method. The abstract class
is modified by keyword \'abstract\'.
Interface can be think of as fully abstract class.All the method within the interface are
abstract must end with a semicolon followed by parantheses.If a class implement an Interface,
it must provide the definition to all the methods of the interface or it must be the abstract class.

Answer:

abstract static class A{


//abstract class can be static.
//static int a; can to deacral static static only static or top tavel type.
private int aa;
protected int aga=0;
public int sss;
int gg;
//varible may be public ,private,default,protucted,
satic final,final,non initialize,initialized,final must initialized
public static int a=0;
public final int b=0;
public final static int cc=0;
public abstract void did();//must have return types.only public or protected.
not either final static
private vo
id dd(){}
public void ff(){}
protected void fff(){} //concarite method may be public ,protected,private,default
void dddd(){}

}
//an interface can not extends or implements abstract class or class
//No, an interface can extends only other interface.

interface AA {
//private int aa;
//protected int aga=0;
public int sss=0;
int gg=0;//default initialisation
//only public ,default ,final,static.
public static int a=0;
public final int b=0;
public final static int cc=0;
public abstract void did();//must have return types.only public or protected.
not either final static
//private void dd();//only public & abstract
public void ff();
//protected void fff(); //only public & abstract
void dddd();//default modifer
}

Question :

What is use of static, final variable?

Give Your Answer


Answer:

If you modify a variable or method by a static modifier it means


there is only one copy of that variable or method shared by all the
instances of that class. A class can not be modified as static,
but an inner class.
A final variable is just like a constant. It's value can not be
change once it is initialized. It must be initialized at the
time of variable declaration or the constructor completed.

Question :

Examples of final class.

Answer:
If you modify a class with a final keyword, it means, this class can not be
subclassed.
No class can inherit the features of the final class. If you try to this, an
error will result.
Example:

package p1;
public final class FinalClass{
public void show(){
System.out.println("This is a final class.");
}
}

class FinalSub extends FinalClass{ //error


public static void main(String[] args){
FinalClass f=new FinalClass();
f.show();
}
}

Output:
The above program will result an error in compilation like 'can't subclassed a
final class'.

Date:11.01.09

Question :
What is a java bean?

Give Your Answer

Answer:
JavaBeans is an API reusable, platform indepent component written
in java programming language. A JavaBean is a simple class having
the setter and getter methods for each property. It is good convension
to implement the Serializable interface.
Example:
import java.io.*;
public class MyBean implements Serializable {
// Properties
private String name = null;
private int age = 0;
// Getter and Setter Methods
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}

public int getAge() {


return age;
}

public void setAge(int i) {


age = i;
}
}

Date:11.01.09

Question :
What is use of synchronized keyword?

Give Your Answer

Answer:
One of the most powerful feature of Java is its multithreading mechanism.
The synchronization is used to coordinate the activities between
the multiple threads.
Java uses the monitor to synchronize the methods or the block of code.
A 'synchronized' keyword is used with the method signature or before a
block of code. If all the thread of the class want to access the
same method concurrently, monitor helps them to synchronize the access
one thead at a time by locking the resource being accessed on the accessing
object.

Date:11.01.09
Question :
What is reflect package used for & the methods of it?

Give Your Answer

Answer:
The java.lang.reflect package provides the information about the code, i.e.
objects and classes.
Reflection provides the programmatic access to variables, methods,
constructors to operate on objects.
It is used to retrieve the member information for any loaded class.

Example:
Class a=Class.forName("java.lang.String");
Method m[]=a.getDeclaredMethods();

java.lang.reflect package provides classes such as


Method,Modifier,Field,Constructor,Proxy etc.
Using these classes we can retrieve the needed
information of the loaded class.

Date:11.01.09

Question :
What is use of serialization?

Give Your Answer

Answer:
Serialization can be obtained in a class by implementing the
java.io.Serializable interface. All the subclasses of a serialized
class are also themseleves serialize. This interface contains no
methods and used simply to identify being serialized.
Its main purpose is to save the object state into a device or file
for the future use. This process is calles serialization.
When we want to access the state of the object we make it deserialized.
The classes that require serialization must implement the
following methods for the serialization and deserialization process.

private void writeObject(java.io.ObjectOutputStream out)


throws IOException{
//write the object state
}
private void
readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException{
//read the object state
}

The writeObject() method is responsible for saving the state


of the object into a resource, i.e. device or a file. The readObject()
method is responsible for the accessing the object state.

Question :

Can methods be overloaded based on the return types ?

Give Your Answer

Answer:
No! Methods can't be overloaded based on the return type.
For methods overloading you must change the argument list.
You can change the number of parameter passed or their data types.
The return type may be the same, doesn't matter.

Date:11.01.09

Question :
Why do we need a finalize() method when Garbage Collection is there ?

Give Your Answer

Answer:
Before performing the garbage collection the JVM called the
finalize() method to cleanup the resources such as closing
the file or socket connection etc.
The finalize() method is declared in the java.lang.Object
class. When you implement the finalize method, you are
actually overriding it from the Object class.

Your finalize() method must be declared as follows:

protected void finalize () throws throwable{


//some cleanup code here
}
Question :

What is Exception ?

Give Your Answer

Answer:
An Exception is an abnormal condition that may occur during
the program execution. Exception is a class drived from
the Throwable class. Two types of exception are there:Checked
exception and Unchecked exception. If a checked exception is
thrown by a method it must declare it or handle it by providing a
try/catch block.
Java provides the five keywords for handling the exception:
try,catch,throw,throws and finally.
When an exception is thrown,the class Exception or its subclass
must be instantiated and passed to the catch block as a parameter.

Date:11.01.09

Question :
What are the ways you can handle exception ?

Give Your Answer

Answer:
When an exception is thrown by a method, it must declare or handle it.
A method can declare the exception using the keyword throws with
the method signature and a list of exceptions type so that the
calling methods can guard themselves.
For example:
public void myMethod() throws IOException, ArithemeticException{
//some code here that might cause the exception
}

If a method does not declare the exception then it must handle


the exception by providing the try/catch block.
For example:
public void myMethod(){
try{
//some code here that might cause the arithematic exception
}catch(ArithematicException e){
}
}

Date:11.01.09

Question :
What is finally method in Exceptions ?

Give Your Answer

Answer:
You never know that the exception will be thrown or not.
That means you are not sure that the catch will be executed or not.
So it is better not to put the code inside the catch block which
must be executed such as closing a file or a socket connection.
Java provide another keyword 'finally' for this purpose. The finally
block must come immediately after the all catch blocks or after the
try block if there is no catch associated with the try block. The finally
block must be executed, doesn't matter the exception is thrown or not.

Date:11.01.09

Question :
What are the types of access modifiers ?

Give Your Answer

Answer:
In java, there are three types of access modifiers:
*public
*protected
*private
But, there are four access control levels, burn it
into your mind. The fourth access control level is
default. We get default access control if we
don't use any of the access modifiers.
Question :

What are the other modifiers in java ?

Give Your Answer

Answer:
Besides access modifiers, the other modifiers in java are:
*abstract,
*static,
*final,
*strictfp,
*transient,
*volatile,
*native,
*synchronized, etc.

Date:11.01.09

Question :
Is synchronized modifier ?

Give Your Answer

Answer:
Yes! synchronized is a modifier in java. It is used
for synchronized a resource if multiple threads
want to access the resource.

Date:11.01.09

Question :
What is meant by polymorphism ?

Give Your Answer


Answer:
Polymorphism is a useful mechanism in java.
Polymorphism means 'one name with multiple
implementaions.' Java supports two types of
polymorphism: static and dynamic polymorphism.
Polymorphism can be achieved in java by method
overloading (static polymorphism) and method
overriding (dyanmic polymorphism).

Overloading: Using the same method name with


multiple implementation in such a way that
the argument list must be changed and return
type may change. For overloading, change in
the argument list is a must. Overloading resolve
at the time of compilation.

Overriding: Using the same method name with the


same argument list and return type called method
overriding. However in Java 5, the ruturn type of
the overrriding method may be changed with the
subtype of the overridden method.

Date:12.01.09

Question :
What is inheritance ?

Give Your Answer

Answer:
Inheritance is the mechanism of using the features of one
class into another class. The class which acquire the properties of
another class (super class)is called subclass or drived class.
Java provides the keyword 'extends' to support the Inheritance.

Example:

package p1;
public class SuperClass{
void show(){
System.out.println("Super class");
}
}

class SubClass extends SuperClass{


public static void main(String[] args){
SubClass s=new SubClass();
s.show();
}
}

Date:12.01.09

Question :
What is method Overloading ?

Give Your Answer

Answer:
Using the same method name with different arguments
list is called method overloading. To overload a
method, you must change the arguments list. The
return type may or may not be change.

Question :

What is method Overriding ?

Give Your Answer

Answer:
Using the same method name with the same argument list and
return type called method overriding. However in Java 5, the
ruturn type of the overrriding method may be changed with
the subtype of the overridden method.

Date:12.01.09

Question :
Does java support multi dimensional arrays ?
Give Your Answer

Answer:
No! Java does support array within arrsay.We can achive multidimensional
arrays using it.Example:int[][][] m=new int[3][3][2];

Date:12.01.09

Question :
Is multiple inheritance used in Java ?

Give Your Answer

Answer:
Java does not support multiple inheritance.
But we can achievethis using interface.
A class can't extends more than one class
but an interface can extends more than one
interface.
Example:

interface I1{
//some abstract methods here
}

interface I2{
//some abstract methods here
}

interface I3 extends I1,I2{


//some abstract methods here
}

Date:12.01.09

Question :
Is there any tool in java that can create reports ?
Give Your Answer

Answer:
Yes! There are many reporting tools in java:
* JFreeChart
* Prefuse
* JasperReports
* jCharts
* JFreeReport

Date:12.01.09

Question :
What is meant by Java ?

Give Your Answer

Answer:
Java is a pure Object oriented programming language originally developed by
Sun Microsystems,
released in 1995 and has the capability in its platform independency.
It support multithreading, exception handling and automatic
garbage collection facilities.
Java supports various applications like:Web applications and web services.

Question :

What is meant by a class ?

Give Your Answer

Answer:
A Class is a just like a container which contains
variables and methods. The variables make up the
state and the methods describe the behaviour of the
class.
Date:12.01.09

Question :
What is meant by a method ?

Give Your Answer

Answer:
A method is a group of instructions enclosed by the curly braces{}.
A method has a specific signature having the method name along
with the parameter list and a return type. Methods describe
the behaviour of the class. Methods are where the real work gets done,
date get manipulated and algorithms implemented.

Date:12.01.09

Question :
What are the OOPS concepts in Java ?

Give Your Answer

Answer:
Java is a pure Object oriented programming language and supports:
* Class
* Object
* Abstraction
* Encapsulation
* Polymorphism
* Inheritance, etc.

Date:12.01.09

Question :
What is meant by encapsulation ? Explain with an example.

Give Your Answer

Answer:
Binding up the data and methods into a single
unit, i.e. class is called encapsulation.
Example:

class Area{
//data variable
double dim1;
double dim2;
//methods
public double calculateArea(double d1,double d2){
//some calculation code here
}
}

Date:12.01.09

Question :
What is meant by inheritance ? Explain with an example.

Give Your Answer

Answer:
Inheritance is the mechanism of using the features of one
class into another class. The class which acquire the properties of
another class (super class)is called subclass or drived class.
Java provides the keyword 'extends' to support the Inheritance.

Example:

package p1;
public class SuperClass{
void show(){
System.out.println("Super class");
}
}

class SubClass extends SuperClass{


public static void main(String[] args){
SubClass s=new SubClass();
s.show();
}
}

Question :

What is mean by JVM ?

Give Your Answer

Answer:
A Java source code is compiled by java compiler(javac)
and converted into the bytecode. This bytecode is then executed
by the JVM. A Java Virtual Machine (JVM) is a software program
and data structures which use a virtual machine model to execute
the instructions. JVM accepts accepts the byte code and provides
output of that bytecode. A bytecode is highly optimized set of
instructions.The JVM is combines a set of standard class
libraries which implement the Java API (Application Programming Interface).

Date:12.01.09

Question :
What is meant by identifiers ?

Give Your Answer

Answer:
Identifiers are just the name of the variables, methods, classes,
interfaces etc. Each of the above things is identified by their
names in the programm. They are not the thing themselves, they just
point to the values in the memory. Identifiers follows some rules to
be declared:
* Identifiers must be composed of letters, numbers, the underscore _ and
the dollar sign $.
* Identifiers may only begin with a letter, the underscore or a dollar sign.

Date:12.01.09
Question :
What are the different types of modifiers ?

Give Your Answer

Answer:
There are two types of modifiers in Java:
* Access Modifiers,
* Non-access modifiers.

Acess modifiers are public, protected and private.


Non-access modifiers are abstract, final, static, transient, volatile,
strictfp, and synchronized.

Date:12.01.09

Question :
What are the primitive data types in Java ?

Give Your Answer

Answer:
Primitives data types in java are:
* boolean
* char
* byte
* short
* int
* long
* float
* double

Date:12.01.09

Question :
What is mean by a wrapper class ?
Give Your Answer

Answer:
The wrapper classes serve the two purpose:
* It wraps the primitive to an object so that primitives can
be used in the activities which are reserved only for the objects.
* Converting primitives to and from String objects.or we can use the Wrapper
class for wrapping up of the primitive types into the collections so that we
can use the primitive types as objects in the collections.
Java provides the Wrapper class for each of the primitives
in java. Some of these are:
* Boolean
* Character
* Byte
* Short
* Integer
* Long
* Float
* Double

Question :

What is Garbage collection ?

Give Your Answer

Answer:
Java provides the automatic garbage collection facility.
JVM performs the garbage collection to free up the unnecessary
memory which can't be reached through the object reference.
We can't force the JVM to perform the garbage collection,
but we can request the JVM by our program to to call the
method System.gc(), but it is upto JVM to perform garbage
collection or not.

Date:12.01.09

Question :
What is mean by final class, methods and variables ?

Give Your Answer


Answer:
A final keyword is used to prevent the inheritance if it
is used with the methods and classes.
If we modify a class with the final modifier, it means, that class
can't be subclassed, i.e. we can not make a subclass of final class.
If we declare a method to final, it means, that method will not be inherit
in the subclass of that class in which the final method is declared.
If we declared a final variable, it means, that the value of the
variable can not be modified once it is initialized.

Date:12.01.09

Question :
What is mean by interface ?

Give Your Answer

Answer:
You can think of interface as a fully abstract class.
An abstract class can have abstract and non-abstract methods,
but an interface can have only abstract methods ends with the semicolon.
An interface may also contain constant.
Example:

public interface MyInterface{


int i1;
static int i2;
static final int i3;

void showi1();
public void showi2();
public abstract showi3();
}

Date:12.01.09

Question :
What is the difference between an array and a vector ?

Give Your Answer

Answer:
An array is simply a data structure that stores the similar
types of elements with sequence of consecutively numbered.

int a[]=new int[3];

This will create an array of int of size 3. The size


of the can't be increase once it is created.

Vector is just like an array, but it is rescalable.


That means we can increase or decrease the size of the vector.
One most important thing about vector is that unlike array,
vector can hold multiple types of element. Vector can be declared as:

Vector v=new Vector();

Vector provides the methods to manipulate the elements:

v.add("Hello");
v.add(3);
v.add(1,"world!");
v.set(2,"How are you!");
v.get(0);

Use the vector if you want to store the multiple data types
and don't know about the size.

Date:12.01.09

Question :
What is singleton class ?

Give Your Answer

Answer:
The Singleton is a Design Pattern for allowing only
one instance of your class. The Singleton's main
purpose is to control object creation upto one. It
is good for threading problems, because we are sure
that there is only one instance of the class.
Question :

What is constructor ?

Give Your Answer

Answer:
Constructors are the special member functions which have
the same name as the class name. The most important
thing is that they don't hava return type. Constructors
may be overloaded. If you don't provide a constructor
for the class, the compiler will supply the defualt one.
Constructors can have any of the access modifiers.

Example:

public class MyClass{


int i;
int j;
public MyClass(){}
protected MyClass(int i){}
private MyClass(int i,int j){}
}

Date:12.01.09

Question :
What is casting ?

Give Your Answer

Answer:
Casting is the process of assigning the value of one type of variable to
another type of variable. Two types of casting are there in java:
*Implicit casting
*Explicit casting

We can directly assign the value of a variable to other variable if


that variable can be easily fit by memory size into the other
variable, this is called implicit casting.

Example:
int a=5; //a having 4 byte of memory
byte b=6; //b having 1 byte of memory

a=b; //OK! byte b can be easily fit into an int a.


b=a; //NO! int a can't be fit into the byte b.

b=(byte)a; //OK! Explicit casting.

The above statement telling the compiler that, I know there may
be some loss of bits.

Date:12.01.09

Question :
What is the difference between final, finally and finalize ?

Give Your Answer

Answer:
final is a keyword used for the following things:
* final variable use to prevent the value modification.
* final methods can't be inherited.
* final class can't be subclassed.

finally is the block of code used with the try/catch block


or the try block if there is no catch associated with the try
block. It is useful where you want some code must be executed
wheather the exception is thrown or not.

finalize is a method that is called by JVM just before the


performing the garbage collection. But is not sure that
this method will be called ore not, it depends upon the JVM.
It is declared in the Object class. You can override the
finalize() method.

Date:12.01.09

Question :
What is mean by packages in java?

Give Your Answer


Answer:
Packages are the container for the classes. A single
package may contain several classes and sub packages.

Java provides the keyword 'package' to declare the package.


Each package has an identifier and can be import in the
other package. Packages are introduced to resolve the class
naming confliction that can arise when two programmers
have the same name for their classes.

Declaring a package:

package p1;
class abc{}

Importing a package:

package p2;
import p1.abc;
class xyz{}

Date:12.01.09

Question :
Name 5 calsses you have used ?

Give Your Answer

Answer:
* String
* Thread
* ArrayList
* Vector
* HashMap

Question :

Name 2 classes that can store arbitrary number of objects ?

Give Your Answer


Answer:
* ArrayList
* Vector

Date:12.01.09

Question :
What is the difference between java.applet.* and java.applet.Applet ?

Give Your Answer

Answer:
When you import java.applet.*, it means you are importing
all the classes available in the java.applet package.

When you import java.applet.Applet, it means you are importing


the single class. It is better to import the classes that
you need instead of importing all the classes in the package.

Date:12.01.09

Question :
What is a default package ?

Give Your Answer

Answer:
The java.lang is the default package which is automatically
imported in each of the java source file.

Date:12.01.09
Question :
What is anonymous class ?

Give Your Answer

Answer:
Anonymous class is one that has no name. Java provides
the anonymous inner classes with different flavours.
An anonymous inner class can also be declared even in the
argument list of the method.

Date:12.01.09

Question :
What is the use of an interface ?

Give Your Answer

Answer:
An interface tells that what a class can do. It is a good
object oriented design to use interfaces in your program.
When a class implements the interface, it is actually
contracting to implement all the functionality of the interface.
Interfaces also support multiple inheritance.

Question :

What is a serializable interface ?

Give Your Answer

Answer:
If a class implements the serializable interface,
it means that state of objects of that class can be
serialized and deserialized. This interface has no
methods.
Date:12.01.09

Question :
How to prevent field from serialization ?

Give Your Answer

Answer:
If you want prevent serialization of the
fields(variables), mark them transient.
The transient variable can't be serialized.

Date:12.01.09

Question :
What is the difference between throw and throws ?

Give Your Answer

Answer:
The throw keyword is used to throwing the exception
manually in the program. For Example:

try{
throw new NullPointerException();
}catch(NullPointerException e){
}

The throws keyword is used with the method signature


with the list of Exceptions type. This process is called
exception declaration. It tells the calling method to
guard themselves to declare the exception or handle it.
For example:

void calculate(int a,int b) throws ArithematicException{


//some calculation code here
}
Date:12.01.09

Question :
Can multiple catch statements be used in exceptions ?

Give Your Answer

Answer:
Yes! Multiple catch statement can be used in exceptions,
but with some general rules. A single try block can have
multiple catch associated with it but the each catch has
an arguments according to the inheritance heirarchy of
Exception. That means a subtype of Exception heirarchy
must not be come in the catch block before the supertype
of the Exception heirarchy.

Example:
try{
int i=3/0; //divide by zero exception
}catch(Exception e){
}catch(ArithematicException e){
}

The above code will result a compilation error 'unreachable


code' at the second catch statement because ArithematicException
is a subtype of the Exception class. The above code should be
like this:

try{
int i=3/0; //divide by zero exception
}catch(ArithematicException e){
}catch(Exception e){
}

Date:12.01.09

Question :
Is it possible to write a try within a try statement ?

Give Your Answer


Answer:
Yes! The try statement can be nested within another try block.

Question :

What is mean by a Thread ?

Give Your Answer

Answer:
Thread is a light weight process.The Java Virtual Machine
allows an application to have multiple threads of execution
running concurrently.Every thread has a priority from one
to ten. Threads with higher priority are executed in preference
to threads with lower priority. Java provides two ways to
create the Thread:
* Extending the Thread class
* Implementing the Runnable interface.

Date:12.01.09

Question :
What is mean by multi-threading ?

Give Your Answer

Answer:
Multithreading allows two or more parts of the same program to
run concurrently. A single program or block of code can be
executed by any number of treads. Some problems may arises with
multi-threading if two or more threads manipulates
the shared or global variable.

Date:12.01.09
Question :
What is the 2 way of creating a thread ? Which is the best way and why?

Give Your Answer

Answer:
Two way of creating the thread in java are:
* Extending the Thread class
* Implementing the Runnable Interface.

Both ways provides the same functionality. But it


is better to implement the Runnable interface,
because if you extends the Thread class you will
not be able to extend any other class. One class
can extends only a single class but can
implements many interfaces.

Date:12.01.09

Question :
What is the method to find if a thread is active or not ?

Give Your Answer

Answer:
The method to find if a thread is active:

boolean isAlive()

Date:12.01.09

Question :
What is the difference between sleep and suspend ?

Give Your Answer


Answer:
The sleep() method moves the thread to waiting
state for particular time.
for example
Thread.sleep(7000);
but
the suspend() method moves to waiting state until
the resume() method gets called.

Question :

Can thread become a member of another thread ?

Give Your Answer

Answer:
No! In multi-threading environment a thread can
start the another thread but it can not be a
member of another thread.

Date:12.01.09

Question :
What are the three types of priority ?

Give Your Answer

Answer:
MIN_PRIORITY
MAX_PRIORITY
NORM_PRIORITY

Date:12.01.09

Question :
Garbage collector thread belongs to which priority ?

Give Your Answer

Answer:
Garbage collector thread belongs to low priority.

Date:12.01.09

Question :
What is the use of this ?

Give Your Answer

Answer:
this keyword is used to point to the currently executing object.
The most common reason for using the this keyword is because a field
is shadowed by a method or constructor parameter.

Example:

public class PointExample {


public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Date:12.01.09

Question :
How can you find the length and capacity of a string buffer ?
Give Your Answer

Answer:
The StringBuffer is a class that has a mutable sequence
of charcters. Length and capacity of the StringBuffer
object can be find out by the following two methods:

* length()
* capacity()

Capacity of the StringBuffer is always plus 16 to


the length.
Example:

class StringBufferExample {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello World!");
System.out.println("Buffer value= "+sb);
System.out.println("Length = " +sb.length());
System.out.println("Capacity = " +sb.capacity());
}
}

Question :

How to compare two strings ?

Give Your Answer

Answer:
There are two ways to compare the two strings in java:
* using the == operator,
* using the equals() method.

For Example:

String s1=new String("Hello!");


String s2=new String("Hello!");

if(s1==s2)
System.out.println("Equal using == operator.");
elseif (s1.equals(s2))
System.out.println("Equal using equals method.");
else
System.out.println("Not Equal.");
Date:12.01.09

Question :
What is the purpose of run-time class and system class?

Give Your Answer

Answer:
The System class provide system
level functionality to Java applications.
Some of the facilities provided by System class:
* Reading input from the keyboard.
* Writing output to console.
* Reading and writing system properties and
environment variables

Runtime class provides support for runtime environment.

Date:13.01.09

Question :
What is the method used to clear the buffer ?

Give Your Answer

Answer:
flush()

Date:13.01.09

Question :
What is mean by Stream Tokenizer ?
Give Your Answer

Answer:
The StreamTokenizer is class in Java that takes
an input stream and parses it into "tokens",
allowing the tokens to be read one at a time.
Each byte read from the input stream is a
character in the range from '\u0000' to '\u00FF'.
The character value is used to look up five
possible attributes of the character: white
space, alphabetic, numeric, string quote, and
comment character.

Some Methods defined by StreamTokenizer class:


* void whitespaceChars(int low, int hi)
* void wordChars(int low, int hi)
* String toString()
* void slashStarComments(boolean flag)
* void parseNumbers()
* void ordinaryChars(int low, int hi)
* int lineno() ,etc.

Date:13.01.09

Question :
What is serialization and de-serialisation ?

Give Your Answer

Answer:
The values assigned to the variables of an object
make up the state of the object. Saving the state
of the object for the future use into some file
or the device is called the Serialization. When
we want to use that object, we read the values of
the variables from the file or device. This
process is called De-serialization.

Question :

What is the difference between C++ & Java ?


Give Your Answer

Answer:
Difference between java and C++ :
* C evolved into C++, and C++ transmuted into Java.
* Java is the language of the Internet whereas
C++ was designed mainly for systems programming,
* Java supports object-oriented programming,
same way as C++.
* Java does not support operator overloading.
* Java does not include a preprocessor or
support the preprocessor directives.
* Java does not support multiple inheritance.
* Java does not support destructors, but rather,
add the finalize() function.
* Java does not support templates.
* Java does not support pointers.

Question :

Why Java is not fully objective oriented ?

Give Your Answer

Answer:
Java is not fully object oriented language,
because not all values in Java are Objects. The
basic numeric types such as int, long, double,
etc., are not objects and need to be "boxed" into
objects in order to pass them as Object
parameters or call methods on them. Java does not
support Multiple inheritance and operator
overloading. Java uses static keyword. We can
perform a function declared as static without an
object this violates real world reflection and
object orientation.

Date:14.01.09

Question :
What it the root class for all Java classes ?
Give Your Answer

Answer:
The Object class is the root class of all the Java classes

Question :

Why there are some null interface in java ? What does it mean ?

Give Your Answer

Answer:
Interface which does not contain any variables and methods.
Examples:
* java.io.Serializable,
* java.lang.Cloneable, etc

Both of these interfaces declare no methods, by


implementing them, a class signals some fact to
the JVM (either it's OK to serialize it, or it's ok to clone it.)

The null interface is also called as Marker


Interface or tagged interface.

Question :

public static void main - Explain?

Give Your Answer

Answer:
Public is an access modifiers tells that this
method can be accessed anywhere inside or outside
the package by any class' object reference.

static means there is only one copy of that method


is available to all the instances of the class.

void is simply a return type of the method


telling that this method will return nothing.

main is an identifier to indentify the method.


The main() method is the entry point to the
program.

Question :

What is difference between String & StringBuffer?

Give Your Answer

Answer:
String class provides the immutable character
sequence whereas StringBuffer class objects are
mutable characters sequence. The StringBuffer is
faster than String when performing simple
concatenations.

Example:

String s=new String("Hello");


s.toUpperCase();

The String object s is still pointing to "Hello"


instead of "HELLO". Here a new string "HELLO" is
created but did not assinged to any reference
variable.

But:

StringBuffer sb=new StringBuffer("Hello");

sb.toUpperCase();

The StringBuffer object sb is now pointing to the


"HELLO".
This is the main difference that string object
are immutable and string buffer objects are
mutable.

Date:14.01.09

Question :
What is Wrapper class. Is String a Wrapper Class?

Give Your Answer


Answer:
Wrapper classes are used to "wrap" the primitives
data types into objects so that they can be
included in the activities which are reseved for
the objects.

Yes! String class is a wrapper class, it wraps


the string literals to an object.

Date:14.01.09

Question :
What is Default modifier in Interface?

Give Your Answer

Answer:
Default modifier in Interface is public access modifier.

Date:14.01.09

Question :
Can abstract be declared as Final?

Give Your Answer

Answer:
No! An abstract method or abstract class can't be
marked as a final. They both have the opposite meaning. An abstract class must
be subclassed,
whereas a final class must not be. An abstract
method must be overridden whereas a final method
can't be inherited, hence can't be overridden.
Date:14.01.09

Question :
Can we declare variables inside a method as Final Variables?

Give Your Answer

Answer:
Yes! we can declare variables inside a method as final variables.

Question :

How can a dead thread be started?

Give Your Answer

Answer:
A Thread is considered to be dead when it completes
its run() method. We can't call a start() method on
a given Thread object for the second time. Hence a
dead thread can't be restarted.

Date:14.01.09

Question :
Can Applet have constructors?

Give Your Answer

Answer:
Yes we can have constructors in an applet. But
applets don't usually have constructors because an
applet isn't guaranteed to have a full environment
until its init() method is called. Applet
constructor is just like any other constructor,
they cannot be overridden.

Date:14.01.09

Question :
What is Checked & Unchecked exception?

Give Your Answer

Answer:
Both types of exceptions are drived from the class Exception. But Unchecked
exception are RunTimeException, which do not to be handled or declared.
Whereas Checked Exceptions must be handled by try/catch block or must be
declared in the method signature.

What is meant by a resource leak ?

Give Your Answer

Answer:
A resource leak is where memory is being steadily consumed by resources that
are no longer being used. In java this situation arises when references to
objects that are no longer required. To avoid this you should remember to set
all variables to null as soon as you are finished with the reference. This
will allow the gc to free up the memory that the objects were consuming.

Date:14.01.09

Question :
What are the thread-to-thread communication ?

Give Your Answer


Answer:
Threads communication is possible in java. A first thread registers with a
gateway for receiving communication. Registration includes identifying a
location for receiving messages. The gateway maps message payloads received
from second threads to the location of the first thread. The first thread
detects a payload in the location and consumes it for processing.

Question :

What is user defined exception ?

Give Your Answer

Answer:
Yes! We can also defined our own exceptions according to our requirment. We
can do this by extending the Exception class, in this class we override the
toString() method.

Date:14.01.09

Question :
In an HTML form I have a Button which makes us to open another page in 15
seconds. How will do you that ?

Give Your Answer

Question :
Suppose If we have variable I in run method, If I can create one or
More thread each thread will occupy a separate copy or same variable will be
shared ?

Give Your Answer

Answer:
If we have a local variable declared in the run method then all the existing
thread will hava a separate copy for that variable. If we are using the
instance variable in the run method then this will be shared by all the
existing variable.

Question :

Can a method be overloaded by different return type but same argument type?

Give Your Answer

Answer:
No! For method overloading, the parameter list must be changed. Method
overloading does not depend the on return type.

Date:14.01.09

Question :
What is constructor chaining and how to do this in Java?

Give Your Answer

Answer:
Contructor can be overloaded,i.e. a single class can hava more than one
contructor. A construct may call to another constructor. The first statement
in the constructor must be a call to either this() or super() but not both.
The super() will call the matching superclass constructor according to the
number of arguments passed in the super(). A this() will call the overloaded
constuctor in the same class according to the parameter list. The called
constructor may also make a call to the other constructor using this(). This
type of contructor calling in the same class is called constructor chaining.

Date:14.01.09

Question :
What is passed by ref and by value?

Give Your Answer

Answer:
When we make a call to the method, we may pass some values in the parameter
list. When we pass the actual value of the variable, it simply pass the copy
of the variable not actual value. Hence change in the copy of that variable
will not affect the actual value of that variable.

When we passed the object reference into the parameter list in to a method
call, we are actually passing the copy of bits that refer to the object
somewhere into the memory not actual value of the object. If we modify the
object using the reference of that object will also affect the actual value of
that passed object.

Question :

Explain difference between Constructer and a method

Give Your Answer

Answer:
Constructors are the special member, they do not have a return type. We can
call the methods explicitly but constructors are called automatically when we
create the object using the new operator. The purpose of constructor is to
allocate the memory to the object and initialize the class' variables. If you
don't provide the constructor in your class, the compiler will insert the
default constructor.

Why threads block or enters to waiting state on I/O?


Give Your Answer

Answer:
Threads block or enters to waiting state on I/O, so that other threads may
execute while the i/o
Operation is performed.

Date:14.01.09
Question :
What are transient variables in java?

Give Your Answer

Answer:
A transient variable is a variable that may not be serialized. It is not
stored as part of its objects persistent state. The value of the variable
can't be written to the stream instead when the class is retrieved from the
ObjectStream the value of the variable becomes null.

Question :

What is List interface ?

Give Your Answer

Answer:
List is an ordered collection of elements. The user of this interface has
precise control over where in the list each element is inserted. The user can
access elements by their integer index. Unlike sets, lists typically allow
duplicate elements. The List interface includes operations for the following:

* Positional access
* Search
* Iteration
* Range-view

Useful methods of the List Interface:

* add()
* clear()
* contains()
* get()
* isEmpty()
* listIterator()
* remove()
* size()
Date:14.01.09

Question :
What is the difference between yield() and sleep()?

Give Your Answer

Answer:
Thread.sleep(1000) method hands over the control to other thread for a
particular time period. Whereas Thread.yield() method causes the currently
executing thread object to temporarily pause and allow other threads to
execute according to the scheduling algorithm the CPU is running on.

Date:14.01.09

Question :
Can we call finalize() method ?

Give Your Answer

Answer:
No! The finalize method is invoked by the JVM/GarbageCollector on Objects
which are no longer referenced.

Date:14.01.09

Question :
What is the initial state of a thread when it is created and started?

Give Your Answer


Answer:
The thread is in ready state.

Can we declare an anonymous class as both extending a class and implementing


an interface?

Give Your Answer

Answer:
No. An anonymous class can extend a class or implement an interface, but it
cannot be declared to do both

Date:14.01.09

Question :
What is the differences between boolean & operator and && operator?

Give Your Answer

Answer:
When we use boolean & operator between the two operands then both the operands
are evaluated. If we are using the && operator between the two operands then
second operand is evaluated if the first operand is true.

Date:15.01.09

Question :
What is an abstract method ?

Give Your Answer


Answer:
An abstract method does not have a body. It contains only method signature
terminated by a semicolon instead of curly braces. Abstract method can be
declared only within the abstract class or within the interfaces. The
definition to the abstract method will be provided by the class which extends
the abstract class or implements the interface.

Date:15.01.09

Question :
what is a the difference between System.err and System.out

Give Your Answer

Answer:
The System.out writes to the "standard output". The System.err writes to
"standard error". These two streams are setup by the operating system when the
Java program is executed, and can be redirected with the uses of "|", ">",
etc. on the command line. You can redirect the output of the System.out to any
other file. The following example can help to understand the concept :

public class Test{


public static void main(String args[]){
System.out.println("Output of System.out");
System.err.println("Output of System.err");
}
}

First Execution -
C:\>java Test
Output of System.out
Output of System.err

Second Execution -
C:\>java Test > abc.txt
Output of System.err

In the second execution we diverted only the std output stream and std err
stream remained unchanged. i.e., by this way, we can handle error stream
separately.

Date:15.01.09
Question :
What is the difference between synchronized block and synchronized method ?

Give Your Answer

Answer:
Both the synchronized method and block are used to acquires the lock for an
object. When you mark a method synchronized, then you are forcing every thread
which calls that method to lock the monitor. If you expect a synchronized() {}
block in the calling code, it is possible that some code which calls your
method might neglect to
use synchronized() and end up with a threading problem in your program.
synchronized code always use objects as locks to prevent other threads from
entering the synchronized block. For instance methods, they are synchronized
on the 'this' reference, and for static methods they are synchronized on the
instance of the Class object method belongs to. Best practice is to minimize
the code inside synchronized blocks because they prevent concurrent threads
from executing - losing any advantage of multi-threaded applications.
Synchronized blocks help let those portions of a method that do not access
shared resources to be run simultaneously while still keeping those parts that
need to be shared thread-safe.

Question :

How can you force garbage collection in java?

Give Your Answer

Answer:
You can not force the JVM for the garbage collection. However you can call the
System.gc() method in your program to tell the JVM that it may the time to
perform garbage collection. But it is upto the JVM that if will call the
System.gc() method or not. There is no way to force the JVM, it works fine
without programmer's intervention.

Date:15.01.09

Question :
How can you call a constructor from another constructor ?

Give Your Answer

Answer:
Yes, we can call the constructor but within the another constructor of the
same class using the this().

Date:15.01.09

Question :
How can you call the constructor of super class ?

Give Your Answer

Answer:
We can call the superclass constructor by making a call to super() in the
subclass constructor.

Date:15.01.09

Question :
What must be the order of catch blocks when catching more than one exception?

Give Your Answer

Answer:
When you use multiple catch blocks, it is important to remember that exception
subclasses must come before any of their superclasses. This is because a catch
statement that uses a superclass will catch exceptions of that type plus any
of its subclasses. Thus a subclass would never be reached if it came after its
superclass. Further, in Java, unreachable code is an error.

Date:15.01.09

Question :
How can we call a method or variable of the super class from child class ?

Give Your Answer

Answer:
We can use super.methodNme() or super.variableName.

Question :

What is difference between jdk1.4 and jdk1.5?

Give Your Answer

Answer:
Following is added into jdk1.5 .which was not into jdk1.4:
Java Language Features
Generics
Enhanced for Loop
Autoboxing/Unboxing
Typesafe Enums
Varargs
Static Import
Metadata (Annotations)
Virtual Machine
Class Data Sharing
Garbage Collector Ergonomics
Server-Class Machine Detection
Thread Priority Changes
Fatal Error Handling
High-Precision Timing Support

So many other new features has been added.

Question :
What must a class do to implement an interface?

Give Your Answer

Answer:
If a class implements the interface, it must provides the definition to all
the methods declared in the interface or it must be the abstract class. If it
is an abstract class then the first concrete subclass must provides the
definition to the interface's mathods and abstract methods of the abstract
class.

Date:15.01.09

Question :
What is the difference between notify_and notifyAll method ?

Give Your Answer

Answer:
THe notify() method wakes up a single thread waiting on the object and passes
the control of the monitor to it. The notifyAll() method will wake up all the
threads waiting on the object and will select a thread to pass control to it.
The unselected thread will again go back to sleep
in the JVM scheduler list and they will need yet another call to notifty (or
notifyAll) in order to wake them up. The notifyAll() method is the same as the
notify() method. The only difference is that in this case all the threads from
the non-empty wait set of the object are removed and are re-enabled for thread
scheduling in stead of only one thread from the wait set being picked
arbitrarily, removed, and re-enabled for thread scheduling as is the case in
notify() method.

Date:15.01.09

Question :
What does wait method do ?

Give Your Answer


Answer:
The wait() method is defined in the Object class. The method should only be
called by a thread that has ownership of the object's monitor, which usually
means it is in a synchronized method or statement block.

Threads - wait() method do :

* the wait() method causes a thread to release the lock it is holding on


an object; allowing another thread to run.
* the wait() method is defined in the Object class.
* wait() can only be invoked from within synchronized code.
* it should always be wrapped in a try block as it throws IOExceptions.

There are actually three wait() methods

1. wait()
2. wait(long timeout)
3. wait(long timeout, int nanos)

The timeout is measured in milliseconds. when wait() is called, the thread


becomes disabled for scheduling and lies dormant until one of four things
occur:

1. another thread invokes the notify() method for this object and the
scheduler arbitrarily chooses to run the thread
2. another thread invokes the notifyAll() method for this object
3. another thread interrupts this thread
4. the specified wait() time elapses

Date:15.01.09

Question :
What are the different states of a thread ?

Give Your Answer

Answer:
The different stated of a thread :
* NEW : A Fresh thread that has not yet started to execute.
* RUNNABLE : A thread that is executing in the Java virtual machine.
* BLOCKED : A thread that is blocked waiting for a monitor lock.
* WAITING : A thread that is wating to be notified by another thread.
* TERMINATED : A thread whos run method has ended.
Date:15.01.09

Question :
What is the difference between static and non static inner class ?

Give Your Answer

Answer:
A non-static inner class may have object instances that are associated with
instances of the class's outer class. A static inner class does not have any
object instances.

Question :

What is the difference between readers and streams?

Give Your Answer

Answer:
The Reader/Writer classes is character-oriented and the
InputStream/OutputStream classes is byte oriented.

Date:15.01.09

Question :
Why we cannot override static methods?

Give Your Answer

Answer:
Static methods are class bound rather than runtime object type bound. That
means they cannot be overridden since polymorphism doesn't hold. We can't
override the static methods. We know overriding depends upon the inheritance.
Since the static methods are not inherited, hence we can not override static
methods. If u try to that, you are actually redefining the superclass version
of the static method, this is not an override.

Date:15.01.09

Question :
When does a compiler supplies a default constructor for a class?

Give Your Answer

Answer:
If a class has no constructors, then the compiler provides a default
constructor for that class.

Date:15.01.09

Question :
What will happen if an exception is not caught ?

Give Your Answer

Answer:
An uncaught exception results in the uncaughtException() method of the
thread's ThreadGroup being invoked, which eventually results in the
termination of the programin.

Date:15.01.09

Question :
What are the different ways in which a thread can enter into waiting state?

Give Your Answer


Answer:
A thread can enter into waiting state in 3 ways:
* sleep() method.
* wait() method.
* suspend() method.

Question :

What is a ResourceBundle class?

Give Your Answer

Answer:
Resource bundle used to contain locale-specific objects. When your program
needs a locale-specific resource, a String for example, your program can load
it from the resource bundle that is appropriate for the current user's locale.
This allows you to write programs that can:

* be easily localized, or translated, into different languages.


* handle multiple locales at once.
* be easily modified later to support even more locales.

The Java ResourceBundle class eases the process of separating localized


resources from an application's source code, but you may want to extend the
ResourceBundle class to better fit your needs.

Question :

What is the difference between the prefix and postfix forms of the ++
operator?

Give Your Answer

Answer:
Prefix ++ operator first increments the value of operand by 1 and then return
the value. Postfix ++ operator first reutrn the value and then increments the
value of operands by 1.

Date:15.01.09
Question :
What is the difference between a switch statement and an if statement?

Give Your Answer

Answer:
Both the statements provides the condition checking of the expressin but
Switch statement reduces the complexity of using the multiple if-else clause.

Sponsored Ads

Total Questions:-281 Goto Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22


23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57

R4R --->Java-->Core Java -->Core Java Subjective Questions And Answers


Core Java Subjective Questions And Answers

Page 39
Question :
What is a ResourceBundle class?

Give Your Answer

Answer:
Resource bundle used to contain locale-specific objects. When your program
needs a locale-specific resource, a String for example, your program can load
it from the resource bundle that is appropriate for the current user's locale.
This allows you to write programs that can:

* be easily localized, or translated, into different languages.


* handle multiple locales at once.
* be easily modified later to support even more locales.
The Java ResourceBundle class eases the process of separating localized
resources from an application's source code, but you may want to extend the
ResourceBundle class to better fit your needs.

Date:15.01.09

Question :
What is numeric promotion?

Give Your Answer

Answer:
Numeric promotion contexts allow the use of an identity conversion or a
widening primitive conversion. Numeric promotion is the conversion of a
smaller numeric type to a larger numeric type,so that integer and floating-
point operations may take place. In numerical promotion,byte, char, and short
values are converted to int values. The int values are also convertedto long
values, if necessary. The long and float values are converted to double
values. Numeric promotions are used to convert the operands of a numeric
operator to a common type so that an operation can be performed. In java, if u
are arithematic operator on the operands then :
* If either operand is of type double, the other is converted to
double.

* Otherwise, if either operand is of type float, the other is converted to


float.

* Otherwise, if either operand is of type long, the other is converted to


long.

* Otherwise, both operands are converted to type int.

Date:15.01.09

Question :
What is the difference between the prefix and postfix forms of the ++
operator?

Give Your Answer


Answer:
Prefix ++ operator first increments the value of operand by 1 and then return
the value. Postfix ++ operator first reutrn the value and then increments the
value of operands by 1.

Date:15.01.09

Question :
What is the difference between a switch statement and an if statement?

Give Your Answer

Answer:
Both the statements provides the condition checking of the expressin but
Switch statement reduces the complexity of using the multiple if-else clause.

Date:15.01.09

Question :
What is hashCode?

Give Your Answer

Answer:
The hashCode() is id number allocated to an object by JVM. Objects in Java
have hash codes associated with them. An object's hash code is a signed number
that identifies the object (for example, an instance of the parent class). An
object's hash code may be obtained by using the object's hashCode() method as
follows:

int hashCode = SomeObject.hashCode();

The method hashCode() is defined in the Object class and is inherited by all
Java objects. In order for the Java Collections to work properly (and
everything else in Java), the equals() and hashCode() methods must be
compatible. Here, compatible means that if equals() reports that two instances
are the same, then the hashCode() of both instances must be the same value.

What is the difference between Hashtable and HashMap ?

Give Your Answer

Answer:
The HashMap class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls. A hashmap is not synchronized and faster
than hashtable. HashMap does not guarantee that the order of the map will
remain constant over time.

Question :

What is object cloning?

Give Your Answer

Answer:
Object cloning means creating the identical object of any object. If you say :

obj1=obj2;

In the above statement obj1 is not actually making another copy of object, it
simply makes the copy of reference bits. For this purpose java provides the
clone() method for object cloning. This method is defined by the Object class.

Question :

What are the restrictions placed on static method ?

Give Your Answer

Answer:
Static method hava some of the following restrictions :
* Static methods can not be overridden.
* Static methods can only be invoked directly without object reference
within the same class and with the class name in another class.
* There is only one copy of static method for the entire class.
* They are available before creating the instance of the class.
* Static method can't be declared as final or abstract.

Question :

Strings are immutable. But String s="Hello"; String s1=s+"World" returns


HelloWorld how ?

Give Your Answer

Answer:
String s="Hello";
String s1=s+"World";
In the second line above, We are trying to concatenating the "Hello" and a new
strign object "World". Here a new object is created "HelloWorld" and returned
to the reference s1. Since string objects are immutable, the reference s is
still pointing to "Hello".

Date:15.01.09

Question :
What is classpath?

Give Your Answer

Answer:
The classpath is the connection between the Java runtime and the filesystem.
It defines where the compiler and interpreter look for .class files to load or
the CLASSPATH is an environment variable that tells the Java compiler
javac.exe where to look for class files to import or java.exe where to find
class files to interpret. The class path can be set using either the
-classpath option when calling an SDK tool (the preferred method) or by
setting the CLASSPATH environment variable.

Date:15.01.09

Question :
What is path?

Give Your Answer

Answer:
A path tells the java compiler and java interpreter where ot find the classes
they need to execute or import. Multiple entries in the class path are
separated by a semicolon on Windows (;) and by a colon on UNIX (:).

Date:15.01.09

Question :
What is java collections?

Give Your Answer

Answer:
The Java collections framework is a set of classes and interfaces that
implement commonly reusable collection data structures. A collection framework
includes :
* Collection Interface
* Iterator Interface
* Set Interface
* List Interface
* ListIterator Interface
* Map Interface
* SortedSet Interface
* SortedMap Interface
* HashSet & TreeSet Classes
* ArrayList & LinkedList Classes
* HashMap & Treemap Classes Vector & Stack Classes

Date:15.01.09

Question :
Can we compile a java program without main?
Give Your Answer

Answer:
Yes! We can compile our java program without main() method.

Question :

What is static initializer block? What is its use?

Give Your Answer

Answer:
After method and constructor, Initialization blocks are the third place where
the operations can be performed. Initialization block do not have identifier
and they are of two types :

* Instance initialization block.


* static initializaton block.

Static initialization block starts with the keyword static with opening and
ending curly braces. Static initialization block is used to initialize the
static variable of the class because they are available before any instance
created of the class i.e. before executing the constructor. Hence static
initialization block are the right place to initialize the static variable.

Date:15.01.09

Question :
How does a try statement determine which catch clause should be used to handle
an exception?

Give Your Answer

Answer:
When an exception is thrown within the try block the JVM start searching from
the first catch block associated with the try block, the first matching catch
block is executed and rest are ignored.

Question :
If a class doesn't have any constructors, what will happen?

http://r4r.co.in/answer.php?id=1646Answer:
If a class doesn't have any constructors, the compiler will supply the default
constructor.

Question :
What will happen if a thread cannot acquire a lock on an object?

Give Your Answer

Answer:
If a thread cannot acquire a lock on an object, it will enter to the waiting
state until it acquire the lock on that object.

What is the difference between Exception and Error ?


Answer:
Exceptions are the abnormal condition that you can handle by your program, but
Error is an unrecoverable condition that can be handled by the program at
runtime. Both Exceptiona and Error classes are drived from the class Trowable.
Java running out of memory is an Error and can not be handled by the program.

Question :
What is the difference between List, Set and Map?

Give Your Answer

Answer:
List is an ordered collection of elements by index. Key methods of List are :
get(int index), indexOf(Object o), add(int index, Object o), etc.

A Set cares about Uniqueness, it doesn't allow duplicates elements. The


equals() method helps you to find out whether two objects are identical.

A map stores the elements in the form of Key/Value pairs. Here key and value
both are objects. A map cares about unique key (unique ID) to a specific
value. You can search value in a Map by giving its key.

Date:16.01.09

Question :
What is the difference between Comparable and Comparator ?
Give Your Answer

Answer:
The comparable interface should be used when the current object is to be
compared to objects of its type only.
The comparator should be used when some external class is taking your class as
a parameter for some comparison operation and it doesn't know how to compare
the objects and expects you to give it. You have a set of objects where you
want to sort it in both ascending and decending order. Just Comparable will
not help you in this. Here you can implement your own comparator and pass it
to the sorting algorithm to use.

Question :

How will you define an interface?

Give Your Answer

Answer:
The following syntax is used to define the interface :
accessModifier interface InterfaceName{
dataType var1;
dataType var2;
..............
..............
void method1();
void method2();
..............
..............
}

Here accessModifier may be default or public.


Interface may contain constant variables. These variables are implicitly
public static final, you don't have to type it explicitly.
Interface can have only public abstract methods, you dont have to type public
abstract modifiers explicitly.

Question :
How will you define an abstract class?

Give Your Answer

Answer:
An abstract class have abstract modifier in its declaration. An abstract class
can contain instance variable, methods that can be concrete methods and
abstract methods. An abstract class may not have any abstract method, that
does not mean that it is not an abstract class.

Example :

public abstarct AbstractClass{


// instance variable
int a;
int b;
//instance methods
public int getValue(){}
public void setValue(int){}
//abstract method
public int getMaxValue();
}

Question :
What is a JVM heap?

Give Your Answer

Answer:
The JVM heap is where the objects of a Java program live. The JVM's heap
stores all objects created by an executing Java program. Objects are created
by Java's "new" operator, and memory for new objects is allocated on the heap
at run time. The JVM heap size determines how often and how long the VM spends
collecting garbage. A Java Virtual Machine on 32-bit operating systems
typically has a maximum heap size of 64Mb. You can modify the JVM heap size .

Question :

Why ArrayList is faster than Vector?

Give Your Answer

Answer:
Arraylist is faster than the Vector because ArrayList doesn't have
synchronisation overhead, i.e. ArrayList has synchronized methods.

Question :

Can a top level class be private or protected?

Answer:
No! A top level class can't be private or protected, it can only be either
public or default.

Question :

What is an Object and how do you allocate memory to it?


Answer:
An object is a runtime entity. It is an instance of the class and have its own
state, made up of values assigned to all variables of its class collectively.
An object will hava access to all the behaviours(methods) of its class.

The object can be allocated memory using the "new" keyword. For Example :
//class declaration
class CrateObject{
}
//Object creation
CreateObject o = new CreateObject();

Question :

What is a thread group?

answer:
A thread group represents a set of threads. Every Java thread is a member of a
thread group. In addition, a thread group can also include other thread
groups. Threads can only access the ThreadGroup to which they belong. Thread
groups provide a mechanism for collecting multiple threads into a single
object and manipulating those threads all at once, rather than individually. A
tree structure can be formed from ThreadsGroups containing other ThreadGroups.
Java provides the ThreadGroup class for creating and managing the thread
groups. The ThreadGroup class provides two constructors :

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

You might also like