Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string questions?

 
Deep Chand
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
this is from Abhilash's Quiz link (from mock exams available):
a) if("String".trim() == "String".trim())
System.out.println("Equal");
else
System.out.println("Not Equal");

b) if( "STRING".toUpperCase() == "STRING")
System.out.println("Equal");
else
System.out.println("Not Equal");
The answers to both these questions are: "the code will compile an print "Equal". "
I tried this and ans is correct but I can't understand why? I know you java gurus will have an answer to "why"?
Thanks,
Deep
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
String methods, such as toUpperCase(), toLowerCase() and trim(), will return the original String object if NOTHING is changed on the string.
Hope this helps.
[ August 31, 2003: Message edited by: Alton Hernandez ]
 
billli li
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the code below copying from String class:
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
 
Larry Mathys
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesn't this question deal with how Java stores String objects on the heap? To keep the overhead down, if there is more than one copy of the same string in memory, both references to the string point to the same String object instead of making another object on the heap. This special region of memory is called the String constant pool. (Which is why Strings are immutable.) So the if statement, comparing the reference objects with the double equals, NOT the value of the String (a la String.equals()) will return true. The reference variables do have the same address in memory.
Each new String literal is still a new reference to a string object. :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic