Basic Java Interview Questions and Answers - 2

7. What is protected access modifier?

Variables, methods and constructors which are declared protected in a superclass are accessible within package and outside the package but through inheritance only.

8. Why is String called 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.

9. Explain the importance of finalize() method.

- Finalize() method is fired when an object is just about to be reclaimed by the garbage collector. When an object needs to perform some action before the object is destroyed, Finalize() method is handy.

- Sometimes an object is holding some non-java resources that should be released before it is destroyed, finalization process of used.

10. Can we force the garbage collection to run?

- Yes, we can force but it is not certain that garbage collector will act upon immediately.
- We can use, System.gc() or runtime.gc()

11. What is the static method?

A static method belongs to the class rather than the object.

There is no need to create the object to call the static methods.

A static method can access and change the value of the static variable.

12. What is the purpose of 'this' keyword?

- 'this' keyword is used to refer current instance of an object.

- It is a non-static method and cannot be used inside main method in Java.

- It invokes current class constructor.

- It can be passed as an argument in the method call.