Interger.parseint(x) and (int) Analysis

See the code below.

class test02
{
public static void main(String[] args)
{
char s2='a';
String s1="12";
double x=Double.parseDouble(s1);
int y=(int)s2;//Integer. parseInt(s2);
System.out.println(x+y);
}
}

The result is 109.0
If you use Integer.parseInt(s2);
it will report an error

but the following code
class test02
{
public static void main(String[] args)
{
String s1="0.5",s2="12";
double x=Double.parseDouble(s1);
int y=Integer.parseInt(s2);//(int)s2;
System.out.println(x+y );
}
}
The output result is 12.5. If you use (int), an error will be reported. Why is this?


 

First, let's take a look at how the parameters of parseint() are defined

static int parseInt(String s) 
          parses the string argument as a signed decimal integer. 
static int parseInt(String s, int radix) 
          Parses the string argument as a signed integer using the radix specified by the second argument.

So chars is a character type and cannot use the parseint() method.

However, you are not asking how (int)x can forcibly convert a data that is not itself an Int to an Int. In java, char can be forcibly converted to int, and it is converted to ASCII. For example, a is 97

And the second one is originally a string, so just interger.parseint directly into int

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325329992&siteId=291194637