13

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 doesn't it work?

3 Answers 3

29

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)

2
  • I could agree on that 3 is a bit convoluted. But why not 2?
    – aioobe
    Commented Jun 12, 2010 at 21:05
  • 1
    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
    Commented Jun 13, 2010 at 0:25
12

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

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

6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.