if(" String ".trim() == "String") System.out.println("Equal"); else System.out.println("Not Equal"); why this is printing not equal, because when string is trimmed it should be equal to String.., can someone explain
Bhasker Reddy
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Originally posted by Bhasker Reddy: if(" String ".trim() == "String") System.out.println("Equal"); else System.out.println("Not Equal"); why this is printing not equal, because when string is trimmed it should be equal to String.., can someone explain
I think you need to read the chapter on "Strings" once more. This is the most basic thing, here you are trying to compare the addresses of the two strings with the operator ==. I you want to compare the strings as such(the contents of the strings), you need to use the method - equals() as: " String ".trim().equals("String") - you will get the correct result.
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
the following code will print Equal if ("String"=="String")System.out.println("Equal");
because there is only one string object is created. This is equivalent to saying, String a="String"; String b="String"; if (a==b) System.out.println("Equal"); // will print Equal
But " String ".trim()=="String" is not equal because " String ".trim() creates a new String object. This is equivalent to String a="String"; String b=new String("String"); if (a==b) System.out.println("Equal"); else System.out.println("Not Equal"); // will print not equal
Harry Chawla
Ranch Hand
Joined: Jun 03, 2000
Posts: 97
posted
0
What about String a=new String("String");; String b=new String("String"); if (a==b) System.out.println("Equal"); else System.out.println("Not Equal"); It stills prints Not Equal. I thought this time it should point to the same memory address. Your inputs will be highly appreciated.
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
String a=new String("String"); String b=new String("String"); The above code creates 2 string objects. The following mock exam has a lot of questions on string equality. http://members.theglobe.com/apoddar/questions.html
Harry Chawla
Ranch Hand
Joined: Jun 03, 2000
Posts: 97
posted
0
Thanks Srini I need to do a lot of reading and practice cos I'm giving exam on Aug 18. THanks again