• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using charAt() and adding it to a "result" String  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, I'm currently going through simple practice problems on CodingBat and ran into a problem; the goal is to copy each character in a string twice so that every /character is doubled. Here is the code:


So when I use the top piece of code, the result returns a string of numbers, rather than doubling each character, but the bottom piece of code works correctly. Can anyone explain to me why the top piece of code does this? Thank you
 
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The character datatype is a actually a numeric data type, between integer and byte, that represents a code point for a character. As a number you can add them and subtract them. So in the first section of code, the plus operator has a higher precedence than the += operator, this means that the two characters get added together first. Unless forced to do otherwise, the + operator converts its operands to integers before performing its action the chars are promoted to ints and the ints are added. After the addition, the += operator is evaluated and since the Left Hand side of the operator is a String, so the Right Hand side is converted to a String and String concatenation occurs instead of addition.

In the second code snippet, the two + operators have the same precedence so they are evaluated Left to Right. The first one has a String on its Left Hand side, so String concatenation occurs. The Right Side of the first operator is a char, and the conversion to String is the conversion to the character the char represents. Then the result of this String concatenation becomes the Left Hand side of the second + operation and the same thing occurs. Finally the result is assigned to the result variable.
 
henry xiao
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot! I don't recall ever reading about operator precedence in the book - I'll look more into it now
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!