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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "constructores" Watch "constructores" New topic
Author

constructores

sona gold
Ranch Hand

Joined: Feb 14, 2001
Posts: 234
public class Test
{
static StringBuffer sb = new StringBuffer("Java");
public Test() {}
public Test(StringBuffer s) {
this( s,s.append(" Script"));
}
public Test(StringBuffer s, StringBuffer sb1) {
System.out.println(s.toString());
System.out.println(sb1.toString());
}
public static void main(String[] args) {
new Test(sb);
}
}
prints the output as :
Java Script
Java Script

sona<br />SCJP
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
That is correct. s and sb1 are two pointers to the same object so naturally they print the same thing. s.append("xxx") does not create a new object but rather updates the existing StringBuffer object.
Step at a time:
1) MAIN METHOD:
new Test(sb);
2) STATIC:
static StringBuffer sb = new StringBuffer("Java");
3) CONSTRUCTOR:
public Test(StringBuffer s) {
this( s,s.append(" Script"));
}
- s.append(" Script") will update sb so that it contains "Java Script"
- at this point we have 2 pointers pointing to the same StringBuffer (class variable sb and method variable s)
4)THE OTHER CONSTRUCTOR
public Test(StringBuffer s, StringBuffer sb1) {
System.out.println(s.toString());
System.out.println(sb1.toString());
}
- we now have 4 pointers pointing to the same StringBuffer (class variable sb, method variable s from first constructor, and method variables s and sb1 from the second constructor)
- there has only been 1 new so that is a clue that we only have created one StringBuffer object

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: constructores
 
Similar Threads
casting
StringBuffer question?
help needed regarding appending character
equals() in Wrapper Classes