0
String c="12345";
for(char k:c.toCharArray())
System.out.print(k+4);

This program outputs: 5354555657

I don't really understand why this is out putting those numbers. The only pattern I see is that it prints a "5" then takes the "1" from the string and adds 2 to make "3". Then prints a "5" then takes the "2" from the string and adds 2 to make "4" then prints a "5" and so on.

3
  • asciitable.com Commented Mar 2, 2018 at 17:42
  • 1
    It prints 53|54|55|56|57. Just adds 4 to the ascii values of the respective characters. (for eg: "1" has ASCII of 49 => Add 4 => 53) Commented Mar 2, 2018 at 17:44
  • Each char can be treated as numeric value, representing its index in Unicode Table. Also in Java char + int = int which means that when we end up with '1'+4 it is evaluated as 49 (index of character '1') incremented by 4 which is 53. Commented Mar 2, 2018 at 17:49

2 Answers 2

1

The characters in the array, when promoted to int for the addition of 4, take on their underlying Unicode value, of which the ASCII values are a subset. The digits 0-9 are represented by codes 48-57 respectively. Characters '1' through '5' are 49-53, then you add 4 and get 53-57.

After adding, cast the sum back to char so print can interpret it as a char.

System.out.print( (char) (k+4));

Output:

56789
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this makes sense. I appreciate the reply.
0

This is because you're adding an int to a character (it's casting your character to an int and then adding it to 4, then printing it out).

You need to do:

System.out.println(Character.getNumericValue(k) + 4);

4 Comments

Awesome response! This is for a UIL question my kids are having on the written portion of Computer Science.
The ASCII for k is 107 though, so I don't think I am following you.
@TroyWalker k is valuable holding as value characters like '1', '2', you need to look at their indexes.
@TroyWalker - it's the ascii values for the numerical character, not k. For instance, 1 in ascii is 47, 2 is 48, etc (it's casting the char to an int). Adding those to the value of k gives you your output above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.