Coding for All
Lesson 4: String Concatenation
String Concatenation Join two Strings together with +.
1public static void main(String[] args) {
2 String hello = "Hello";
3 String world = "World";
4 System.out.println(hello + world);
5}
Terminal
$ javac Main.java
$ java Main
HelloWorld
Every line, explained
public static void main(String[] args) {
Every Java program starts at the main method. When you run the program, Java looks for this exact line, public static void main(String[] args), and runs everything between its { and } from top to bottom.
String hello = "Hello";
String declares a variable that stores text. In Java, text always goes inside double quotes: "like this". Single quotes are only for one single character (like 'A'), so writing 'Hello' would be an error. Also notice that String starts with a capital S.
String world = "World";
String declares a variable that stores text. In Java, text always goes inside double quotes: "like this". Single quotes are only for one single character (like 'A'), so writing 'Hello' would be an error. Also notice that String starts with a capital S.
System.out.println(hello + world);
Using + between two Strings glues them together; this is called concatenation. Java joins them exactly as they are, without adding a space, so this prints HelloWorld. To get a space you would write hello + " " + world.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.