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.

Java TRAINING
Weekend / Weekday Batch

26.What is the default value of the local variables?

They aren’t initialized to any default value. Neither are primitives or object references.
There are no default values assigned to the local variables. They should be declared and the initial value should be assigned before the first use.

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 the static method?

A static method can be invoked without the need for creating an instance of a class. A static method belongs to the class rather than an object of a class. A static method can access static data member and can change the value of it. A static methods are accessed by their class name, rather than object of 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.