java 文字列を連結する

java 文字列を連結する

javaで、文字列を連結する手順を記述してます。「concat​」を使用します。

環境

  • OS windows11 home
  • java 19.0.1

手順

Unicodeコー文字列を連結するには、「concat​」で可能です。

文字列.concat​(文字列)

実際に、使用してみます。

public class App {
    public static void main(String[] args) throws Exception {

        String str1 = "hello";
        String str2 = "world";

        System.out.println(str1.concat(str2)); // helloworld      

    }
}

連結されていることが確認できます。

「null」を指定するとエラーとなります。

public class App {
    public static void main(String[] args) throws Exception {

        String str1 = null;
        String str2 = "world";

        System.out.println(str1.concat(str2));
        // Exception in thread "main" java.lang.NullPointerException: 
        // Cannot invoke "String.concat(String)" because "<local1>" is null
        // at App.main(App.java:7)   

    }
}

「+」演算子

連結は「+」演算子でも可能です。

public class App {
    public static void main(String[] args) throws Exception {
        
        String str1 = "hello";
        String str2 = "world";

        System.out.println( str1 + str2 ); // helloworld

    }
}

「null」があると「null」と表示されます。

public class App {
    public static void main(String[] args) throws Exception {
        
        String str1 = null;
        String str2 = "world";

        System.out.println( str1 + str2 ); // nullhello

    }
}