Wednesday, June 24, 2015

Interview Questions in JAVA

Interview Questions in JAVA


Question: Can Java thread object invoke start method twice?

Code:
package com.java2novice.exmpcode;

public class MyExmpCode extends Thread{

 public void run(){
  System.out.println("Run");
 }
 public static void main(String a[]){
  Thread t1 = new Thread(new MyExmpCode());
  t1.start();
  t1.start();
 }
}
Answer:

No, it throws IllegalThreadStateException

Question: Give the list of Java Object class methods.

Answer:

 clone() - Creates and returns a copy of this object.
 equals() - Indicates whether some other object is "equal to" this one.
 finalize() - Called by the garbage collector on an object when garbage collection
   determines that there are no more references to the object.
 getClass() - Returns the runtime class of an object.
 hashCode() - Returns a hash code value for the object.
 notify() - Wakes up a single thread that is waiting on this object's monitor.
 notifyAll() - Wakes up all threads that are waiting on this object's monitor.
toString() - Returns a string representation of the object.
 wait() - Causes current thread to wait until another thread invokes the notify()
 method or the notifyAll() method for this object.

Question: Can we call servlet destroy() from service()?

Answer:
As you know, destroy() is part of servlet life cycle methods, it is used to kill theservlet instance. Servlet Engine is used to call destroy(). In case, if you call destroy method from service(), it just execute the code written in the destroy(), but it wont kill the servlet instance. destroy() will be called before killing the servlet instance by servlet engine.

Question: Can we override static method?

Answer:
We cannot override static methods. Static methods are belongs to class, not belongs to object. Inheritance will not be applicable for class members

Question: Can you list serialization methods?

Answer:
Serialization interface does not have any methods. It is a marker interface.
It just tells that your class can be serializable.

Question: What is the difference between super() and this()?

Answer:
super() is used to call super class constructor, whereas this() used to call
constructors in the same class, means to call parametrized constructors.

Question: How to prevent a method from being overridden?

Answer:
By specifying final keyword to the method you can avoid overriding in a subcalss. Similarlly one can use final at class level to prevent creating subclasses.

Question: Can we create abstract classes without any abstract methods?

Answer:
Yes, we can create abstract classes without any abstract methods.

Question: How to destroy the session in servlets?

Answer:
By calling invalidate() method on session object, we can destory the session.

Question: Can we overload the main method in Java?

Answer:
You can overload the main() method, but only public static void main(String[] args)
will be used when your class is launched by the JVM. 
For example:

public class Test {
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}
That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

Question: Can we have static methods in interface?

Answer:
By default, all methods in an interface are decleared as public, abstract. It will never be static. But this concept is changed with java 8. Java 8 came with new feature called "default methods" with in interfaces click here for more details.

Question: What is transient variable?

Answer:
Transient variables cannot be serialized. During serialization process,transient variable states will not be serialized. State of the value will be always defaulted after deserialization.

Question: Incase, there is a return at the end of try block, will execute finally block?

Answer:
Yes, the finally block will be executed even after writing return statement at the end of try block. It returns after executing finally block.

Question: What is abstract class or abstract method?

Answer:
We cannot create instance for an abstract class. We can able to create instance for its subclass only. By specifying abstract keyword just before class, we can make a class as abstract class.
public abstract class MyAbstractClass{
}
Abstract class may or may not contains abstract methods. Abstract method is just method signature, it does not containes any implementation. Its subclass must provide implementation for abstract methods. Abstract methods are looks like as given below:
public abstract int getLength();

Question: What is default value of a boolean?

Answer:
Default value of a boolean is false.

Question: When to use LinkedList or ArrayList?

Answer:
Accessing elements are faster with Array List, because it is index based.But accessing is difficult with Linked List. It is slow access. This is to access any element, you need to navigate through the elements one by one. But insertionand deletion is much faster with Linked List, because if you know the node, just change the pointers before or after nodes.Insertion and deletion is slow with Array List, this is because, during these operations Array List need to adjust the indexes according to deletion or insertion if you are performing  on middle indexes. Means,an Array List having 10 elements, if you are inserting at index 5, then you need to shift the indexes above 5 to one more.

