A variable is a named place in memory that holds a value. In Java, every variable has a type that you write when you create it, and that type never changes. An int variable always holds a whole number; a String variable always holds text.
Declaring types takes a few extra words, but it gives you a safety net: if you try to put text into a number variable, the compiler stops you before the program even runs. In large programs with many people working on them, that saves a lot of debugging.
In this lesson you'll declare variables, learn the most common types, create constants with final, and convert values from one type to another.
Declaring a variable
Write the type, the name, an equals sign and the value, then a semicolon:
int age = 15;
String name = "Leo";You can declare a variable first and give it a value later, int score; then score = 10;, but you must assign a value before you use it. Change the value at any time with =. You don't repeat the type when you do: score = 25;.
The most common types
| Type | Holds | Example |
|---|---|---|
int | whole numbers | int lives = 3; |
double | decimal numbers | double price = 9.99; |
boolean | true or false | boolean isOpen = true; |
char | one character, in single quotes | char grade = 'A'; |
String | text, in double quotes | String city = "Oslo"; |
int, double, boolean and char are primitive types, built into the language and written in lowercase. String starts with a capital letter because it's a class, which is why strings have useful methods like name.length() and name.toUpperCase().
Other primitive types: long, float, byte and short
int and double cover most everyday values, but Java has eight primitive types in total. The other four exist for very large numbers or for saving memory:
| Type | Size | Range or use |
|---|---|---|
byte | 8 bits | -128 to 127, raw file and network data |
short | 16 bits | -32,768 to 32,767, rarely used |
int | 32 bits | about ±2.1 billion |
long | 64 bits | about ±9.2 quintillion, for IDs, timestamps and file sizes |
float | 32 bits | decimals with about 7 significant digits |
double | 64 bits | decimals with about 15 to 16 significant digits |
Number literals are int and double by default. A number too big for an int needs an L at the end, and a float needs an f:
long worldPopulation = 8_100_000_000L;
float ratio = 0.75f;The underscores are optional separators that make long numbers easier to read; Java ignores them. Use a capital L, because a small l looks too much like the digit 1. In practice, choose int for whole numbers and double for decimals unless you have a reason not to.
Primitive types and wrapper classes
Each primitive type has a matching wrapper class: Integer for int, Double for double, Boolean for boolean, Character for char, and so on. Wrappers are objects, so they can be stored in collections such as ArrayList<Integer> and can hold null, which a primitive can't.
Java converts between the two automatically, which is called autoboxing and unboxing: Integer count = 5; and int n = count; both just work. The wrapper classes are also where the useful helper methods live, such as Integer.parseInt(), Integer.MAX_VALUE and Character.isDigit().
Naming rules and constants
- Names may contain letters, digits,
_and$, but can't start with a digit. - They're case-sensitive:
totalandTotalare different. - Java uses camelCase: start lowercase and capitalise each new word, as in
totalPriceorisLoggedIn.
Add final to make a constant, a variable that can't be changed after it's set. Constants are written in UPPER_CASE by convention:
final double VAT_RATE = 0.2;Converting between types
Java converts automatically when no information can be lost, for example from int to double. Going the other way needs a cast: the target type in brackets.
double exact = 9.7;
int whole = (int) exact; // 9, the decimal part is cut offTo turn text into numbers use Integer.parseInt("42") or Double.parseDouble("3.5"). To turn anything into text, join it with a string: "" + 42, or use String.valueOf(42).
Java Variables Syntax
Variables and casting
type name = value;
final type CONSTANT_NAME = value;
int n = (int) 3.9; // 3
int fromText = Integer.parseInt("12");
double d = Double.parseDouble("2.5");Java Variables Summary
- Declare variables as
type name = value;. - Common types:
int,double,boolean,charandString. - Text uses double quotes; a single
charuses single quotes. finalmakes a constant. Java names use camelCase; constants use UPPER_CASE.- Cast with
(int) value; parse text withInteger.parseInt()orDouble.parseDouble().
Java Variables Examples
Each example shows the code, the output it produces and what each part does.
A student record
public class Main {
public static void main(String[] args) {
String name = "Leo";
int age = 15;
double average = 82.5;
boolean onTeam = true;
char house = 'B';
System.out.println(name + " is " + age);
System.out.println("Average: " + average);
System.out.println("On the team: " + onTeam);
System.out.println("House " + house);
}
}Leo is 15
Average: 82.5
On the team: true
House BLine-by-line explanation
- Lines 3 to 7One variable for each of the five common types.
- Lines 9 to 12Joining a String with any value turns that value into text.
Changing values and constants
public class Main {
public static void main(String[] args) {
final int MAX_LIVES = 3;
int lives = MAX_LIVES;
lives = lives - 1;
lives--;
System.out.println("Lives left: " + lives + " of " + MAX_LIVES);
String word = "java";
System.out.println(word.toUpperCase() + " has " + word.length() + " letters");
}
}Lives left: 1 of 3
JAVA has 4 lettersLine-by-line explanation
- Line 3final means MAX_LIVES can never be changed.
- Lines 6 to 7Two ways to subtract one.
lives--is a shortcut. - Line 11Strings have methods: toUpperCase() and length().
Casting and parsing
public class Main {
public static void main(String[] args) {
double price = 19.99;
int rounded = (int) price;
long nearest = Math.round(price);
String input = "42";
int number = Integer.parseInt(input);
System.out.println(rounded);
System.out.println(nearest);
System.out.println(number + 8);
}
}19
20
50Line-by-line explanation
- Line 4Casting to int cuts off the decimals; it doesn't round.
- Line 5Math.round() rounds to the nearest whole number.
- Line 8parseInt turns the text "42" into the number 42, so maths works.
Common Java Variables Mistakes
Putting the wrong type in a variable
int price = 9.99;double price = 9.99;The compiler reports "possible lossy conversion from double to int", because an int can't hold the .99.
Single quotes around text
String name = 'Leo';String name = "Leo";Single quotes are only for one char, like 'L'. Strings always use double quotes.
Using a variable before giving it a value
int total;
System.out.println(total);int total = 0;
System.out.println(total);Java refuses to compile code that reads a local variable that "might not have been initialized".
Java Variables in Real Projects
Types in real programs
A banking app stores account numbers as String (they're labels, not numbers you do maths with), balances as precise decimal types, and flags such as isLocked as boolean. Choosing the right type for each piece of data is one of the first decisions in any real Java project.
Java Variables FAQ
What is the difference between int and Integer in Java?
int is a primitive type that stores a whole number directly. Integer is a class that wraps an int in an object. Use int for ordinary variables and calculations, and Integer when an object is required, such as in a List<Integer>, or when a value may be missing and null is meaningful.
Do Java variables have default values?
Local variables declared inside a method don't: you must assign a value before reading them, or the code won't compile. Fields declared in a class do get defaults: 0 for numbers, false for boolean, and null for objects such as String.
Should I use var or write the type?
Both are correct. var is useful when the type is obvious from the right-hand side, such as var names = new ArrayList<String>();. Write the type when it adds information, for example double total = 0;, where var total = 0; would make an int. var only works for local variables that are given a value straight away.
What is the largest number an int can hold?
Integer.MAX_VALUE, which is 2,147,483,647. Going past it doesn't cause an error: the value wraps around to a large negative number. Use long for values that can grow beyond about two billion, such as file sizes in bytes or milliseconds since 1970.
Can I declare several variables on one line?
Yes, if they share a type: int x = 0, y = 0, z = 0;. Many style guides prefer one declaration per line, because it's easier to read and to comment each variable.
Java Variables Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the declarations.
score = 10;
player = "Mia";
Which type should store the value true?
What does this print?
double d = 7.8;
int i = (int) d;
System.out.println(i);
What does this print?
String a = "5";
int b = 5;
System.out.println(a + b);
What does this print?
int a = 7;
double b = a;
System.out.println(b);
Java Variables Quiz
5 questions to check what you learned.
Which keyword makes a variable impossible to change?
- static
- final
- const
- fixed
How is a single character written in Java?
- "A"
A- (A)
- 'A'
Why does
Stringstart with a capital letter?- It's a class, not a primitive type
- It's a constant
- All types start with a capital letter
- It's a mistake that Java allows
Which line correctly turns the text "25" into the number 25?
- int n = (int) "25";
- int n = Integer.parseInt("25");
- int n = "25".toInt();
- int n = String.parse("25");
Which keyword makes a variable's value unchangeable?
- final
- static
- const
- fixed