Thursday, March 12, 2009

Important Java interview Questions

Q1. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.

Q2. What is the difference between a while statement and a do statement?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

Q3.What is the Locale class?
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Q4.Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Q5. Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.

Q6.What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example
int i = 1000;
long j = i; //Implicit casting
Is sizeof a keyword in java?
The sizeof operator is not a keyword.

Q7.What is a native method?
A native method is a method that is implemented in a language other than Java.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

Q8.What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

Wednesday, February 11, 2009

Important Java interview Questions

What if the static modifier is removed from the signature of the main method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

  • The global variables breaks the referential transparency
  • Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

Sunday, January 18, 2009

Java Interview Questions

Q1. What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.

Q2. What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

Q3. If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()

Q4.What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Q5.Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

Q6.What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables - the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
public class EqualsTest {

public static void main(String[] args) {

String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println("== comparison : " + (s1 == s5));
System.out.println("== comparison : " + (s1 == s2));
System.out.println("Using equals method : " + s1.equals(s2));
System.out.println("== comparison : " + s3 == s4);
System.out.println("Using equals method : " + s3.equals(s4));
}
}

Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

Monday, October 13, 2008

Revision Quiz

1. A ____ object can store and retrieve “value” objects indexed by “key” object.
Ans: Hashtable

2.Wrapper class objects contain mutable values.
True/False?
Ans: False

3.A Vector can hold object references or primitives types.
Ans: False

4.Hashtable class implements which of the following interfaces?Ans: Map

5.String s1=new String(“MyString”);String s2=new String(“MyString”);s1==s2 will return ___.

Ans: False

6.Float.NaN or Double.NaN refers to ___
Ans: Not a number

7.The java.lang.System is a ___ class.

Ans: final

8.The ___ class is a wrapper around int data type in java.

Ans: Integer

9.java.lang.Double is a concrete subclass of abstract class java.lang.Number.
True/False
Ans:True

10.What happens when you try to compile and run the following code snippet?
public class Wrapper{
public static void main(String []a)
{
String s=”15.25”;
try {
int number=Integer.parseInt(s); //line 1
System.out.println(number); //line 2
}
catch(NumberFormatException nfe)
{
System.out.println(“sorry”);
}
catch(Exception e){ }
}
}
A) It will compile fine and display 15 when run.
B) It will compile fine and display Sorry when run.
C) It will not compile.
D) It will compile fine nothing will be displayed when run
Ans: B

11.The java.lang.Math class has ___ constructor.

A) public
B) private
C) protected
Ans: B

12.A Vector maintains object references in the order they were added.
Ans: True

13.The String class represents a mutable string

Ans: False

14.The parent class of both Integer and Character class is Number class
Ans: False

15.What happens when you try to compile and run the following code snippet?

public class WrapChar
{
public static void main(String []a)
{
Character wrapChar=new Character(“c”);//line1
System.out.println(wrapChar);//line 2
}
}
A) Compile time error at line 1
B) Compile time error at line 2
C) Compile fine and display c when run
D) Compile fine but throws RuntimeException
Ans: A

Tuesday, September 9, 2008

LAST MINUTE REVISION NOTES

The tips to attend the exam SCJP 5

1. Check for any obvious complier errors first like two else statements , accessing ofprivate variable/method , accessing a variable declared in a for loop outside the for loop.

2. If you try to unbox a null Integer value to int , it will result in a NullPointerException.

3. If method having the same name as Class name and having a return type is not a constructor but a ordinary method.

4. Map is the only interface that does not extend Collection. List , Set and Queue extends the Collection interface.

Collection is a interface ,
Collections is Class which extends Object class.

Map: key , value pair
Hashtable , HashMap , LinkedHashMap , TreeMap

Set : unique values
HashSet , TreeSet , LinkedHashSet

List : List of values allows duplicates, accessed by index
ArrayList , Vector , LinkedList

Queue : stack or queue. to-do list. priority queue is sorted based on the natural order or based on the object of Comparator or Comparable.LinkedList , PriorityQueue
The twins clases.

a. The Hashtable and HashMap: Both are atmost same except that Hashtable methods are synchronized and it does not allow null key/value, whereas HashMap allows one null key and many null values and its methods are not synchronized . The Hashtable is oldest class in java. The t in Hashtable is indeed a small letter rather than capital letter.

b. The Vector and ArrayList have same functionalities except that Vector Methods are synchronized , while ArrayList methods are not. Both ArrayList and Vector implementes RandomAccess interface (which is marker interface having no methods) as of java 5

