Concatenating Strings

Next up, let’s look at how to append to existing strings.

We do this by combining strings, or to use the fancy word we concatenate.

How to Concatenate

To concatenate strings in Java we use the + operator. Yes, that’s the same one that we’d use to add numbers. But Java is smart enough to know that you can’t add strings and just sticks them together.

Let’s look at some code.

String a = "Hello";
String b = "There";
System.out.println( a + b );

This would output HelloThere. Notice that there’s no space because we didn’t tell Java to include a space. If you wanted to include a space you could do something like this and concatenate 3 strings together.

String a = "Hello";
String b = "There";
System.out.println( a + " " + b );

Two things to notice here. First, we concatenated 3 strings together. There’s an upper limit to how many you could concatenate, but it’s not realistic that you’d ever hit that limit. And second, we mixed variables containing strings along with a literal space. You’ll need that second piece for our first code break.

For this break we’re changing it up and implementing a method that returns a concatenated string containing the word "Hello" followed by a space with the string in name concatenated on the end.


Solution
public String sayHello( String name ) {
    String out = "Hello " + name; 
    
    return out; 
}

One thing to notice is that I included the space in the string with "Hello ".

Next?

There’s not much to concatenating strings. I’m convinced that remembering the word concatenate is harder than actually doing it.

Next up we’re going to look at the first string method in the AP Java Subset, equals.

In this series

A quick, short introduction to strings in Java.
You can't always work with string literals. You need variables.
Concatenation is the fancy word for combining multiple strings.
Built in method to see if two strings are the same.
Need to know how many characters are in a string? There's a method for that.
indexOf / lastIndexOf
CompSci.rocks Newsletter

Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?

Leave a Reply

Your email address will not be published. Required fields are marked *