1.

Write a program in Java to prove that the strings are immutable in Java.

Answer»

Strings are immutable in Java. This can be proven by making changes to a string and comparing them with the == operator. Since this operator compares only the references, i.e. the addresses of the objects, it will be able to tell us if the changes are made to the same object or not. If after making changes to a string we compare it by == and we get no equals, this means that the strings are immutable. 

Java program to prove Strings are Immutable

class Main {
public static void main(String args[]) {
// Your code goes here
String s1 = "InterviewBit";
String s2 = s1;

System.out.println(s1 == s2); //they are equal

s1 += "Scaler";

System.out.println(s1 == s2); //not equal
}

Output

true
false

So, let us now discuss an array of programs related to Java interviews. 




Discussion

No Comment Found