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.
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.
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.
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();
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.
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.
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.
You should call myIntegerObject.toString() if you want the string representation.
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.
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
Use String.valueOf(integer).
It returns a string representation of integer.
Use .toString instead like below:
String myString = myIntegerObject.toString();
Related
My goal is to cast to a generic type, the information that a String contains, being this information variable between the different Java types. Ex:
String s = "10";
E e1 = (E)s;
String s = "abc";
E e2 = (E)s;
In this example e1 would be an Integer and e2 remains String. I have been searching for a solution during several hours, and the best I have found is a solution with reflection
However it cast to String, indepently if it contains other type of information, causing malfunctions in other parts of the code.
There's some terminological friction between your notion of "generic" (the kind of information that e.g. the 2nd and 3rd characters of "€10.-" might represent) and generic types, which is a Java technical term and concept.
There are some things below, that objects of class String are compatible with. Only Comparable is considered a generic type in the Java technical sense (here it has the type parameter <String>), all the rest is not.
public final class String implements java.io.Serializable,
Comparable<String>, CharSequence, Constable, ConstantDesc
You don't need to cast a String to any of them. You can just do stuff like this:
String s = "10";
CharSequence c = s;
If you go the other way round and you have CharSequence c then you can find out if it is actually String, and if it is, then you can cast. Btw. also the "reflection approach" you referred to tests (clazz.isAssignableFrom) before it casts.
CharSequence c = new StringBuffer("Käse");
if(c instanceOf String) // it is not, it is instanceOf StringBuffer
{
String anotherString = (String) c;
}
What you talked about isn't about casting but converting or evaluating. You can get an Integer from a String using Integer's conversion method valueOf().
Integer two = Integer.valueOf("2");
But it may fail, e.g. if you try this Integer.valueOf("€10.-") you'd get a NumberFormatException. You'd need to pick the numerical part only to make it work Integer.valueOf("€10.-".substring(1, 3))
If we can typecast an Integer object to Object and unbox an Integer to int, why can't we unbox the same Object type to int?
Integer i=new Integer(5);
Object p=i;
int s=p;//gives error
The compiler has no idea that something of type Object is actually an integer. To your eyes, you can clearly see that you are assigning an integer and that is converted into an integer object. However, as soon as you assign it to an Object, that information becomes lost for the semantic purposes of the source code.
It's the same reason why this code would be wrong:
Object o = getSomeObject(); // What exactly does it return? We don't know
int i = o; // How do you know this will work?
The function getSomeObject() could return anything. We have no idea if it will be an integer, or a String, or an ArrayList... and therefore we have to assume it is an unsafe conversion. If the above makes sense to you, then you can extrapolate to your example why you can't do the conversion.
Now the part I assume that is confusing you is "I clearly put an integer in there, which is auto boxed into an Integer and should be assignable by unboxing!"
... however the rules of the language state that once we do that assignment, we have to treat it as that it could be any object of that type. Since we can't blindly assume that the object is an integer, you need to explicitly cast it.
This also plays a role in going up the hierarchy chain for polymorphism. If you have a parent P, and a child C that extends from P, then we know that:
Child c = new Child();
Parent p = c; // Valid, because c is definitely a Parent
but
Parent p = new Parent();
Child c = p; // Can't go down the hierarchy, this is also wrong
The same thing is seen in your example. Integer is a child of Object, that's why we can do
Integer i = 5;
Object o = i;
and likewise, we can't do it in the reverse
Object o = new Object();
Integer i = o; // Not allowed
and because for your example we need to go from Object -> Integer -> int (by unboxing), the second step from Object to Integer is not allowed.
Now if you did in fact write code like
Integer i = new Integer(5);
Object p = i;
int s = (Integer) p;
this would work. In fact, the JVM at runtime (via HotSpot) would likely notice exactly what you're doing and convert the above code into:
int s = 5;
because the JVM is likely smart enough to realize exactly what you as a human realize.
So while you have to write semantically correct Java source code (which doing int i = someObj is not when the right hand side of the equals side is an Object), the compiler will likely be smart enough to inline all of it for you when you run your program.
Upcasting is casting to a supertype in your case object, while downcasting is casting to a subtype in your case int. Upcasting is always allowed, but downcasting involves a type check.
Object p=i;
Here you are doing Upcasting which is always allowed because it make sense that int is an Object.
int s = p;
Here p is object and you are trying to assign it to subtype int, how would the compiler will know that p-object is an int not a string or double etc. So to solve this your have to do downcasting explicitly like this:
int s = (int) p;
NOTE: Wrong downcasting can throw a ClassCastException.
String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);
Why sometimes cast will not work but String.valueOf() will? Aren't they all exist for same functionality of converting current type to String?
For example:
addgui.getIdField().setText(String.valueOf(jtable.getValueAt(rowNum, 0)));
here jtable.getValueAt(rowNum, 0) returns an Integer value and if I directly cast it to String it causes eroor, but String,valueOf works instead.
Remember that String.valueOf(Object) invokes Object.toString(), creates a String out of it and assigns it to the the Object.
Casting will just assign object2 to the object1, If both have same type it will work. Otherwise, the expression would throw a ClassCastException.
Example
Object a1 = "abc";
String s =(String)a1; //this works
But this shall give you a ClassCastException
int b = 1;
Object c = b;
String s1 =(String)c;
Where as String.valueOf() converts whatever to pass to it as a String
I having the following code and member value is type object and in this process = long and i want to cast it to big decimal ,when i trying the following code i get error:java.lang.Double cannot be cast to [C
} else if (typeName.equals("java.math.BigDecimal"))) {
return new SwitchInputType<BigDecimal>(new BigDecimal((char[]) memberValue));
The error message:
java.lang.Double cannot be cast to [C
tells you that this cast is illegal:
(char[]) memberValue
so don't do it. The error message tells you that memberValue is a Double, so this should work:
return new SwitchInputType<BigDecimal>(new BigDecimal((Double) memberValue));
Depending on the declared type of memberValue the cast may be completely unnecessary, though it sounds like the declared type is Object. Alternately, since there is a BigDecimal constructor which accepts strings, you could try to get away with this, though it's not really any less-smelly:
return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue.toString()));
The [C represents the type "array of char", and indeed, you can't cast a Double to an array of char, nor should you want to. According to the message, memberValue is a Double, so you just want to do
return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue));
If you are getting that error, it means that memberValue is a Double. In this case, you should probably just use
new BigDecimal(memberValue)
but I'd have to see more code to be sure.
The error message means that memberValue is a java.lang.Double object, and you are trying to cast it to char[]. That doesn't work, because a Double is not a char[].
In this case, you can just remove the cast, and call doubleValue() on the Double object:
return new SwitchInputType<BigDecimal>(new BigDecimal(memberValue.doubleValue()));
This way, you're using the constructor of BigDecimal that takes a double instead of a char[].
If the type of memberValue is Object, you'll have to cast it to Double first:
((Double)memberValue).doubleValue()