why is string is immutable in java?

  • In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be modified.
  • Whenever you try to update the value of that object instead of updating the values of that particular object, Java creates a new string object.
  • Java String objects are immutable as String objects are generally cached in the String pool.
  • Since String literals are usually shared between multiple clients, action from one client might affect the rest.
  • It enhances security, caching, synchronization, and performance of the application.

What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor.

this:

  1. this() represents the current instance of a class
  2. Used to call the default constructor of the same class
  3. Used to access methods of the current class
  4. Used for pointing the current class instance
  5. Must be the first line of a block

super:

  1. super() represents the current instance of a parent/base class
  2. Used to call the default constructor of the parent/base class
  3. Used to access methods of the base class
  4. Used for pointing the superclass instance
  5. Must be the first line of a block

What is the difference between equals() and == in Java?

  • Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.
  • ''=='' or double equal operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects.
  • public boolean equals(Object o) is the method provided by the Object class.
  • The default implementation uses == operator to compare two objects.
  • For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

What is final keyword in Java?

final is a special keyword in Java that is used as a non-access modifier. A final variable can be used in different contexts such as final variable,final method, final class

What is a constructor?

A constructor is a "kind of" method in java which is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. A constructor definition is similar to a method definition, except that the constructor should have same name as the class and doesn't contain a return type.

public class MyClass {
    public MyClass() {
      // class level definitions
    }
}