AI Hints
Home›Java Tutorial›Strings, Joining Strings and String Methods
Java · Lesson 20 of 120

Joining Strings

Plus, concat, join.

⏱ 2 min read▶ Video at 26:16🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Joining strings together is called concatenation. In Java, the easiest way is with a plus sign.

  • Joining is concatenation
  • Use plus
  • Text and numbers

Joining with plus

Plus joins first name, a space, and last name. Plus equals adds to the end of an existing string. Numbers join too, they become text. But order matters. Java works left to right. One plus two is added first, then joined. But after text, the plus joins instead. Run it. We get three apples, but apples one two.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String first = "Ada";
        String last = "Lovelace";
        String full = first + " " + last;
        System.out.println(full);

        String greeting = "Hello";
        greeting += ", " + first;
        greeting += "!";
        System.out.println(greeting);

        System.out.println("Age: " + 36);
        System.out.println(1 + 2 + " apples");
        System.out.println("apples " + 1 + 2);
    }
}
Output
Ada Lovelace
Hello, Ada!
Age: 36
3 apples
apples 12

Other ways to join

Concat joins two strings, like plus. String dot join puts a separator between several strings. And repeat repeats a string, a number of times. Run it. Tea and cake, the three colours with commas, and ha ha ha.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String a = "tea";
        String b = a.concat(" and cake");
        System.out.println(b);
        System.out.println(String.join(", ", "red", "green", "blue"));
        System.out.println("ha".repeat(3));
    }
}
Output
tea and cake
red, green, blue
hahaha

Summary

Plus joins strings, and numbers become text. Java works left to right, so use brackets for sums. Join and repeat are handy helpers. Next, more string methods.

Key takeaways
  • a + b
  • Left to right
  • join, repeat
Next up: String Methods — change, search and slice