Tuesday, August 19, 2014

Java

Java interview question

1) What is immutable object in java? Can you change values of a immutable object?
2) How to created an immutable object in Java? Does all property of immutable object needs to be final?
3) What is difference between string, string buffer and string builder? When to use them? 
4) Criteria To choose among string, string buffer and string builder?
5)  Why string class is final or immutable?
6)   Is java pass by reference or pass by value?
7).  What is outofmemoryerror in java? How to deal with java.Lang.outofmemoryerror error? 
8). What is the use of finally block? Is finally block in java guaranteed t be called? When finally block is NOT called?
9)   Why there are two date classes: one in java.util package and other in java.SQL
10)  What is marker interface?  How is it used in java?
11).   Why main() in java is declared as public static void main? What if the main method is declared as private?
12). What will happen if you call return statement or system.exit on try or catch block? Will finally block execute?
13).  Can you override private or static method in java?
14).   Does java support multiple inheritance?
15). What will happen if we put a key object in hash map which is already there?
16). Do you know how hash map works in java? How does get() method of HashMap works in Java?
17). What will happen if two different objects have same hash code?
18). How would you retrieve value object if two keys have same hash code?
19). What is deadlock?
20). How do you detect deadlock in java?
21). Write code which will result in deadlock?
22) How to avoid deadlock?
23). Can you access non static variable in static context?
24). What is difference between Hashtable and HashMap in java?
25). Difference between concurrenthashmap and hashmap?
26). What is difference between iterator and enumeration in java?
27).  Difference between vector and Arraylist in Java?
28). Linkedlist vs arraylist in java?
29) When to use linkedlist and arraylist in java?
30). What is difference between List and Set in Java?
31). How to check array for duplicate elements in java?


1) What is immutable object in java? Can you change values of a immutable object?

- a java object is considered immutable if it's state cannot be changed after it is created.

2) How to created an immutable object in Java? Does all property of immutable object needs to be final?

- to create an immutable object, you need to make the class final and all it's member final so that once object is created no one can modify it's state.

3) What is difference between string, string buffer and string builder? When to use them?

- string is immutable whereas string buffer and string builder objects are mutable.
- string buffer is synchronized whereas string builder is not synchronized.
- concatenation operator + is internally implemented by java using string buffer or string builder.

4) Criteria To choose among string, string buffer and string builder

- if object value does not change in scenario use string class as string object is immutable.
- if object value change and will only be modified from single thread, use a string builder as string builder is unsychronized(means faster)
- if object value may change and can be modified by multiple threads, use string buffer as string buffer is thread safe(synchronized)

5) Why string class is final or immutable?

- immutable objects are thread safe. Two threads can both work on immutable object at same time without any possibility of conflict
- security:  the system can pass on sensitive bits of read only information without worrying that it will be altered.
- you can create substrings without copying
- immutable objects are good fit for becoming hash table keys.

6) Is java pass by reference or pass by value?

- everything in java is pass by value.
- there is no such thing as pass by reference in java.

7) What is outofmemoryerror in java? How to deal with java.Lang.outofmemoryerror error?

- error is thrown when JVM cannot allocate an object because it is out of memory, and no more memory could be made available by garbage collector.
- two important types of outofmemoryerror are often encountered
- java.Lang.outofmemoryerror: java heap space
Quick solution is to add these flags to JVM command line when java runtime is started.
- Xms1024m -Xmx1024m
- java.Lang.outofmemoryerror: permgen space
The solution is to add these flags to JVM command line when java runtime is started.
-XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled

8) What is the use of finally block? Is finally block in java guaranteed t be called? When finally block is NOT called?

- finally is the block of code that is executed always.
- code in finally block will execute even if an exception will occur.
- finally block is not called in following conditions

If JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.

If thread executing try or catch code is interrupted or killed, the finally block may not execute though the application as whole comtinues.
If exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

9) Why there are two date classes: one in java.util package and other in java.SQL?

- java.util.date represents date and time of day, 
- java.SQL.date only represents a date
- java.SQL.time represents time of the day

10) What is marker interface? How is it used in java?

- market interface is design pattern, used with languages that provide runtime type information about objects.

11) Why main() in java is declared as public static void main? What if the main method is declared as private?

- public: main method is called by JVM to run the method to permit call from anywhere outside the application 
- static: when JVM makes call to main method there is no object existing for class being called thus it has to have static method to allow invocation from class
- void: java is platform independent language therefore if it will return some value then the value may mean different to different platforms 

If main method is declared as private then- program will compile properly but at runtime it will give "main method not public" error.

12) What will happen if you call return statement or system.exit on try or catch block? Will finally block execute?

- finally block will execute even if you put return statement in try or catch block 
- finally block won't run if you call system.exit from try or catch.

13) Can you override private or static method in java?

- you cannot override private or static method in java

14) Does java support multiple inheritance?

- java does not support multiple inheritance.

1) first reason is ambiguity around diamond problem.
Consider class A has foo method and then B and C derived from A and has their own foo method.
Class D derive from B and C using multiple inheritance. If we refer just foo compiler will not be able to decide which foo it should invoke.
This is also called Diamond problem as structure of this inheritance scenario is 4 edge diamond.
It's more of maintainable and clearer design is driving factor.

2) multiple inheritance does complicate the design and create problem during casting, constrictor chaining etc and given that there are not many scenarios where you need multiple inheritance, it's wise decision to omit for sake of simplicity.
 Also java avoids ambiguity by supporting single inheritance with interfaces.
Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity

15) What will happen if we put a key object in hash map which is already there?

- if you put same key again then it will replace old mapping because HashMap doesn't allow duplicate keys.

16) Do you know how hash map works in java? How does get() method of HashMap works in Java?

