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.