Variables allow us to associate names with values. In Java you must declare a variable before you use it. To declare a variable you specify a type and a name followed by a semicolon.
You can also set the value of the variable when you declare it to the result of an expression.
type name = expression;
The type can be any of the primitive types (int, boolean, byte, char, double, float, long, short), a class name, or an interface name. The convention is to start variable names with a lowercase letter and uppercase the first letter of each additional word.
> int i; > double totalBill = 32.43 + 20 * 32.43; > String name = "Mark Guzdial"; > Picture pictureObj; > List studentList = null;
Variable names can be made up of letters, digits, underscores, or currency symbols. They can start with any of these except a digit. Variables can be any word except the reserved words. The reserved words are:
Most of the reserved words are also keywords. The only ones that are not keywords are null, true, and false. All of the Java reserved words have only lowercase letters.
We can use System.out.print or System.out.println to print the value of a variable. The second one will also force a new line after the value has printed.
> int x = 10 > System.out.println(x); 10 > String name = "Barbara Ericson"; > System.out.println(name); Barbara Ericson