用add运算符了解Java字符串 [英] understanding the java string with add operator

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

问题描述

我试图了解编译器如何查看以下打印语句.这很简单,但有点有趣.

I am trying to understand how the compiler views the following print statements. It is simple yet a bit intriguing.

这将打印出附加值.有说服力.

This prints the added value. Convincing enough.

System.out.println(1 + 2); //输出:3

System.out.println(1+2); //output: 3

以下内容的输出也令人信服:

The output from the following looks convincing as well:

System.out.println(1 + 2 +"3");//输出:33

System.out.println(1+2+"3");//output: 33

我的问题(基于上述行为)在这里.

My question (based on the behavior above) is here.

System.out.println("1" + 2 + 3);//应该是15吗?不.是123.

System.out.println("1"+2+3);//Should be 15 right? NO. It is 123.

我尝试了其他类似的陈述.我能够看到一种清晰的行为.

I tried few other such statements which were along the same lines. I was able to see one two clear behaviors.

  • 如果整数在最前面而不加引号,则将它们加起来,随后的整数只是作为后缀附加到从前面开始的值上.

  • If integers are at the front, without the quotes, they are added and subsequent integers are just appended as suffix to the added values from the front.

如果该语句以字符串开头,并用引号引起来,则所有其他后续元素都将附加为后缀.

if the statement starts with string, under quotes, then all other subsequent elements get appended as suffix.

这是Java api文档中的某个地方吗?或者只是非常明显的字符串或添加操作符行为,我没有看到.您的任何宝贵见解都会受到赞赏.

Is this somewhere in the java api docs? Or just very obvious string or add operator behavior which I am not seeing. Any of your valuable insights will be appreciated.

这是代码段:

public static void main(String[] args) {
    System.out.println(1+2);
    System.out.println(1+2+"3");
    System.out.println("1"+2+3); 
    System.out.println("1"+2+"3");
    System.out.println("1"+2);
}
//   The Console output:
//      3
//      33
//      123
//      123
//      12

推荐答案

我猜

I guess the Java specification explains it best:

+运算符在语法上是左联想的,无论它是否 由类型分析确定以表示字符串连接或 数字加法.在某些情况下,需要小心才能获得所需的 结果.例如,表达式:

The + operator is syntactically left-associative, no matter whether it is determined by type analysis to represent string concatenation or numeric addition. In some cases care is required to get the desired result. For example, the expression:

a + b + c

始终被认为是含义:

(a + b) + c

因此,如果aString,则它将与b连接.结果将是String类型,因此它将继续与c连接.

So, if a was a String, then it concatenates with b. The result would be of String type, hence it continues to concatenate with c.

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

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