c. The LinkedList can be used to access values in insertion order. The LinkedHashMap can be used access values in insertion or access order. The LinkedList implements Queue(as of java 5) and List. The LinkedList now implements queue methods like offer, poll and peek.

d. The TreeSet , TreeMap and PriorityQueue sorts the values.

e. The HashSet , Hashtable and HashMap are unordered and unsorted. if you add n values in these Collection objects , iteration will not give you a particular ordering ie no insertion or access or natural order. It iterates in a random order.

f. The LinkedHashSet is ordered form of HashSet , The LinkedHashMap is the ordered form of HashMap.

g. the offer() method adds a element in queue. the poll method returns the first method and removes it from queue. the peek just returns the first method from queue. The higgest priority is stored first in PriorityQueue. if you poll each value from PriorityQueue then values returned will be of Higgest proririty to lowest priorirty.

h. The Object of class which need to be added in HashSet , Hashtable , LinkedHashSet or HashMapt must override the below methods
The exception are all Wrapper classes. The class Number , StringBuffer and StringBuilder.

For example object of Student class need to be added in LinkedHashSetA student class contains id , name. As id is a primaray key , we should not have rwo students with the same id. if the Student class does not override the above methods then

Student d = new Student(44); //44 is id
Student d 1= new Student(44); //44 is id
public int hashCode(){}
public boolean equals(Object o){}
public boolean equals(Object o { if (o instanceof Student) {
Student t= (Student) o;
if(o.getId() ==this.id ) {
return true;
} //if
} //ifreturn false;
} //method
public int hashCode() {
//use any of the below
return id*4;
return id;
return 1038; //any constant
//do no use any of the below
Random r =new Random(44);
return r.nextInt();
//here t is transient variable
return t*id;
}
if above method is implemented then d and d1 will be same object.
both d and d1 are different object accoring to the LinkedHashSet , as a result both will be added to the Set

i. The Object of class which need to be added in TreeMap , TreeSet and PriorityQueue must implement Comparable or Comparator interface

j. java.lang.Comparabl e declaresompareTo( ) and accepts one Object as argument.k. java.util.Comparato r declares compare() which accepts 2 Object as argument.

l. in generics if you declare a variable it must be instantiated with the same type or no type at all

//valid

Listlisto1 =new ArrayList ();
List listo2 =new ArrayList();

List listo3 =new ArrayList ();
List list3 =new ArrayList();
m1(list01);/ /error
m2(list01);/ /ok
m1(list02);/ /error
m2(list02);/ /ok
m1(list03);/ /ok
m2(list03);/ /ok
m1(list3);// ok
m2(list3);// error

//invalid

List listo =new ArrayList(); //compiler error


// functions
static void m1( a) {}
static void m2( a) {}


//The argument that Child class can be applied to a parent class i s not at all applicable to generics . if you specified a type in the variable declaration it must be followed while instantiating also.

In the Exam , there will be drag-drop quetion . in which there will be 4 variable instanciated with the genreic and passed as arguemnt to a function. you have drag and drop , if the code compiles or not.

m.
public class {} and
public class {}
are invalid syntax and leads to compiler error

but it can be defined as

public class {} or
public class {}
public class {} public class {}
public T getObject() {} //correct
public T computeArrays( Y y) {}
//correct, the font-size of s is increased to differentiate from the interface Collection
//here Y is the argument and T is the return type.

5. For garbage collection , you must focus on the value and its reference . there may be a question . which is earliest line in which the value referred by object in line 5(some line) is eligible for garbage collection . The reference variable will be given other values in the consecutive steps but focus if the value which was created/defined in line 5 (example) is referenced by any other variable. The variable can be instance or local variable. if it is a local variable , its scope will be till the method ends but except in the situation the value is returned.
For example below :

Object o= new Object//line 5
Object s =o;//line 6
// the value created in line 5 is referred by s

case 1 .

o = new Object(); //7 //o is set to different value
s=null; //8 s is null or
s = new Object(); // s is set to a new value
}
so old value has no reference.

here the value created in line 5 will be eligible for gc after line 5

case 2.

o= new Object();//5
Object s =o;//6
o = new Object();//7
return s;//8 }
The value created in line 5 will not be eligible for garbage collection even after the method has ended as it is returned.

case 3:

private Object o;
public void data() {
Object o = new Object();//1
doSomething( o);//2
o = new Object();//3
o=null;//4
doSomething( null);//5
Object s = new Object();//6
Object nothing = new Object();//7
return s;//8
}//9

In the above example value created in line 1 is eligible for garbage collection after the line 5. The value created in the line 3 is eligible for garbage collection after the line 4.

The value created in line 6 will not be eligible for garbage collection even after the method ends as the value is returned. The value created in line 7 is eligible for garbage collection after the line 9.