- hash map works in principle of hashing
- we have put(key,value)  and get(key) method for storing annd retrieving objects from HashMap.
- when we pass key and value object to put() method on Java HashMap, HashMap implementation calls hashCode method on key object and applies returned hash code into it's own hashing function to find bucket location for storing entry object.
- HashMap in java stores both key and value object as Map.Entry in bucket which is essential to understand retrieving logic.

17) What will happen if two different objects have same hash code?

- since hash code is same, bucket location would be same and collission will occur in HashMap.
- since HashMap uses linked list to store object, this entry(object of Map.Entry comprise key and value) will be stored in linkedList.

18) How would you retrieve value object if two keys have same hash code?

- after finding the bucket location, we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap.

19) What is deadlock?

- when two or more threads waiting for each other to release lock and get stuck for infinite time, situation is called deadlock. It will only happen in case of multitasking

20) How do you detect deadlock in java?

- I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock
- use j console, it will show you exactly which threads are get locked  and on which object.

21) Write code which will result in deadlock?

- public void method1(){
synchronized(String.class){
System.out.println("acquired lock on string.class object");

Synchronized(integer.class){
System.out.println("Acquired lock on integer.class object");
}
}

- public void method2(){
Synchronized(integer.class){
System.out.println("Acquired lock on integer.class object");
}

synchronized(String.class){
System.out.println("acquired lock on string.class object");
}
}

if method1() and method2() both will be called two or more threads, there is good chance of deadlock as if thread1 acquires lock on string object while executing method1() and thread2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on integer and string to proceed further which will never happen.

22) How to avoid deadlock?

- if you look the code above carefully, you may have figured out that real reason for deadlock is not multiple threads but way they access lock, if you provide ordered access then problem will be resolved, here is fixed version

- public void method1(){
Synchronized(integer.class){
System.out.println("Acquired lock on integer.class object");
}

synchronized(String.class){
System.out.println("acquired lock on string.class object");
}

- public void method2(){
Synchronized(integer.class){
System.out.println("Acquired lock on integer.class object");
}

synchronized(String.class){
System.out.println("acquired lock on string.class object");
}
}

Now there would not be any deadlock as both method is accessing the lock on Integer and String object in same order, so if thread A acquired lock on integer object, thread B will not proceed until thread A releases integer lock. 
Same way thread a will not be blocked even if thread B holds string lock as now thread B will not expect thread A to release integer lock to proceed further.

23) Can you access non static variable in static context?

- no you cannot access static variable non static context.

24) Fibonacci series with recursion example

- fibonacci series is series of natural number where next number is equivalent to sum of previous two numbers. Fn=fn-1 + fn-2
- first two numbers of fibo is always 1,1

25) What is difference between Hashtable and HashMap in java?

- hashmap is not thread safe while hashtable is thread safe collection.
- hashmap is not synchronized so it performs better than hashtable
- hashtable is obsolete class and you should be using concurrenthashmap in place of hashtable in java

26) Difference between concurrenthashmap and hashmap?

- concurrenthashmap do not allow null keys or null values while hashmap allows null keys.

27) What is difference between iterator and enumeration in java?

- only diffence between enumeration and iterator is iterator has a remove() method while enumeration doesnt.
- enumeration acts as read only interface, because it has methods only to traverse and fetch objects where as by using iterator we can manipulate the objects like adding and removing objects from collection. I.e arraylist.
- iterator is more secured and safe as compared to Enumeration as it does not allow other thread to modify collection object while some thread is iterating over it.

Enumeration:
HasMoreElements()
NextElement()
N/A

Iterator:
HasNext()
Next()
Remove()

28) Difference between vector and Arraylist in Java?

- synchronization: vector is synchronized making it threadsafe while arraylist is not.
- multithreading: vector being sychronized is suitable for use in multithreaded and concurrent environment, arraylist methods are not sychronized thus not suitable for multithreaded environment.
- speed: vector is slow than arraylist
- capacity: when vector crossed the threshold specified, it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity() method.

29) Linkedlist vs arraylist in java?

- insertions are easy and fast in linkedlist as compared to arraylist.
- removal is better in linkedlist than arraylist.
- linkedlist has more memory overhead than arraylist as in arraylist each index only holds actual object(data) but in case of linkedlist  each node holds both data and address of next and previous node.

30) When to use linkedlist and arraylist in java?

- linkedlist is not that popular as arraylist. But you can use linkedlist over arraylist if:
- your application can live without random access.
- your application is more insertion and deletion driver and you insert and remove more than retreival. Insertion and deletion is more fast in linkedlist.

31) What is difference between List and Set in Java?

- list allows duplicates and sets doesnt allow any duplicate. If you insert duplicate in set it will replace older value.
- list is ordered collection while set is an unordered collection.
- list maintains insertion order of elements which means any element that is inserted before will go on lower index than any element which is inserted after. set does not maintain order.
- popular implementation of List interface in Java includes Arraylist, vector and linkedlist. While popular implementation of set interface includes hashset, treeset and linkedhashset.

32) How to check array for duplicate elements in java?

- we can check if array contains duplicate elements or nor
- brute force method which compares each element of array to all other elements and returns true if it found duplicates. Though this is not the efficient choice, it is one which first comes in mind.
- another way of checking is to convert that array into set. Since set does not allow dupicates size of corresponding set it will be smaller than original array If array contains duplicate otherwise size of array and set will be same

Code example:

Import java.util.arrays
Import java.util.hashset
Import java.util.list
Import java.util.set

Public class checkduplicateinajavaarray{ 

Public static void main(string args[]){

String[] withDuplicates = new String[] ("one","two","three","one")
String[] withoutDuplicates=new string[]("one","two","three")

No comments:

Post a Comment