Java Program example to demonstrate String concat method

Program

public class StringConcat
{
	public static void main(String[] args)
	{
		String str = "welcome to oodlescoop";
		str = str.concat(" tutorials!!!");
		System.out.println("Concatenated String: " + str);
	}
}

Here’s an explanation of the StringConcat program:

Purpose

This Java program demonstrates the usage of the concat method in the String class to append one string to another.

1. Class Definition

public class StringConcat
  • Defines the class StringConcat.

2. Main Method

public static void main(String[] args)
  • Entry point for the program.

3. String Declaration and Initialization

String str = "welcome to oodlescoop";
  • A String variable named str is declared and initialized with the value "welcome to oodlescoop".

4. Concatenate Another String

str = str.concat(" tutorials!!!");
  • concat Method:
    • Appends the string " tutorials!!!" to the original string str.
    • The concat method returns a new string that combines the original string and the appended string.
    • In this case, "welcome to oodlescoop" is combined with " tutorials!!!" to form "welcome to oodlescoop tutorials!!!".
    • Important: Strings in Java are immutable. The original str is not modified. Instead, a new string is created and assigned back to str.

5. Print the Result

System.out.println("Concatenated String: " + str);
  • Prints the concatenated string:
    Concatenated String: welcome to oodlescoop tutorials!!!
    

Key Points About concat Method

  1. String Immutability:

    • Strings in Java are immutable. The concat method does not modify the original string but creates a new string with the concatenated content.
  2. Usage:

    • concat is used for appending one string to another.
    • Syntax: String result = original.concat(additionalString);
  3. Alternative:

    • You can achieve the same result using the + operator:
      str = str + " tutorials!!!";
      

Output

Concatenated String: welcome to oodlescoop tutorials!!!