public void doSomething( Object obj) {
o= obj;
}

Saturday, August 9, 2008

Serialization and Deserialization Important Tips


**For an object to be serialized, it has to implement either the java.io.Serializable or java.io.Externalizable interfaces, the latter being a subtype of Serializable.

---------------------------------------------------------------------

**Serializable is a marker interface: it specifies no methods and merely indicates an object that has serializable state.

-------------------------------------------------------------

**All subclasses of a Serializable class are also serializable.

--------------------------------------------------------------

**If a supertype of a Serializable object is not itself serializable, then the object can assume the responsibility for saving and reconstructing the supertype's state (public, protected, and package fields if they share a package).For this to work, the superclass must have a public no-arg constructor.

--------------------------------------------------------------

**Further, if an object at runtime refers to a nonserializable object, the serialization system will throw a NotSerializableException, since it cannot write the complete object graph to the serialized stream.

--------------------------------------------------------------

**If an object holds multiple references to another object, this second object is serialized only once, and subsequent references to it will include a handle as a reference instead.

---------------------------------------------------------------

**Along with instance data, the object serialization system writes a special object to the stream to represent the serializable object's class.

---------------------------------------------------------------

**This object is of the type java.io.ObjectStreamClass, and is essentially a descriptor for the Class object associated with the serializable object. It contains the class's name, its unique version number (serialVersionUID), and the class fields.

---------------------------------------------------------------

**In addition, it also has methods to obtain the actual class represented by this object, if, and only if, this class is already present in the local VM:

Class forClass() : If there is no class identified in the local VM that corresponds to this ObjectStreamClass, then a null value is returned.

------------------------------------------------------------------

**Not all objects are suitable for serialization:

1.Threads, for instance, do not have state that can later be recreated. (Actually, it is possible, but very difficult, to do so.)

2.There can also be objects that should not be serialized for semantic reasons. Even if an object is serializable, you may not need to write all object fields to the stream during serialization. For instance, a variable that loses its meaning in a different execution context (such as something indicating the current time) should be marked transient, and will instead be initialized to its default value when reading it from the stream.

----------------------------------------------------------------

**If instances of a class need a special way to serialize their state, that class can implement the Externalizable interface, which mandates two methods:
void readExternal(ObjectInput inputStream);

void writeExternal(ObjectOutput outputStream);

-------------------------------------------------------------

**The main difference between Externalizable and Serializable is that the latter serializes, by default, the entire object graph, including states of an object's superclass. While in the former Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

Externalizable gives you complete control over the serialization process.

Serialization allows you to create a JVM-independent binary representation of an in-memory Java object. This external representation may be used to transfer or store the object and to recreate it in another JVM.

--------------------------------------------------------------------

**Two streams in java.io--

1. ObjectInputStream

2. ObjectOutputStream

-- are run-of-the-mill byte streams and work like the other input and output streams. However, they are special in that they can read and write objects.

----------------------------------------------------------------

**Serializable has no methods but Externalizable has 2 methods: readExternal() and writeExternal()

----------------------------------------------------------------

You can use object serialization in the following ways:
· Remote Method Invocation (RMI) --communication between objects via sockets
· Lightweight persistence--the archival of an object for use in a later invocation of the same program.

---------------------------------------------------------------------

**Technique to protect sensitive data in classes :

Mark fields that contain sensitive data as private transient. transient and static fields are not serialized or deserialized.

Marking the field will prevent the state from appearing in the stream and from being restored during deserialization.

Since writing and reading (of private fields) cannot be superseded outside of the class, the class's transient fields are safe.

-------------------------------------------------------------

Accessor Types Public and Private

Question 1

Given :

public class Hello{
private int i = j;
private int j = 10;
public static void main(String args[]) {
System.out.println((new Hello()).i); }
}

Choose

1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing.
3. No error - The output is 0;
4. No error - The output is 10;

Answer is 2. It is because i is a private variable of Hello. Hence it cannot be accessed directly.

Question 2


Given :

public class Hello {
private int i = giveJ();
private int j = 10;
private int giveJ()
{ return j;
}
public static void main(String args[])
{ System.out.println((new Hello()).i);
}
}

Choose :
1. Compiler error complaining about access restriction of private variables of Hello.
2. Compiler error complaining about forward referencing. .
3. No Compilation error - The output is 0;
4. No Compilation error - The output is 10;


Answer 2 is correct. We cannot assign a value to instance varaible by calling the method.

Search Amazon for Best Books on Java J2EE

Blogarama

blogarama - the blog directory

Search your favourite topics

Google