Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why line 1 prints false?
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
�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
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Marlene -
How did you get that listing?
Thanks!
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic