Java String concat() method with example

Java String concat() method concatenates the specified string to the end of this string. If the length of the argument string is 0, then this String object is returned. Otherwise, a String object is returned that represents a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Examples: “cares”.concat(“s”) returns “caress” “to”.concat(“get”).concat(“her”) returns “together”

Method Signature

public String concat(String str)

Parameters:

str – the String that is concatenated to the end of this String.

Returns:

a string that represents the concatenation of this object’s characters followed by the string argument’s characters.

String concat() internal Implementation

 public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }

Java String concat() method example

package com.ehowtonow.java.lang.string;

public class ConcatExample {

	public static void main(String[] args) {

		String s = "First String ";
		s = s.concat("Second String ");
		System.out.println(s);
		
		s.concat("Third String");
		System.out.println(s);
	}

}

Concat methods returns final output string. We must explicitly assign the result to the reference variable . Check second out “Third String” not append to ” First String Second String “

Output

First String Second String
First String Second String


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. How to convert a String to Upper case
  2. Java String codePointBefore() method with example
  3. Java String compareToIgnoreCase() method with example
  4. Java String copyValueOf(char[] data, int offset, int count) method with example
  5. How to find last occurrence of substring inside string
  6. Java String indexOf(int ch) method with example
  7. How to get Character unicode point in a String
  8. Java String codePointAt() method with example
  9. Java String contentEquals(CharSequence cs) method with example
  10. Java String indexOf(String str) method with example
  11. How to search a word inside String
  12. How to Split the String in Java
  13. How to convert a String to Lower case
  14. Java String format(String format, Object… args) method with example
  15. Java String Compare

Be the first to comment

Leave a Reply