java - Comparing Same Object of String with '==' and getting different result in both scenerio, where the String Object Value is same -
this question has answer here:
- java string.equals versus == [duplicate] 20 answers
- how compare strings in java? 23 answers
in program 1 have declared 2 string , initialized them "madam". when running checking equality of reference variable (by '==' operator') getting "true" response.
but in program 2 declaring string 's' , initialize "madam". after running reverse loop , storing characters of 's' in reverse order in other string variable. have again tried check equality of reference variable (by '==' operator') , getting response 'false'. both string objects of same value , stored in constant pool area both variable should equate , output in both scenario should 'true'. why 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
in program 1 java compiler saves "madam" string in 1 memory location , assigns both "s" , "rev" location hence "s==rev" returns true because both refer same address. should use "equals()" method compare 2 strings. e.equals(rev);
have @ question: java string.equals versus ==
Comments
Post a Comment