2

I am having below simple Java program which I am struggling to understand. Can someone please help here?

class Solution {
  public static void main (String args[])
  {
    String code ="1123";
    System.out.println( (code.charAt(0) - '1' + 'a' ));
  }
}

Output : 97

I understand it is returning ASCII value of character 'a' but - '1' + 'a' part is confusing, what is it exactly doing ?

Mead
  • 100
  • 10
Shashi
  • 2,686
  • 7
  • 35
  • 67
  • 1
    Hi. System.out.println has overload for int, long, String. when you call `code.charAt(0)`, the result is "char" type but there is no arithmetic calculation on char except they converted to int, so the result of calculation is a integer and java choose System.out.println(int). you must cast to char before print it. – Amin Sep 30 '18 at 04:43

2 Answers2

4

Let's look at it this way.

String code ="1123";
System.out.println( (code.charAt(0) - '1' + 'a' ));

In this case, the code.charAt(0) call is essentially turning your code string into an array, and taking the 0-th element, which is 1.

So, the mathematics that are occurring are at the ASCII level, like you notated. The ASCII value for 1 is 49, and the ASCII value for a is 97.

So the mathematics say: 49 - 49 + 97 Which, as we know, equals 97, which is what the output of this function is.

To recap:

  1. The String "code" is turned into an array of characters using the .charAt() function, and the 0th element of the array is referenced, which is 1
  2. The ASCII value of 1 is the subtracted from, 1
  3. The ASCII value of a is then printed, which is 97

Hopefully this helps!

EDIT: Here is a good reference for an ASCII lookup table: http://www.asciitable.com/

artemis
  • 6,857
  • 11
  • 46
  • 99
1

Since the arithmetic calculations on java chars result in formation of integer.

           char a='1',b='3';
           char x=a+b;//compilation error

so arithmetic operations on java chars occur at ascii level therefore you must cast it to char and assign to x.

            char x=(char)(a+b);//executed

You may find the better explanation over here