views:

311

answers:

3

If i try nltxt = nllen.toString(); with nllen being int nllen = nl.getLength(); i get the error Cannot invoke toString() on the primitive type int. I want to convert the int to string so i can display the number of entries with Log... Why doesnt it work?

+5  A: 

Primitive types aren't objects and as such don't have any methods.

To convert it to a String use String.valueOf(nlTxt).

Chris Smith
+5  A: 

Primitives do not have any fields or methods. Sometimes the compiler will "autobox" your primitive into the corresponding class, Integer in this case. Perhaps that is what you expected in this case. Sometimes the compiler will not do this. In this case it does not automatically autobox it.

You have a few alternatives:

  1. String.valueOf(nltxt)
  2. "" + nltxt (or if you have something useful to write along with the number, do "nltxt equals " + nltxt
  3. Do the "autoboxing" manually: new Integer(nltxt).toString().
  4. Format it in some custom way: String.format("nltxt is %d which is bad%n", nltxt)
aioobe
Don't use 2 and 3
Steve Kuo
I could agree on that 3 is a bit convoluted. But why not 2?
aioobe
aioobe: Its not very readable. If someone is quickly scanning through the code they might miss that you were just trying to convert it to a strong.
Mike
A: 

You could also use Integer.toString(nllen); for this.

source.rar