JAVA - Char to Int Conversion

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

O/P is 49, 48 Whereas,

    String s="01221";
    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

2 Answers

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
Related