This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 13870
    
  10

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!

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Assigning values to variables in constructors
 
Similar Threads
how to get rid of space in string
storing user defined variables in an array
StringBuffer class
June Newsletter Puzzle
Random string generation