aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes string questions? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "string questions?" Watch "string questions?" New topic
Author

string questions?

Deep Chand
Ranch Hand

Joined: Dec 17, 2002
Posts: 133
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

Joined: May 30, 2003
Posts: 443
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

Joined: Aug 25, 2003
Posts: 1
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;
}


Welcome to <a href="http://www.xmlmentor.net" target="_blank" rel="nofollow">www.xmlmentor.net</a>
Larry Mathys
Greenhorn

Joined: Sep 02, 2003
Posts: 7
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. :-)


"There are only 10 types of people in the world, those who understand binary and those who don't."
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: string questions?