Java Interview Questions and Answers - 3

14. Why Strings in Java are called as Immutable?

The String class is considered as immutable because once it is created, a String object cannot be changed. If we require to make a lot of modifications to Strings of characters then StringBuffer should be used.

15. Why Runnable Interface is used in Java?

Runnable interface is used for implementing multi threaded applications.

If you want to execute a code in separate thread, you need to implement Runnable interface in a class whose instance you want to run in separate thread instead of Main thread.

16. What are the two ways of implementing multi-threading in Java?

Java offers implementation of multi-threading by two ways:

By extending Thread class and overriding its run() method.

By Implementing Runnable interface

17. When a lot of changes are required in data, which one should be preferred - String or StringBuffer?

Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it's always a good choice to use StringBuffer when data is being changed too many times. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.

18. How garbage collection is done in Java?

In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. Java calls either System.gc() method or Runtime.gc() method for automatic garbage collection

19. How objects of a class are created if no constructor is defined in the class?

When no explicit constructor is defined in a java class, objects can still get created successfully. In this case, Java use default constructor implicitly for object creation. This constructor has no parameters.