All Posts

Java concat() method

Java concat() method

The Java concat() method is used to combine two strings into one. It’s a method of the String class. This method appends one string to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

Method signature

public String concat(String str)

str: The string to be concatenated to the end of the current string.

The concat() method returns a new string that is the concatenation of the current string and the string provided as a parameter. The original string is not modified because strings in Java are immutable.

Example

Let’s understand the usage of the method with an example program:

package com.testingdocs.stringmethods;

public class ExampleProgram {

	public static void main(String[] args) {
		String str = "TestingDocs";
		System.out.println(str.hashCode());
		// concat() method demo
		str = str.concat(".com");
		System.out.println(str);
		System.out.println(str.hashCode());
	}
}

Program Output

The output of the program is as follows:

1555687499

TestingDocs.com

566048094

Java concat method

Notice that the hashCode of the string variable is different before and after the concatenation. This is because, in Java, String objects are immutable, meaning once a String object is created, it cannot be modified. When you perform a concatenation operation, a new String object is created.

When you concatenate strings, a new String object is created. The hashCode of a String is computed based on its content.

Java Tutorials

Java Tutorial on this website: