Java - String concat() 方法



描述

Java String concat() 方法用於將指定的字串連線到此字串的末尾。連線是將兩個或多個字串組合成一個新字串的過程。由於 Java 中的字串是不可變的,因此一旦初始化,我們就無法更改字串值。

String 是一個儲存字元序列的物件。concat() 方法接受一個字串作為引數,該字串儲存另一個字串的值。如果一個字串的值為 null,則會丟擲異常。

語法

以下是 Java String concat() 方法的語法:

public String concat(String str)

引數

  • str - 這是連線到此字串末尾的字串。

返回值

此方法返回一個字串值,該值是當前字串和給定值連線操作的結果。

連線兩個非空字串示例

如果給定的字串值不為 null,則 concat() 方法會將它們連線起來並返回一個新的字串。

在下面的程式中,我們使用值“Hello”“World”建立了一個字串類的物件。使用concat() 方法,我們嘗試將它們連線起來。

package com.tutorialspoint;

public class Concat {
   public static void main(String[] args) {
      
      //create an object of the String
      String str1 = new String("Hello");
      String str2 = new String("World");
      System.out.println("The given string values are: " + str1 + " and " + str2);
      
      //using the concat() method
      System.out.println("After concatenation the new string is: " + str1.concat(str2));
   }
}

輸出

執行上述程式後,將產生以下結果:

The given string values are: Hello and World
After concatenation the new string is: HelloWorld

連線空字串時出現異常的示例

如果給定的字串引數值為null,則此方法會丟擲NullPointerException

在下面的示例中,我們使用值“Tutorials”例項化 String 類。使用concat() 方法,我們嘗試將當前字串值與null連線起來。

public class Concat {
   public static void main(String[] args) {
      try {
         
         //instantiate the String class
         String str1 = new String("Hello");
         String str2 = new String();
         str2 = null;
         System.out.println("The given string values are: " + str1 + " and " + str2);
         
         //using the concat() method
         System.out.println("After concatenation the new string is: " + str1.concat(str2));
      } catch(NullPointerException e) {
         e.printStackTrace();
         System.out.println("Exception: " + e);
      }
   }
}

輸出

以下是上述程式的輸出:

The given string values are: Hello and null
java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "str" is null
	at java.base/java.lang.String.concat(String.java:2769)
	at com.tutorialspoint.StringBuilder.Concat.main(Concat.java:11)
Exception: java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "str" is null

連線兩個空字串的示例

如果給定的字串值為,則 concat() 方法將返回一個空字串。

在此程式中,我們使用空值建立字串字面量。使用concat() 方法,我們將空字串值連線起來。由於這些值為空,因此此方法返回一個空字串。

package com.tutorialspoint;

public class Concat {
   public static void main(String[] args) {
      try {
         
         //create the String literals
         String str1 = "";
         String str2 = "";
         System.out.println("The given string values are: " + str1 + ", " + str2);
         
         //using the concat() method
         System.out.println("After concatenation the new string is: " + str1.concat(str2));
      } catch(NullPointerException e) {
         e.printStackTrace();
         System.out.println("Exception: " + e);
      }
   }
}

輸出

執行程式後,將返回以下輸出:

The given string values are: ,
After concatenation the new string is: 
java_lang_string.htm
廣告