Write a program to concatenate Two strings


This Java program demonstrates the use of the conCat() method to concatenate two strings.

  • public class Concat_String - Defines a class named Concat_String..
  • public String conCat(String s1, String s2) - Defines a method named conCat() that takes two strings s1 and s2 as input parameters and returns a string as output. This method checks whether the length of both strings is not zero and the last character of s1 is equal to the first character of s2. If both conditions are true, then it returns a concatenation of s1 and s2 with the first character of s2 removed. Otherwise, it returns a simple concatenation of s1 and s2..
  • public static void main(String[] args) - Defines the main method..
  • Concat_String m= new Concat_String(); - Creates an object of the Concat_String class..
  • String str1 = "Mark"; - Initializes a string variable str1 with the value "Mark"..
  • String str2 = "Kate"; - Initializes a string variable str2 with the value "Kate"..
  • String s1 = str1.toLowerCase(); - Converts the string str1 to lowercase and assigns it to a new string variable s1..
  • String s2 = str2.toLowerCase(); - Converts the string str2 to lowercase and assigns it to a new string variable s2..
  • System.out.println("String : "+s1+" and "+s2); - Displays the values of s1 and s2..
  • System.out.println("String After Concatination are: "+m.conCat(s1,s2)); - Calls the conCat() method of the Concat_String class and displays the concatenated string.

Source Code

import java.util.*;
public class Concat_String 
{
	public String conCat(String s1, String s2) 
	{
		if (s1.length() != 0 && s2.length() != 0 && s1.charAt(s1.length() - 1) == s2.charAt(0))
			return s1 + s2.substring(1);
		return s1 + s2;
	}
 
    public static void main (String[] args)
    {
		Concat_String m= new Concat_String();
		String str1 = "Mark";
		String str2 = "Kate";		
		String s1 = str1.toLowerCase();
		String s2 = str2.toLowerCase();
		System.out.println("String : "+s1+"  and  "+s2);
		System.out.println("String After Concatination are: "+m.conCat(s1,s2));
    }
}

Output

String : mark  and  kate
String After Concatination are: markate

Example Programs