1

I am new to Java Programming and I stumbled upon below copy pasted code ( which I found from: How to sum digits of an integer in java?)

I am struggling to understand this code and basically would like an explanation on the following line: sum += c -'0'; What does this line evaluate to? and what is the purpose of -'0' ?

thanks all in advance.

import java.util.Scanner;

public class RandomPractice1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
            System.out.println("enter some digits: ");
         String digits = input.nextLine();  //try digits 55
        int sum = 0;
        for (char c : digits.toCharArray()) {
            sum += c -'0';
            
    }
        
        System.out.printf("sum of numbers %s is %d\n", digits, sum); //the answer is 10
}  }

1 Answers1

1

char values in Java have an integer representation, but it doesn't correspond to their integer value. '0' is 48, '1' is 49, and so on.

Assuming you only enter decimal digits, then subtracting '0' from each char is one way to get their apparent integer values, so that when you sum them you get the expected total.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • thank you! does this mean that sum += c -'0'; is equivalent to sum = sum + c - '0'. For example: if input is 55, then would it be read as: sum = 0 + 53 - 48 = 5? – 12InchesUnBuffed Nov 01 '21 at 02:54
  • @12InchesUnBuffed Yes, exactly right for the first time through the loop. (In the second, the old sum of 0 would be replaced with 5.) – Bill the Lizard Nov 01 '21 at 12:29
  • oh okay i see so basically it is necessary for the loop to move to the next position? otherwise, without the +=, the code will not execute through the loop? I tried to remove the += and replaced with only = and my output shows as 5. It seems that the code ignores the first char '5' and only executes the last char '5' minus char '0'. Am I understanding the mechanics correctly? or am I misunderstanding? thank you a lot for your time and help! – 12InchesUnBuffed Nov 02 '21 at 16:54
  • @12InchesUnBuffed Yes `sum += c -'0'` is adding a value to sum and overwriting the old sum. `sum = c -'0'` is just assigning a new value to sum without adding, so you'd end up with *only* the last value in the loop. – Bill the Lizard Nov 02 '21 at 19:41