How to Concatenate Two Strings in Java

How do I concatenate two strings in Java?

You can concatenate Strings using the + operator:

System.out.println("Your number is " + theNumber + "!");

theNumber is implicitly converted to the String "42".

Java Concatenating two Strings with only charAt

You are performing assignment, not concatenation, and you can't assign a char to a String variable anyway.

In order to concatenate the characters, you can use the + operator (or +=):

String concatenated = "";
for (int i = 0; i < firstString.length(); i++){
concatenated += firstString.charAt(i);
}

Or you can use a StringBuilder object and append the characters to it:

StringBuilder concatenated = new StringBuilder(firstString.length()+secondString.length());
for (int i = 0; i < firstString.length(); i++){
concatenated.append(firstString.charAt(i));
}
for (int i = 0; i < secondString.length(); i++){
concatenated.append(secondString.charAt(i));
}
System.out.println(concatenated.toString());

This is more efficient than the + operator, since it only generates one StringBuilder object, while the + operator generates a new String object each time you use it.

Most efficient way to concatenate Strings

String.concat is faster than the + operator if you are concatenating two strings... Although this can be fixed at any time and may even have been fixed in java 8 as far as I know.

The thing you missed in the first post you referenced is that the author is concatenating exactly two strings, and the fast methods are the ones where the size of the new character array is calculated in advance as str1.length() + str2.length(), so the underlying character array only needs to be allocated once.

Using StringBuilder() without specifying the final size, which is also how + works internally, will often need to do more allocations and copying of the underlying array.

If you need to concatenate a bunch of strings together, then you should use a StringBuilder. If it's practical, then precompute the final size so that the underlying array only needs to be allocated once.

How to concatenate two strings and omit possible duplicate word?

You need to find the last word in s1 and the first word in s2. If these words match, you omit one of them while concatenating.

For this, you can write a method like this:

private static String specialConcat(String s1, String s2) {
String lastWord = s1.substring(s1.lastIndexOf(" ") + 1);
String firstWord = s2.split(" ")[0];
if (firstWord.equals(lastWord)) {
return s1 + s2.substring(lastWord.length());
} else {
return s1 + " " + s2;
}
}

Here are some test cases including edge cases:

Assert.assertEquals("hello world am waiting",
specialConcat("hello world", "world am waiting"));

Assert.assertEquals("call attested with level A",
specialConcat("call attested", "attested with level A"));

Assert.assertEquals("", specialConcat("", ""));
Assert.assertEquals("hello", specialConcat("hello", "hello"));

Assert.assertEquals("hello world", specialConcat("hello", "world"));
Assert.assertEquals("hello world", specialConcat("hello world", "world"));
Assert.assertEquals("hello world", specialConcat("hello", "hello world"));
Assert.assertEquals("abc abcde", specialConcat("abc", "abcde"));

Not able to concat two sentences in Java

Edit:

If you change to nextLine(), the previous inputs don't consume the newline character, so you'll have to add in an extra scan.nextLine();.

See demo online


First, declare c (i.e. String c), and also a and b (or maybe you did it but forgot to put it in your post?)

But then, your problem is using Scanner::next instead of Scanner::nextLine.

.next() from the docs:

Finds and returns the next complete token from this scanner.

.next() takes the first token, using whitespace as the delimiter, so that's why your output is HackerRank is, assuming your c is holding something like is a great site.

Solution

Change:

c = scan.next(); to c = scan.nextLine();

How to concatenate 2 or more strings as one inside a string array in Java?

Probably the most concise way is:

  1. Construct an array of the right size:

    String[] result = new String[A.length - (y-1)];
  2. Copy the start and the end of the array using System.arraycopy:

    System.arraycopy(A, 0, result, 0, x-1);
    System.arraycopy(A, x+y-1, result, x+1, A.length-(x+1));
  3. Build the concatenated string:

    result[x-1] = String.join(" ", Arrays.asList(A).subList(x-1, x-1+y));

(Note: out by one errors may be present, owing to the date of writing)

String concatenation: concat() vs + operator

No, not quite.

Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

java.lang.String cat(java.lang.String, java.lang.String);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_2
12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;
18: astore_1
19: aload_1
20: areturn

So, a += b is the equivalent of

a = new StringBuilder()
.append(a)
.append(b)
.toString();

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

How does Java concatenate 2 strings?

'b' and 'c' are not Strings, they are chars. You should use double quotes "..." instead:

System.out.println("b" + "c");

You are getting an int because you are adding the unicode values of those characters:

System.out.println((int) 'b'); // 98
System.out.println((int) 'c'); // 99
System.out.println('b' + 'c'); // 98 + 99 = 197


Related Topics



Leave a reply



Submit