What happens when you use arithmetic operators inside of a string declaration?

Viewed 80

If there is an arithmetic operator inside of a string declaration, how does the String treat the operator?
For example in this case:

String s = "de32";
s = s.charAt(0) * 2 + "";   
System.out.println(s);

String s is not dd but instead is 102. What is the * 2 mean for the string?

2 Answers

s.charAt(0) is a char ('d'), and char is a numeric type. The numeric value of the character 'd' is 100. Therefore s.charAt(0) * 2 simply multiplies that value by 2, which results in 200 (not 102 as you wrote).

Then the result is converted to a String, since you appended to it an empty String, so s is assigned "200".

The expression is evaluated left to right, so it is equivalent to:

s = (s.charAt(0) * 2) + "";
  • First the char 'd' is promoted to an int and multiplied by 2.
  • Then the resulting int (200) is appended to the empty String "". resulting in the String "200".

At 0 position char d is there and it is multiplied with 2. So ASCII value of d is multiplied by 2. Since ASCII value of d is 100 so it gives result 200. Then it is appended to empty string and give "200" as a string .

Related