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
2010-06-12 14:29:59
+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:
String.valueOf(nltxt)
"" + nltxt
(or if you have something useful to write along with the number, do"nltxt equals " + nltxt
- Do the "autoboxing" manually:
new Integer(nltxt).toString()
. - Format it in some custom way:
String.format("nltxt is %d which is bad%n", nltxt)
aioobe
2010-06-12 14:33:19
Don't use 2 and 3
Steve Kuo
2010-06-12 15:50:44
I could agree on that 3 is a bit convoluted. But why not 2?
aioobe
2010-06-12 21:05:19
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
2010-06-13 00:25:05