5

I just figured out that when I do this in Java:

for(int x = 0; x < 3; x++)
{
    String bla = "bla";
    bla += x.toString();
}

It (Netbeans in this case) will tell me I can not dereference my x integer in such a manner (as I would in C#).

Why is that?

Mnescat
  • 195
  • 1
  • 13

6 Answers6

8

Primitive types are not objects in Java, so you need to use other methods to do that, in this case:

Integer.toString(x);
Serabe
  • 3,834
  • 19
  • 24
7

an int is a primitive, not an Object, and hence does not have a toString() method.

But you can do this:

String bla = "bla" + x;
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
5

int is not an object, but a primitive type. Thus, you cannot call methods off of int. If you defined it as Integer, the error message would go away. However, you can really just get rid of toString, because x will be coerced into a String automatically.

Briguy37
  • 8,342
  • 3
  • 33
  • 53
4

x is not an Integer, its an int, and int is a primitive type, so it doesn't have toString.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
4

You declared x to be of type int which is a primitive value, not an object. Primitives cannot have methods (like toString()) called on them. You could use the primitive wrapper Integer if you want to invoke toString(), or you could simply remove the call to toString() and Java's special handling of strings and primitives will take care of itself.

Michael McGowan
  • 6,528
  • 8
  • 42
  • 70
3

In java, primitive types (boolean int, short, char,long, float, double) are NOT objects.

They however do have wrapper type (Integer, Character, ...) which have 1) utilyty static functions and 2) its instances can wrap primitive values.

Alpedar
  • 1,314
  • 1
  • 8
  • 12
  • 1
    Exactly, which is why any C# will come to this question: since the wrapper type automatically boxes the primitive, and the wrapper has a toString(), why then isn't x.toString() valid? x should box to Integer and Integer has a toString(). So the answer isn't really that an int is a primitive (it is in c# as well as he points out), but the question is "why is javas autoboxing not doing what the .net autoboxing does". – Anders Forsgren Aug 22 '11 at 14:27
  • That is indeed exactly what I wanted to know – Mnescat Aug 22 '11 at 14:30
  • I thought that in .NET int actualy is object, so x.toString() does not involve autoboxing at all. But it is value object, so where reference object is needed, autoboxing get involved. – Alpedar Aug 23 '11 at 08:01