Variables
Variables
•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
To create a variable, you must specify the type and assign it a 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).
Create a variable called myNum of type int and assign it the value 15:
To declare more than one variable of the same type, you can use a comma-separated list:
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes
A primitive data type specifies the size and type of variable values, and it has no additional methods.
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are
byte, short, int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals. There are two
types: float and double.
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial, the int
data type is the preferred data type when we create variables with a numeric value.
The float and double data types can store fractional numbers. Note that you should end the value with an "f"
for floats and "d" for doubles:
YES / NO
ON / OFF
TRUE / FALSE
Characters
The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':
public class Main {
public static void main(String[] args) {
B
char myGrade = 'B';
System.out.println(myGrade);
}
}
Alternatively, if you are familiar with ASCII values, you can use those to display certain characters:
Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
The addition assignment operator (+=) adds a value to a variable:
The return value of a comparison is either true or false. These values are known as Boolean values.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Logical operators are used to determine the logic between variables or values: