Home Java Beginners Concatenating two Strings in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Concatenating two Strings in Java

Advertisement
In this section, you will learn how to concatenate or merge two strings in java.

Concatenating two Strings in Java

In this section we will help you, how to concatenate two strings in java. String are sequence of character which is used in java programming language. String is a class in java which provide method to concatenate string in java. The method concat(), which return a new string by adding  two strings. The String class include a method which concatenate strings in the java.lang package.

concat(String str);

This is a method that concatenate the two strings.

String str1="hello";
String str2=" Java";
str1.concate(str2);

In the above code declaring two string str1 and str2 and by concat()  method, which returns a new string as " hello Java".

You can also concat string using "+" operator in java which is commonly used :

" Hello " + " Java"  which result in " Hello Java ".

" + " operator is also used with other data type. Let's use this "+" operator with other data type like as follows :

int id = 1;
String result=" Hello " + "your id is "+result;
System.out.println(result);

As you can see the id is an integer but the output is in string as before. This is because id is converted internally into String representation within a String object. Compiler will convert the operand into its string equivalent whenever the other operand of the "+"  is an instance of String.

The following program will concatenate two string using conact() that concatenate the specified string to the end of the string and , you will get the concatenated string.

import java.util.Scanner;
public class Concatenate {
	public static void main(String args[])
	{
	  String str=args[0].concat(args[1]);
	  System.out.println("");
	  System.out.println("Concatenate String = "+str);
	  
	}
 }

Output of the program :

Download Source Code

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 24, 2013

Ask Questions?    Discuss: Concatenating two String in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com