Sub topic 1
Variables and Types
Variables and Types
A variable is a named place that holds a value. For example, a variable named count can hold the number of items in a box.
Every Java variable has a type. The type tells Java what kind of value the variable can hold. For example, int holds whole numbers. Choosing a type helps Java catch mistakes, such as trying to put text into an int variable.
Primitive and Reference Types
Java has eight primitive types. A primitive variable holds a simple value directly, such as a number.
A reference type works differently. Its variable holds a reference to an object, which is a piece of data created by a program. For example, String is a reference type used for text. A String variable refers to a text object.
Six primitive types hold numbers. The other two are char and boolean.
Declaring, Initializing, and Updating Variables
A declaration gives a variable its type and name. Initialization gives it its first value. Assignment gives it a value, including when that value changes.
Save this program as VariablesExample.java:
class VariablesExample {
public static void main(String[] args) {
int count = 3;
String name = "Mira";
count = count + 1;
System.out.println(count);
System.out.println(name);
}
}In int count = 3;, the program declares and initializes count. Later, count = count + 1; adds one to its value and assigns the result back to count.
Run the program with:
javac VariablesExample.java
java VariablesExampleIt prints 4 and then Mira, each on its own line.
Whole Numbers: byte, short, int, and long
These four primitive types hold whole numbers. They differ in the range of values they can hold.
| Type | Range |
|---|---|
| `byte` | -128 to 127 |
| `short` | -32,768 to 32,767 |
| `int` | -2,147,483,648 to 2,147,483,647 |
| `long` | About -9 quintillion to 9 quintillion |
Use int for most whole numbers. Use long when the value needs a larger range. For example, long population = 10000000000L; uses L to mark the number as a long value.
Floating-Point Numbers: float and double
Floating-point types hold numbers with fractional parts, such as 20.5. The two types are float and double.
float temperature = 20.5f;usesfto mark the value as afloat.double price = 19.99;usesdouble, the usual choice for fractional values.
Floating-point values do not always represent decimals exactly. For now, remember that double can usually keep more digits than float.
Exercise
If int count = 3; is followed by count = count + 2;, what value does count hold? Is int a primitive or reference type?
Show answer
It holds 5. int is a primitive type.