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?
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) + "";
char
'd' is promoted to an int
and multiplied by 2
. int
(200) is appended to the empty String
"". resulting in the String
"200". 在0位置,char d在那里并且它乘以2.所以d的ASCII值乘以2.由于d的ASCII值是100所以它给出结果200.然后它被附加到空字符串并给出“200”作为一个字符串。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.