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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.