Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java String concat() method
Syntax and Examples



Introduction

The concat() method in Java is a straightforward way to join two strings together. Think of it like physically attaching two pieces of string – the result is one longer string containing both original sequences.

Syntax


pubblic String concat(String str)

Parameters

Parameter Description
str The string to be concatenated with the current string. It can be null, in which case it is treated as an empty string.

Return Value

This method returns a new string that is the concatenation of the sequence characters of the current string and the string argument.

Examples

Example 1: Basic Concatenation

Let's start with a simple example. We have two strings, "Hello" and " World", and we want to combine them using concat().


String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2);
System.out.println(result);

Hello World

In this example, str1.concat(str2) creates a new string that is "Hello" followed by " World". The result is then printed to the console.

Example 2: Concatenating with an Empty String

What happens if you try to concatenate with an empty string? It doesn’t change the original string, but it still returns a new one.


String str1 = "Java";
String str2 = ""; // An empty string
String result = str1.concat(str2);
System.out.println("Original: "+str1 +", Result:"+result);

Original: Java, Result:Java

Here, concatenating "Java" with an empty string doesn't modify the original string. The result is still "Java". This highlights that concat() always returns a *new* string.

Example 3: Concatenating Multiple Strings

You can chain multiple calls to concat() together if you want to combine more than two strings.


String str1 = "Hello";
String str2 = " ";
String str3 = "World";
String result = str1.concat(str2).concat(str3);
System.out.println(result);

Hello World

In this case, we first concatenate str1 with str2 (resulting in " Hello "), and then we concatenate the result with str3 to get "Hello World". This demonstrates how you can build up strings step-by-step.

Example 4: Handling Null Values

The concat() method handles null values gracefully. If you try to concatenate with a null string, it's treated as an empty string.


String str1 = "Hello";
String str2 = null;
String result = str1.concat(str2);
System.out.println(result);

Hello

Because str2 is null, it's treated as an empty string when concatenated with “Hello”, so the output remains “Hello”.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M