Java Interview Questions | Page 6

Question 51:

Question 52:

Can a thread hold multiple locks at the same time?

Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the synchronized method / block, it may call another synchronized method and acquire a lock on another object.

Question 53:

How to make a List (ArrayList,Vector,LinkedList) read only?

A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

Question 54:

What are advantages of iterating a collection using iterator?

For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Question 55:

Why character array is better than String for String password?

In Java Strings are immutable and if one stores password in String it will be available in memory until garbage collector clears it. As the developer does not have control over Garbage Collector and string are created in String pool, there is high chance it will remain in pool for long duration.Moreover any one who has access to memory dump can find the password as clear text.Since String are immutable there is no way contents of String can be changed because any change will produce new String while in char[] you can set it to blank or zero.

Question 58:

What is difference between yield and sleep methods?

Yield method pauses the currently executing thread temporarily for giving a chance to remaining thread of same priority to execute whereas sleep causes currently executing thread to sleep for the specific nuber of m/s or n/s.