[java] Why cannot cast Integer to String in java?

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.

This question is related to java string casting integer

The answer is


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


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();

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


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.


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.


Use .toString instead like below:

String myString = myIntegerObject.toString();

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.


Use String.valueOf(integer).

It returns a string representation of integer.


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.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?