In Program 1 I have declared two String and initialized them as "MADAM". When running I am checking the equality of their reference variable (by '==' operator') then I am getting a "true" response.
But in Program 2 I am declaring a String 'S' and initialize it as "MADAM". After that i am running a reverse loop and storing the characters of 'S' in reverse order in other String variable. Now i have again tried to check the equality of reference variable (by '==' operator') and am getting the response as 'false'. As both the String objects are of same value and are stored in constant Pool Area so both the variable should equate and the output in both the scenario should be 'true'. But WHY it is not same?
Program 1: class Reverse { public static void main(String[] args) {
String s="MADAM";
String rev="MADAM";
System.out.println(s==rev);
}
}
Output - true
Program 2: class Reverse { public static void main(String[] args) {
String s="MADAM";
String rev="";
for(int x=s.length()-1;x>=0;x--)
{
rev+=s.charAt(x);
}
System.out.println(s==rev);
}
}
Output- false