• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How the JVM interprets this code?

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code works just fine, but I am trying to figure how the JVM resolve this code (what happend behin scenes).


public class Test{
public static void main (String x[]){

StringBuffer kk = new StringBuffer("Test");

kk.append(" aja") // <- what happend from here
.append(" dos")
.append("tres"); // <- to here

System.out.println(kk);
}

}
[ January 06, 2005: Message edited by: Jose Ortuno ]
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
StringBuffer uses a handy trick called method chaining. Methods that operate on the object without needing to return a result (append, delete, etc) return the object itself (return this instead of being declared void. This allows you to call multiple methods on the same object without typing the reference each time.

Thus, the return value of kk.append(" aja") is the StringBuffer pointed to by kk. The same applies to the two other append() calls.

Note that this is just a typing-saver trick (and some claim higher readability); no special handling was required by the JVM. One downside is that JVMs have been getting much better about optimizing code, so in this codethe buf reference is checked for null only before the first call, as the compiler can tell that local variable buf cannot be changed between calls. Using call chaining, the compiler has no way of knowing that the returned StringBuffer is still not null, and so it must check for null each time. Granted, this is a trivial speed hit, but it's there.

Hmm, perhaps Java should allow declarations liketo tell the compiler that the returned value will always be the same instance, and thus not null.
 
Jose Ortuno
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great....just what I was expecting.

I agree about:
public this append ( String str )
 
reply
    Bookmark Topic Watch Topic
  • New Topic