This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
It compiles just fine. However, when running this happens:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
Now, what appears to be going on is even though I assigned a value to the StringBuffer s in the constructor, it can not be used by any of the methods, even though the variable s was originally declared outside the constructor or any method. (I tried declaring s as static, and that didn't work.) Is there anyway to assign a value to a variable in a constructor that can also be used by any method in that class?
In line 2, you have a member variable 's' that is a StringBuffer. In your constructor (lines 5-9) you create a local variable, also named 's', to which you append the data.
Note that the local variable 's' in the constructor hides the member variable - the member variable never gets filled with the data. That's why you see 0 when you call Dong.length().
To fix the problem, simply remove line 6 from your code.
Another note about line 12: The new String(...) is not necessary, because s.toString() already returns a string. There is no need to create a new String object using the value of the returned string. Change line 12 to this: