Java Interview Questions and Answers Set 3

21.Can we use String in the switch case?

Yes from Java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch.

22.How HashSet works internally in Java?

HashSet is internally implemented using an HashMap. Since a Map needs key and value, a default value is used for all keys. Similar to HashMap, HashSet doesn’t allow duplicate keys and only one null key, I mean you can only store one null object in HashSet.

23.How do you print Array in Java?

You can print an array by using the Arrays.toString() and Arrays.deepToString() method. Since array doesn’t implement toString() by itself, just passing an array to System.out.println() will not print its contents but Arrays.toString() will print each element.

24.Explain Java Heap space and Garbage collection?

When a Java process is started using java command, memory is allocated to it. Part of this memory is used to create heap space, which is used to allocate memory to objects whenever they are created in the program. Garbage collection is the process inside JVM which reclaims memory from dead objects for future allocation.

25.How do WeakHashMap works?

WeakHashMap works like a normal HashMap but uses WeakReference for keys, which means if the key object doesn’t have any reference then both key/value mapping will become eligible for garbage collection.

Weekend / Weekday Batch

26.What is the right data type to represent a price in Java?

BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision.

27.The difference between sleep and wait in Java?

Though both are used to pause currently running thread, sleep() is actually meant for short pause because it doesn’t release lock, while wait() is meant for conditional wait and that’s why it release lock which can then be acquired by another thread to change the condition on which it is waiting.

28.What is meant by binding in RMI ?

Binding is the process of associating or registering a name for a remote object, which can be used at a later time, in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class.

29.What is Servlet Chaining ?

Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client.

30.What is the purpose Class.forName method ?

This method is used to method is used to load the driver that will establish a connection to the database.