Variables
Java Variables
There are various kinds of variables in Java, such as:
- String – stores text, such as “Hello”. String values are surrounded by double quotes
- int – stores integers (whole numbers), without decimals, such as 123 or -123
- float – stores floating point numbers, with decimals, such as 19.99 or -19.99
- char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
- boolean – stores values with two states: true or false
Declaring (Creating) Variables
A variable may only be created by designating its type and giving it a value:
Syntax
type variableName = value;
where variableName is the name of the variable (like x or name), and type is one of the Java types (like int or String). Values are assigned to the variable using the equal sign.
Take a look at the following example to learn how to construct a variable that will hold text:
Example
Make a variable called name of type String and put “John” in it:
String name = "John";
System.out.println(name);
Take a look at the following example to learn how to build a variable that should hold a number:
Example
Make a variable of type int named myNum, and give it the value 15:
int myNum = 15;
System.out.println(myNum);
It is also possible to declare a variable without first assigning a value, then assign the value afterwards:
Example
Changing myNum’s value from 15 to 20:
int myNum;
myNum = 15;
System.out.println(myNum);
Keep in mind that updating a variable that already exists will replace its prior value:
Example
Changing myNum’s value from 15 to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
Final Variables
Use the final keyword (this will declare the variable as “final” or “constant,” which means unchangeable and read-only) if you don’t want other people (or yourself) to replace existing values:
Example
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final variable
Other Types
An example of declaring variables of different types:
Example
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";