Home > Tutorial > Java String Concat Example

Java String Concat Example

The concat() method of String class will concatenate the specified string to the end of a string. Why not just use the “+” operator instead of concat()? Good question. Both concat() method and + operator will concatenate a string, but they do it in slightly different ways.

concat() will return a new String object only when the length of argument string is greater than zero. Ff the length of argument string is zero, then concat() returns the same original string as opposed to returning a new String object.

The + operator creates a new String object every time it concatenates something, except when the concatenation is done at compile time. The concat() method is considered to be better in terms of performance over the + operator.

Method Parameters Return Type Exceptions Description
concat() String String none Concatenates the specified string to the end of this string.


Java String Concat Source Code

The sample code below gives an example how to use the String concat() method.

package com.jcd.java.tutorials;

public class JavaStringConcat 
{

	public static void main(String[] args) 
	{

		//Use conncat() with Strings
		String jcdString1 = "Java Code Depot";
		String jcdString2 = jcdString1.concat(" Com");
		System.out.println("jcdString1: "+jcdString1);
		System.out.println("jcdString2: "+jcdString2);
		
		//Use concat() without any variables
		System.out.println("Java ".concat("Code ").concat("Depot ").concat("Com"));

	}

}


Java String Concat Output

jcdString1: Java Code Depot
jcdString2: Java Code Depot Com
Java Code Depot Com


Smedley
Posted by

Smedley

Smedley has been doing software development for years, which mainly docues on C and C++. In the past number of years, he has focused on Java programming.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot