CodeAndWave
CodeAndWave

Reputation: 1604

Character subtraction in String

Here is the code snippet i am trying to figure out whats happening

String line = "Hello";
        for (int i = 0; i < line.length(); i++) {
        char character = line.charAt(i);
        int srcX = 0;
            if (character == '.') {
            }else{
                srcX = (character - '0') * 20;

                System.out.println("Character is " + (character - '0') +"     " + srcX);
            }
        }

and executing that code will result to this

Character is 24     480
Character is 53     1060
Character is 60     1200
Character is 60     1200
Character is 63     1260

How a character minus the string which is "0" result in integer?? and where does the system base its answer to have 24,53,60,60,63?

Upvotes: 1

Views: 2545

Answers (2)

ggbranch
ggbranch

Reputation: 559

http://www.ascii.cl/

'0' is 48 in ascii 'H' is 72.

Therefore 72-48 gives you 24

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

You are allowed to subtract characters because char is an integer type.

The value of a character is the value of its codepoint (more or less, the details are tricky due to Unicode and UTF-16 and all that).

When you subtract the character '0' from another character, you are essentially subtracting 48, the code point of the character DIGIT ZERO.

So, for example, something like '5' - '0' would evaluate to 53 - 48 = 5. You commonly see this pattern when "converting" strings containing digits to numeric values. It is not common to subtract '0' from a character like 'H' (whose codepoint is 72), but it is possible and Java does not care. It simply treats characters like integers.

Upvotes: 2

Related Questions