在 Java 中的加法和连接


Java 中的“+”运算符既可用于添加数字,也可用于连接字符串。应该考虑以下规则。

  • 只有数字为操作数,结果将是数字。

  • 只有字符串为操作数,结果将是连接的字符串。

  • 如果数字和字符串都是操作数,则在字符串之前出现的数字将被视为数字。

  • 如果数字和字符串都是操作数,则在字符串之后出现的数字将被视为字符串。

  • 可以用括号来覆盖上述规则。

示例

创建一个名为 Tester 的 Java 类。

Tester.java

实时演示

public class Tester {
   public static void main(String args[]) {      
      //Scenario 1: Only numbers as operands to + operator
      System.out.print("Scenario 1: (1 + 2)  = ");      
      System.out.println(1 + 2);

      //Scenario 2: Only Strings as operands to + operator
      System.out.print("Scenario 2: (\"tutorials\" + \"point.com\") = ");      
      System.out.println("tutorials" + "points.com");

      //Scenario 3: both numbers and strings as operands to + operator
      //numbers will be treated as non-text till a string comes
      System.out.print("Scenario 3: (1 + 2 + \"tutorials\" + \"point.com\") = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com");

      //Scenario 4: both numbers and strings as operands to + operator
      //if string comes first, numbers will be treated as text.
      System.out.print("Scenario 4: (1 + 2 + \"tutorials\" + \"point.com\" + 3 + 4 ) = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com" + 3 + 4);

      //Scenario 5: both numbers and strings as operands to + operator
      //if string comes first, numbers will be treated as text.
      //Use brackets to treat all numbers as non-text
      System.out.print("Scenario 5: (1 + 2 + \"tutorials\" + \"point.com\" + (3 + 4)) = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com" + (3 + 4));
   }
}

输出

编译并运行文件以验证结果。

Scenario 1: (1 + 2)  = 3
Scenario 2: ("tutorials" + "point.com") = tutorialspoints.com
Scenario 3: (1 + 2 + "tutorials" + "point.com") = 3tutorialspoints.com
Scenario 4: (1 + 2 + "tutorials" + "point.com" + 3 + 4 ) = 3tutorialspoints.com34
Scenario 5: (1 + 2 + "tutorials" + "point.com" + (3 + 4)) = 3tutorialspoints.com7

更新于:2020 年 6 月 18 日

1 千+ 次浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.