aspose file tools*
The moose likes Java in General and the fly likes Assigning values to variables in constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Assigning values to variables in constructors" Watch "Assigning values to variables in constructors" New topic
Author

Assigning values to variables in constructors

Andrew Stallard
Ranch Hand

Joined: Mar 06, 2010
Posts: 33
Now, in this program:



It compiles just fine. However, when running this happens:

supercalifragilisticexpialadocious 34
0
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.StringBuffer.charAt(StringBuffer.java:162)
at CSTest.charAt(CSTest.java:21)
at CSTest.main(CSTest.java:27)

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?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14103
    
  16

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:

Or, even better, just replace lines 12 and 13 by:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Andrew Stallard
Ranch Hand

Joined: Mar 06, 2010
Posts: 33
Yes, this worked!

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assigning values to variables in constructors