| Variables are containers for storing data values. In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotesint - stores integers (whole numbers), without decimals, such as 123 or -123float - stores floating point numbers, with decimals, such as 19.99 or -19.99char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotesboolean - stores values with two states: true or false
Declaring (Creating) Variables To create a variable, you must specify the type and assign it a value: type variableName = value;
Where type is one of Java's types (such as int or String), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable. To create a variable that should store text, look at the following example: String name = "John";
System.out.println(name);
To create a variable that should store a number, look at the following example: int myNum = 15;
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign the value later: int myNum;
myNum = 15;
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value: int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
Display Variables 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
- Then we use the
println() method to display the value of x + y, which is 11
Declare Many Variables To declare more than one variable of the same type, you can use a comma-separated list: 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);
One Value to Multiple VariablesYou 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);
|