Java tutorialLesson 3 of 18 · tap to see all lessons
Java tutorial · Beginner
Java Variables, Constants, and Data Types
Declare and initialize Java variables, pick the right primitive or reference type, use final constants, understand scope, and convert between types with casting.
- Qyubie Learn Editorial Team
- Published
- 8 min read
Includes 3 quick checks you can do right here.
Almost every program stores information: a name, a score, whether a student is enrolled. In Java you keep each piece in a variable, and every variable has a type that decides what it can hold. This lesson covers how to create variables, which types to choose, how to make values that never change, and how to convert one type to another.
By the end of this lesson you will be able to:
- declare and initialize variables,
- choose between Java's primitive types and reference types,
- explain where a variable can be used (its scope),
- create constants with
final, and - convert between types, including casting.
Declaring and initializing
A variable has a type, a name, and (usually) a value:
int units; // declaration: create a box for an int
units = 3; // assignment: put 3 in it
int hours = 5; // declaration + initialization in one line
units = units + 1; // replace the value: now 4
System.out.println(units + " units, " + hours + " hours");Output:
4 units, 5 hoursJava won't let you use a local variable before it has a value. int x; System.out.println(x); is a compile error: variable x might not have been initialized.
You can declare several variables of the same type on one line, int a = 1, b = 2, c = 3;, but one per line is easier to read.
Primitive types
Java has eight primitive types. They hold simple values directly.
| Type | Size | Holds | Example |
|---|---|---|---|
byte | 8 bits | whole numbers −128 to 127 | byte level = 5; |
short | 16 bits | whole numbers −32,768 to 32,767 | short year = 2026; |
int | 32 bits | whole numbers, about ±2.1 billion | int population = 1394329; |
long | 64 bits | very large whole numbers (add L) | long views = 9000000000L; |
float | 32 bits | decimals, about 7 digits of precision (add f) | float rate = 0.05f; |
double | 64 bits | decimals, about 15 digits of precision | double gwa = 1.75; |
char | 16 bits | one character, in single quotes | char section = 'A'; |
boolean | — | true or false | boolean enrolled = true; |
In everyday code you'll mostly use int for whole numbers, double for decimals, char, and boolean.
Quick check
Reference types
Everything that isn't primitive is a reference type: String, arrays, and objects of any class (including classes you'll write). The variable holds a reference, a way to find the object, rather than the value itself.
String course = "BSCS";
int[] scores = {85, 92, 78};
System.out.println(course.length());
System.out.println(scores.length);Output:
4
3Reference types have methods you call with a dot, like course.length(). A reference variable can also be null, meaning it doesn't point to any object yet.
| Primitive | Reference |
|---|---|
| Holds the value itself | Holds a reference to an object |
Lowercase name: int, double | Usually a class name: String, Scanner |
Can't be null | Can be null |
| No methods | Has methods: name.length() |
Scope: where a variable lives
A variable exists only inside the block ({ }) where it is declared, from the declaration to the closing brace. This is its scope.
int total = 0;
for (int i = 1; i <= 3; i++) {
int doubled = i * 2; // exists only inside the loop body
total = total + doubled;
}
System.out.println(total);
// System.out.println(doubled); // error: cannot find symbolOutput:
12total was declared outside the loop, so it's still available after it. doubled and i are gone once the loop ends.
Constants with final
Mark a variable final when its value must never change. By convention, constant names use UPPER_SNAKE_CASE.
final double PASSING_GRADE = 3.0;
final int MAX_UNITS = 26;
System.out.println("Max load: " + MAX_UNITS + " units");
// MAX_UNITS = 30; // error: cannot assign a value to final variable MAX_UNITSOutput:
Max load: 26 unitsConstants make code easier to read (MAX_UNITS instead of a mystery 26) and easier to change, because you update one line.
Type conversion
Widening (automatic). Java converts a smaller type to a larger one by itself, because no information is lost:
byte → short → int → long → float → double
int whole = 7;
double asDecimal = whole; // int to double: automatic
long big = whole; // int to long: automatic
System.out.println(asDecimal);
System.out.println(big);Output:
7.0
7Narrowing (casting). Going from a larger type to a smaller one might lose information, so Java makes you ask for it with a cast: the target type in parentheses.
double price = 99.99;
int pesos = (int) price; // drops the decimal part, doesn't round
System.out.println(pesos);
int total = 17;
int count = 5;
System.out.println(total / count); // int / int
System.out.println((double) total / count); // cast first, then divideOutput:
99
3
3.4Casting a double to int truncates: it cuts off the decimals, so 99.99 becomes 99, not 100. To round, use Math.round(price).
Quick check
char and int. A char is stored as a number (its Unicode code), so the two convert:
char letter = 'A';
int code = letter; // widening: 'A' is 65
char next = (char) (code + 1);
System.out.println(code);
System.out.println(next);Output:
65
BConverting text to numbers and back
Input from users and files often arrives as text. Use these to convert:
String ageText = "19";
int age = Integer.parseInt(ageText);
double gwa = Double.parseDouble("1.75");
String again = String.valueOf(age + 1);
System.out.println(age + 1);
System.out.println(gwa * 2);
System.out.println(again + "!");Output:
20
3.5
20!If the text isn't a valid number, as in Integer.parseInt("nineteen"), Java throws a NumberFormatException at run time.
Quick check
Common mistakes
- Using a local variable before giving it a value: might not have been initialized.
- Putting the wrong kind of value in a variable:
int age = "19";won't compile. UseInteger.parseInt. - Forgetting
Lon biglongliterals:long n = 9000000000;is an error because the number is too big for anintliteral. - Expecting a cast to round:
(int) 2.9is2. charvsStringquotes:'A'is achar, and"A"is aString.
Summary
- A variable has a type, a name, and a value; declare it before use and give it a value first.
- Primitive types (
int,double,char,boolean, and four more) hold values directly. Reference types (String, arrays, objects) hold references and have methods. - A variable exists only inside the block where it's declared.
finalmakes a constant; name it in UPPER_SNAKE_CASE.- Widening is automatic. Narrowing needs a cast, and casting a decimal to
inttruncates. Integer.parseInt,Double.parseDouble, andString.valueOfconvert between text and numbers.
Next lesson: input and output: printing neatly with printf and reading what the user types with Scanner.