| Author |
String Objects created
|
dennis zined
Ranch Hand
Joined: Mar 07, 2003
Posts: 330
|
|
hello ranchers. Is it correct to say there are two String objects created by this statement: System.out.println("hello world".toUpperCase()); thanks.
|
SCJP 1.4<br />SCWCD 1.4
|
 |
Vivek Nidhi
Ranch Hand
Joined: Aug 10, 2003
Posts: 133
|
|
Hello there I think only One object is created. Used javap to conclude this if am wrong please point out. D:\javaprg>javap -c hi Compiled from hi.java public class hi extends java.lang.Object { public hi(); public static void main(java.lang.String[]); } Method hi() 0 aload_0 1 invokespecial #1 <Method java.lang.Object()> 4 return Method void main(java.lang.String[]) 0 getstatic #2 <Field java.io.PrintStream out> 3 ldc #3 <String "hello world"> // Push Item from Constant Pool (The String is put in the Constant Pool) 5 invokevirtual #4 <Method java.lang.String toUpperCase()> // invoke the method to convert it to UpperCase 8 invokevirtual #5 <Method void println(java.lang.String)> 11 return regs Vivek Nidhi
|
 |
dennis zined
Ranch Hand
Joined: Mar 07, 2003
Posts: 330
|
|
|
thanks Vivek.
|
 |
Nathaniel Stoddard
Ranch Hand
Joined: May 29, 2003
Posts: 1258
|
|
Um, well not to be a pain, but unless you're being very specific about your useage of the term "object" there are going to be 2 strings created. The first will be "hello world" string placed in the constant string pool. After that, the toUpperCase method will return a separate string since strings are immutable. So, 2 strings. Um, how many objects? Well, is a string placed in the constant memory pool an object? You did call toUpperCase on it, so I would venture to say that it is an object. Of course, I didn't run across any questions on the exam that asked how many "string objects" are created by a segment of code. Only questions that just asked "how many strings".
|
Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
|
 |
Vivek Nidhi
Ranch Hand
Joined: Aug 10, 2003
Posts: 133
|
|
Thanks for pointing out my mistake. regs Vivek Nidhi
|
 |
Nathaniel Stoddard
Ranch Hand
Joined: May 29, 2003
Posts: 1258
|
|
|
My pleasure. String creation is one of the easier topics on the exam and a nice place to have the opportunity to pick up a few points without breaking a sweat.
|
 |
 |
|
|
subject: String Objects created
|
|
|