Java Strings
A String is a type that holds text. The text of a string sits inside double quotes.
Print a string
The variable holds text in double quotes. The print line shows the text without the quotes.
public class Main {
public static void main(String[] args) {
String city = "Oslo";
System.out.println(city);
}
}Join strings with +
The + operator joins the parts into one line. A space sits between the two values in the join.
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
String name = "Ada";
System.out.println(greeting + " " + name);
}
}Join order changes the result
Text at the start pulls later numbers into the join as text. Numbers at the start add up before the text arrives.
public class Main {
public static void main(String[] args) {
System.out.println("10" + 20 + 30);
System.out.println(10 + 20 + "30");
}
}A quote inside text
A backslash marks the quote as part of the text. The text ends at the final quote without a backslash.
public class Main {
public static void main(String[] args) {
String line = "She said \"hello\" today.";
System.out.println(line);
}
}Example
public class Main {
public static void main(String[] args) {
String firstName = "Mia";
String lastName = "Chen";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
System.out.println(fullName + " is here.");
}
}Key points
- A String variable holds text.
- Double quotes mark the start and the end of the text.
- The + operator joins values into one longer string.
- Values in a join are handled from left to right.
- A backslash before a double quote puts that quote inside the text.
- The == operator compares whether two variables hold the same object, so text compares with equals.
In this example, firstName holds Mia and lastName holds Chen. The join builds fullName with a space between the parts. The print lines show the full name on its own and inside a sentence.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does "10" + 20 + 30 print?