Example:
01. ArrayList arrayList = new ArrayList();
02. LinkedList linkedList = new LinkedList();
03.
04.// ArrayList add
05.long startTime = System.nanoTime();
06.
07.for (int i = 0; i < 100000; i++) {
08. arrayList.add(i);
09.}
10.long endTime = System.nanoTime();
11.long duration = endTime - startTime;
12. System.out.println("ArrayList add: " + duration);
13.
14.// LinkedList add
15. startTime = System.nanoTime();
16.
17.for (int i = 0; i < 100000; i++) {
18. linkedList.add(i);
19.}
20. endTime = System.nanoTime();
21.duration = endTime - startTime;
22. System.out.println("LinkedList add: " + duration);
23.
24.// ArrayList get
25. startTime = System.nanoTime();
26.
27.for (int i = 0; i < 10000; i++) {
28. arrayList.get(i);
29.}
30. endTime = System.nanoTime();
31.duration = endTime - startTime;
32. System.out.println("ArrayList get: " + duration);
33.
34.// LinkedList get
35. startTime = System.nanoTime();
36.
37.for (int i = 0; i < 10000; i++) {
38. linkedList.get(i);
39.}
40. endTime = System.nanoTime();
41.duration = endTime - startTime;
42. System.out.println("LinkedList get: " + duration);
43.
44.
45.// ArrayList remove
46. startTime = System.nanoTime();
47.
48.for (int i = 9999; i >=0; i--) {
49. arrayList.remove(i);
50.}
51. endTime = System.nanoTime();
52.duration = endTime - startTime;
53. System.out.println("ArrayList remove: " + duration);
54.
55.// LinkedList remove
56. startTime = System.nanoTime();
57.
58.for (int i = 9999; i >=0; i--) {
59. linkedList.remove(i);
60.}
61. endTime = System.nanoTime();
62.duration = endTime - startTime;
63. System.out.println("LinkedList remove: " + duration);
After executing you will get to know that adding and removing is faster in LinkedList than arrayList but getting elements is faster in arrayList

Question: What is daemon thread?

Answer:
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care  of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
Example:
public class ThreadMainEx {
public static void main(String[] args) {
System.out.println("Introducing Demon Thread Example");
Thread t = new Thread();
t.setDaemon(true);
t.start();
}}

Question: Does each thread in java uses seperate stack?

Answer:
In Java every thread maintains its own separate stack. It is called Runtime Stack but they share the same memory.

Question: What is the difference between Enumeration and Iterator?

Answer:
The functionality of Enumeration and the Iterator are same. You can get remove() from
Iterator to remove an element, while while Enumeration does not have remove() method.
Using Enumeration you can only traverse and fetch the objects, where as using Iterator we can
also add and remove the objects. So Iterator can be useful if you want to manipulate the list
and Enumeration is for read-only access.Enumeration are only applicable for legacy classes
e.g Hash table, Vector.

Question: Find out below switch statement output.

Code:
public static void main(String a[]){
 int price = 6;
 switch (price) {
  case 2: System.out.println("It is: 2");
  default: System.out.println("It is: default");
  case 5: System.out.println("It is: 5");
  case 9: System.out.println("It is: 9");
 }
}
Answer:
It is: default
It is: 5
It is: 9

Output Description:In the above switch case the case 6 is not available .So, it goes to the default case and firstlyit will print the default case.Next Remaining two statements will also be printed because there is no break statement after the end of  the default statement.
Reason:If there is a break in between then the switch will return with the defined case. 
If there is no break, switch will execute from the first matched case till the end.

Question: Does system.exit() in try block executes code in finally block?

Code:
 try{
  System.out.println("I am in try block");
  System.exit(1);
 } catch(Exception ex){
  ex.printStackTrace();
 } finally {
  System.out.println("I am in finally block!!!");
 }

Answer:
It will not execute finally block. The program will be terminated
after System.exit() statement.

Question: What is fail-fast in java?

Answer:
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behaviour with iterators. In case, you have called iterator on a collection object, and another thread tries to modify the collection object, then concurrent modification exception will be thrown. This is called fail fast.




No comments:

Easy Way to Handle Android Notifications

Android Notifications Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persist...