File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes explain this string method.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "explain this string method.." Watch "explain this string method.." New topic
Author

explain this string method..

Bhasker Reddy
Ranch Hand

Joined: Jun 13, 2000
Posts: 176
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
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
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
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
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
Thanks Srini
I need to do a lot of reading and practice cos I'm giving exam on Aug 18.
THanks again
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explain this string method..