串联字符串和数字Java [英] concatenating string and numbers Java

查看:112
本文介绍了串联字符串和数字Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在这些情况下输出会有所不同?

Why is the output different in these cases ?

int x = 20,y = 10;

System.out.println(打印:+ x + y); ==> 打印:2010

System.out.println(printing:+ x * y); ==> 打印:200

为什么不是第一个输出30?它与运算符优先级有关吗?像第一次打印和x连接,然后这个结果字符串和y连接?我是否正确?

Why isn't the first output 30? Is it related to operator precedence ? Like first "printing" and x are concatenated and then this resulting string and y are concatenated ? Am I correct?

推荐答案

BODMAS 规则

我在下面显示从高到低的优先顺序:

B  - Bracket 
O  - Power
DM - Division and Multiplication
AS - Addition and Substraction

这可以从 从左到右 如果运算符具有相同的优先级

现在

System.out.println(打印:+ x + y);

打印::是字符串

+:是Java中唯一一个将Number连接到String的重载运算符。
As我们这里有2个+运算符,并且x + y落在print:+ 之后已经发生,它将x和y视为字符串。

"+" : Is the only overloaded operator in Java which will concatenate Number to String. As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.

因此输出 2010。

Syste m.out.println(打印:+ x * y);

这里

*:优先级高于 +

所以它的 x * y 然后打印:+

因此输出 200

如果你想要这样做在第一种情况下输出200:

System.out.println("printing: "+ (x+y));

优先顺序 支架 更高加法

这篇关于串联字符串和数字Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