permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings" Watch "Strings" New topic
Author

Strings

Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787

Why line 1 prints false?
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
You're creating two different objects in the String constant pool. The equality test (==) only returns true when two object references are pointing to the same object. If you want to compare value, then use one of the String's equals() methods:

[ October 08, 2003: Message edited by: Jeff Bosch ]

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Even though "hello" and "world" are string literals, you're using concatenation with a variable to put them together. When you do that, a brand new String is created.
However, if you don't use the variable (as is done with s4 and s5), the compiler can perform an optimization and create a single "helloworld" string literal.


SCJP Tipline, etc.
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
�hello� + �world� is a constant expression.
final String s = �world�;
�hello� + s is a constant expression.
String s = �world�;
�hello� + s is not a constant expression.
This is how the concatenation operator works.
StringBuffer sb = new StringBuffer();
sb.append(�hello�);
sb.append(s);
String x = sb.toString(); // a new String object is created

You can see the StringBuffer method calls in the byte codes. You can see the call to toString() that creates a new String object.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
Hi, Marlene -
How did you get that listing?
Thanks!
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
Hi Jeff.
javap is a utility that comes with the SDK. It disassembles a class file.
javap �c classname
The �c switch prints the byte codes.
You probably know where the byte codes are defined. Java Virtual Machine Spec Chapter 6.
javap �private classname
The �private switch prints all members of a class. This is very useful for seeing the synthetic fields the compiler adds to inner classes.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
Thanks, Marlene!
I have a background in hardware and assembly language, so I love digging into the depths of how machines work. This'll be fun.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Strings
 
Similar Threads
strings
Doubt in Strings
String puzzle
subString
String