Java Topics

2022 Interview Questions & Answers

 1. What is immutable and mutable in java?

  • Immutable means we cann't change the value of existing object. If we try to do, instead of changing the existing object new object will be created.

          Ex: String class

  • Mutable means, if we try to change existing object it will append the value to existing object without creating any new object.

          Ex: StringBuffer and StringBuilder

2. How to make class as immutable?

To make any class has immutable, follow below steps:

1. Final class - if we make class as final it cann't be extended

2. Private members - declare the members of the class as private so

    that direct access to the feilds will be blocked

3. No setter methods and only get methods should be allow

3. Difference between equals() and hashcode() in Object and String class?

  • In Object class, equals() compares the reference/address of two objects using == operator where as hashcode() returns unique integer value for each object at runtime.
  • In String class, equals() compares the content of two strings using .equals() method.

NOTE :the equals() in String class is overridden method from Object

class. Both equals() and hashcode() methods are part of Object class.

4. Can we override private method in java?

No, private method cann't be extended to subclass since it's not

accessible. Beacuse the scope of private methods and varibales will be

within same class.

5. Does finally block always executes in java?

No, except in below two cases it won't execute.

a. System.exit()

b. System crashes

6.Difference between Error and Exception?

  • Error which we cann't able to handle it where as exception we can able to handle it using try catch block.
  • If error occurs the rest of the code won't get executed that means it terminates the program execution.
  • But in case of exception the code will be executed by handling the exception using try catch.
7.Can we overload main method?

Yes, because main is a static method and overloaded method will have different arguments. Even though there are two main methods JVM always calls main method with String[ ] arguments.

8.Can we override main method?

No, because main method is static and static method cannot be inherited and overridden.

No comments:

Post a Comment