Line At A Time
Lesson 5: String and Number
String and Number See what happens when you add a number to text.
1public static void main(String[] args) {
2 int ten = 10;
3 String str = "ten";
4 System.out.println(ten + str);
5}
Terminal
$ javac Main.java
$ java Main
10ten
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.
int ten = 10;
int declares a variable that stores a whole number (an "integer") like 1, 5 or 1000. The = sign stores the value on the right into the variable named on the left, and the semicolon ; ends the statement, like a full stop at the end of a sentence.
String str = "ten";
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(ten + str);
When you use + between a number and a String, Java turns the number into text and glues the two together: 10 + "ten" becomes "10ten". With two numbers + means add, but as soon as a String is involved, + means join.
}
This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.