Variable Addition
Add two variables together and print the result.
1public static void main(String[] args) {
2 int five = 5;
3 int ten = 10;
4 System.out.println(five + ten);
5}
$ javac Main.java
$ java Main
15
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 five = 5;- 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.
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. You can create as many variables as you like, as long as each has a different name.
System.out.println(five + ten);- System.out.println(...) prints whatever is inside the parentheses to the terminal, then moves to a new line. Read the name carefully: print-l-n is short for "print line". Java works out five + ten first (5 + 10 = 15) and then prints the answer.
}- This closing curly brace } ends the main method. In Java every opening brace { must have a matching closing brace }.