I have very basic question.
How is possible for int a = 'a'
to give 97
in output.
Below is my code:
class myClass {
int last = 'a' ;
myClass () {
System.out.println(last );
}
}
I have very basic question.
How is possible for int a = 'a'
to give 97
in output.
Below is my code:
class myClass {
int last = 'a' ;
myClass () {
System.out.println(last );
}
}
You can have a look at this: Why are we allowed to assign char to a int in java?
Basically, you are assigning a char
to your int. A char
is technically an unsigned 16-bit character. That's why you can assign it to an int.
Hope this helps.
You can basically cast the char
to the int
and store it as int
:
int a = (int)'a';
System.out.println(a); //prints 97
Since Java can do the basic castings from your type specifications, you do not need to explicity write casting even.
int a = 'a';
System.out.println(a); // prints 97
The output is the ASCII value of the character stored in last. The ASCII value of the character 'a' is 97, and hence the output on the console is 97.
you have to take 'a' as a char
char char1 = 'a';
then cast it to int
int num = (int) char1 ;