111

I found some strange exception:

java.lang.ClassCastException: java.lang.Integer 
 cannot be cast to java.lang.String

How it can be possible? Each object can be casted to String, doesn't it?

The code is:

String myString = (String) myIntegerObject;

Thanks.

user710818
  • 23,228
  • 58
  • 149
  • 207
  • 11
    _"Each object can be casted to String"_ -- This is wrong. Rather, every object has a `toString()` method that will convert it to a String. As several answers point out, that is what you should use. (For some objects, `toString()` doesn't return a very _useful_ string, but for `Integer`, it probably does exactly what you want.) – Ted Hopp Jan 23 '12 at 14:53
  • 2
    `""+myIntegerObject` also works :) – Samuel Katz Apr 15 '14 at 02:48
  • 1
    In my case, this error was reported in fault... I was using `Integer.toString(IntegerObject)` and it gave me this error, but it's happy with `IntegerObject.toString()`... And yes, that really is an Integer, and I really did get this error... – Andrew Mar 07 '19 at 19:43
  • Scratch that, only `String.valueOf()` actually works... – Andrew Mar 07 '19 at 19:50

11 Answers11

172

Why this is not possible:

Because String and Integer are not in the same Object hierarchy.

      Object
     /      \
    /        \
String     Integer

The casting which you are trying, works only if they are in the same hierarchy, e.g.

      Object
     /
    /
   A
  /
 /
B

In this case, (A) objB or (Object) objB or (Object) objA will work.

Hence as others have mentioned already, to convert an integer to string use:

String.valueOf(integer), or Integer.toString(integer) for primitive,

or

Integer.toString() for the object.

Bhushan
  • 18,329
  • 31
  • 104
  • 137
51

No, Integer and String are different types. To convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
  • 1
    @Ted Hopp - which one? If it is a primitive use the first two, if it is the Integer object use the third one. – Petar Minchev Jan 23 '12 at 14:50
  • Oops. I didn't see that last phrase of your answer. I'm deleting my comment and upvoting this answer. – Ted Hopp Jan 23 '12 at 14:59
  • 1
    Similar (but not duplicate) issue: an ['int' cannot be cast to a String](http://stackoverflow.com/questions/4105655/problems-converting-integer-to-string) because an 'int' is not an object, much less in the String hierarchy. – Kelly S. French Jan 23 '12 at 15:03
  • All answers acceptable (Petar knows his stuff) and while the primitives versus object options in Java static utilities can be exasperating... the general rationale to the OP's question is effectively "any integer can be a String but not every string can be an integer". Also take care with sorting. A list of bonafide integers as String types does not have the same natural order sorting as a list of actual integer types. – Darrell Teague Apr 09 '22 at 02:05
22

For int types use:

int myInteger = 1;
String myString = Integer.toString(myInteger);

For Integer types use:

Integer myIntegerObject = new Integer(1);
String myString = myIntegerObject.toString();
DRiFTy
  • 11,269
  • 11
  • 61
  • 77
6

No. Every object can be casted to an java.lang.Object, not a String. If you want a string representation of whatever object, you have to invoke the toString() method; this is not the same as casting the object to a String.

andri
  • 11,171
  • 2
  • 38
  • 49
6

You can't cast explicitly anything to a String that isn't a String. You should use either:

"" + myInt;

or:

Integer.toString(myInt);

or:

String.valueOf(myInt);

I prefer the second form, but I think it's personal choice.

Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

Jonathan
  • 7,536
  • 4
  • 30
  • 44
  • OP is starting with an Integer object. It's much more efficient to just do `myIntegerObject.toString()`. – Ted Hopp Jan 23 '12 at 16:21
5

Objects can be converted to a string using the toString() method:

String myString = myIntegerObject.toString();

There is no such rule about casting. For casting to work, the object must actually be of the type you're casting to.

millimoose
  • 39,073
  • 9
  • 82
  • 134
4

You should call myIntegerObject.toString() if you want the string representation.

Savino Sguera
  • 3,522
  • 21
  • 20
3

Casting is different than converting in Java, to use informal terminology.

Casting an object means that object already is what you're casting it to, and you're just telling the compiler about it. For instance, if I have a Foo reference that I know is a FooSubclass instance, then (FooSubclass)Foo tells the compiler, "don't change the instance, just know that it's actually a FooSubclass.

On the other hand, an Integer is not a String, although (as you point out) there are methods for getting a String that represents an Integer. Since no no instance of Integer can ever be a String, you can't cast Integer to String.

yshavit
  • 42,327
  • 7
  • 87
  • 124
1

In your case don't need casting, you need call toString().

Integer i = 33;
String s = i.toString();
//or
s = String.valueOf(i);
//or
s = "" + i;

Casting. How does it work?

Given:

class A {}
class B extends A {}

(A)
  |
(B)

B b = new B(); //no cast
A a = b;  //upcast with no explicit cast
a = (A)b; //upcast with an explicit cast
b = (B)a; //downcast

A and B in the same inheritance tree and we can this:

a = new A();
b = (B)a;  // again downcast. Compiles but fails later, at runtime: java.lang.ClassCastException

The compiler must allow things that might possibly work at runtime. However, if the compiler knows with 100% that the cast couldn't possibly work, compilation will fail.
Given:

class A {}
class B1 extends A {}
class B2 extends A {}

        (A)
      /       \
(B1)       (B2)

B1 b1 = new B1();
B2 b2 = (B2)b1; // B1 can't ever be a B2

Error: Inconvertible types B1 and B2. The compiler knows with 100% that the cast couldn't possibly work. But you can cheat the compiler:

B2 b2 = (B2)(A)b1;

but anyway at runtime:

Exception in thread "main" java.lang.ClassCastException: B1 cannot be cast to B2

in your case:

          (Object)
            /       \
(Integer)       (String)

Integer i = 33;
//String s = (String)i; - compiler error
String s = (String)(Object)i;

at runtime: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

Dmytro Sokolyuk
  • 966
  • 13
  • 13
0

Use .toString instead like below:

String myString = myIntegerObject.toString();
A.Aleem11
  • 1,844
  • 17
  • 12
0

Use String.valueOf(integer).

It returns a string representation of integer.

RanRag
  • 48,359
  • 38
  • 114
  • 167