Unique And
Tough Interview Questions
Q) What is volatile keyword? Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased. In this case the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues. Q) What is a transient variable? Ans) If some of the properties of a class are not required to be serialized then the varaibles are marked as transient. Q) What is the use of final keyword?
Class level variable
final int i=1;
If a final is assigned to a method then it cannot be overridden in its child class. class Parent { public final void print(){
System.out.println(“Inside”);
} class Child extends Parent{ public final void print(){ // error cannot override final method
System.out.println(“Inside”);
} If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class. Final objects are instantiated only once. i.e final Map map = new HashMap(); map.put(“key”,”value”); map = new HashMap(); // error Q) What is use of synchronized keyword? Ans) This keyword is used to prevent mulitple access. synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g. public void synchronized method(){}
synchronized (this){
// synchronized keyword on block of code
}
Relevant Java Topics:
Ask It in The Java Forum Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|