Skip to content
Qyubie Learn
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 hours

Java 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.

TypeSizeHoldsExample
byte8 bitswhole numbers −128 to 127byte level = 5;
short16 bitswhole numbers −32,768 to 32,767short year = 2026;
int32 bitswhole numbers, about ±2.1 billionint population = 1394329;
long64 bitsvery large whole numbers (add L)long views = 9000000000L;
float32 bitsdecimals, about 7 digits of precision (add f)float rate = 0.05f;
double64 bitsdecimals, about 15 digits of precisiondouble gwa = 1.75;
char16 bitsone character, in single quoteschar section = 'A';
boolean—true or falseboolean enrolled = true;

In everyday code you'll mostly use int for whole numbers, double for decimals, char, and boolean.

Quick check

Which type is the best fit for storing a student's general weighted average, like 1.75?

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
3

Reference 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.

PrimitiveReference
Holds the value itselfHolds a reference to an object
Lowercase name: int, doubleUsually a class name: String, Scanner
Can't be nullCan be null
No methodsHas 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 symbol

Output:

12

total 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_UNITS

Output:

Max load: 26 units

Constants 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
7

Narrowing (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 divide

Output:

99
3
3.4

Casting 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

What does this print?
double temp = 36.9;
int t = (int) temp;
System.out.println(t);

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
B

Converting 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

What does this print?
int a = 5;
double b = 2;
System.out.println(a / b);

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. Use Integer.parseInt.
  • Forgetting L on big long literals: long n = 9000000000; is an error because the number is too big for an int literal.
  • Expecting a cast to round: (int) 2.9 is 2.
  • char vs String quotes: 'A' is a char, and "A" is a String.

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.
  • final makes a constant; name it in UPPER_SNAKE_CASE.
  • Widening is automatic. Narrowing needs a cast, and casting a decimal to int truncates.
  • Integer.parseInt, Double.parseDouble, and String.valueOf convert between text and numbers.

Next lesson: input and output: printing neatly with printf and reading what the user types with Scanner.

References and further reading