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

更新日期: 18-6 月-2020

1 千次+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.