Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assigning values to variables in constructors

 
Andrew Stallard
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Andrew Stallard
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, this worked!

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic