The println() method is often used to display variables.
To combine both text and a variable, use the + character:
String name = "John"; System.out.println("Hello " + name);
You can also use the + character to add a variable to another variable:
String firstName = "John "; String lastName = "Doe"; String fullName = firstName + lastName; System.out.println(fullName);
For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):
int x = 5; int y = 6; System.out.println(x + y); // Print the value of x + y
From the example above, you can expect:
x stores the value 5
y stores the value 6
To declare more than one variable of the same type, you can use a comma-separated list:
Instead of writing:
int x = 5; int y = 6; int z = 50; System.out.println(x + y + z);
You can simply write:
int x = 5, y = 6, z = 50; System.out.println(x + y + z);
You can also assign the same value to multiple variables in one line:
int x, y, z; x = y = z = 50; System.out.println(x + y + z);
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable code:
// Good int minutesPerHour = 60; // OK, but not so easy to understand what m actually is int m = 60;
The general rules for naming variables are: