-2

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 );
    }

}
Molly
  • 1,887
  • 3
  • 17
  • 34
Si Ci Pin
  • 21
  • 1
  • 5

4 Answers4

2

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.

Ben
  • 66
  • 5
1

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
Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68
0

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.

0

you have to take 'a' as a char char char1 = 'a'; then cast it to int int num = (int) char1 ;

  • 1
    This is not entirely correct, eg consider what happens if the character is not in ASCII: you'll still get an integer value. – Mark Rotteveel Jan 23 '19 at 10:17