简体   繁体   中英

JAVA - Char to Int Conversion

int x='1';
    int y='0';
    System.out.println(x);
    System.out.println(y);

O/P is 49, 48 Whereas,

 int x=s.charAt(1);
    int y=s.charAt(0);
    System.out.println(x);
    System.out.println(y);

O/P is 50, 49 What would be the reason

charAt() method used for string object and get the character in the index

charAt(int index)

String s="Hello"
int x=s.charAt(1) //output: e
System.out.println(x)
// will be the ascii code for the letter

in your code there's no s string so it will be buggy

You can use the cast operator to cast int to char and char to int.

Here's an example:

char c1 = 'b';      //the character 'b' 
int  n = (int) c1;  //convert character to int (ascii code of 'b')
char c2 = (char) n; //convert int to a char 
        
System.out.println(c1);
System.out.println(n);
System.out.println(c2);

output

b
98
b

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM