WilliamJestes
WilliamJestes

Reputation: 77

Why is it subtracting incorrectly from char?

So here is my code:

public class charTest
{
  public static void main(String[] args)
  {
    String bigNum = ("789");
    char s1 = bigNum.charAt(0);
    System.out.println(s1);
    System.out.println(s1-1);
  }
}

It prints 7 on the first line, then it prints out 54 on the next line, why? I have a really really long number that I have as a string and I am referencing individual numbers in it seperately. I just did the subtraction test to see if it was working correctly. Any insight?

Upvotes: 0

Views: 52

Answers (2)

Reimeus
Reimeus

Reputation: 159754

The unicode point value of 7 (character) is 55. Subtracting 1 gives 54

The first println statement uses uses an char argument whereas the second uses an int (Subtraction of a int from a char causes widening to an int)

to get 6 you could do

System.out.println(Character.getNumericValue(s1) - 1);

Upvotes: 5

Andrew Johnson
Andrew Johnson

Reputation: 7289

s1 is a char and prints as such. s1 - 1 is being implicitly cast to an int as prints as an int. i.e. the toString method is being called on the value of 54.

Upvotes: 0

Related Questions