Java Variables and Data Types

Declare variables with types such as int, double, boolean, char and String, and convert between them.

Lesson 5 of 127Beginner18 min read

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:

Java
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

TypeHoldsExample
intwhole numbersint lives = 3;
doubledecimal numbersdouble price = 9.99;
booleantrue or falseboolean isOpen = true;
charone character, in single quoteschar grade = 'A';
Stringtext, in double quotesString 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:

TypeSizeRange or use
byte8 bits-128 to 127, raw file and network data
short16 bits-32,768 to 32,767, rarely used
int32 bitsabout ±2.1 billion
long64 bitsabout ±9.2 quintillion, for IDs, timestamps and file sizes
float32 bitsdecimals with about 7 significant digits
double64 bitsdecimals 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:

Java
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: total and Total are different.
  • Java uses camelCase: start lowercase and capitalise each new word, as in totalPrice or isLoggedIn.

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:

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

Java
double exact = 9.7;
int whole = (int) exact;   // 9, the decimal part is cut off

To 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, char and String.
  • Text uses double quotes; a single char uses single quotes.
  • final makes a constant. Java names use camelCase; constants use UPPER_CASE.
  • Cast with (int) value; parse text with Integer.parseInt() or Double.parseDouble().

Java Variables Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A student record

Java
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);
    }
}
Output
Leo is 15
Average: 82.5
On the team: true
House B
Line-by-line explanation
  1. Lines 3 to 7One variable for each of the five common types.
  2. Lines 9 to 12Joining a String with any value turns that value into text.
Example 2

Changing values and constants

Java
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");
    }
}
Output
Lives left: 1 of 3
JAVA has 4 letters
Line-by-line explanation
  1. Line 3final means MAX_LIVES can never be changed.
  2. Lines 6 to 7Two ways to subtract one. lives-- is a shortcut.
  3. Line 11Strings have methods: toUpperCase() and length().
Example 3

Casting and parsing

Java
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);
    }
}
Output
19
20
50
Line-by-line explanation
  1. Line 4Casting to int cuts off the decimals; it doesn't round.
  2. Line 5Math.round() rounds to the nearest whole number.
  3. Line 8parseInt turns the text "42" into the number 42, so maths works.

Common Java Variables Mistakes

Putting the wrong type in a variable

Don't
int price = 9.99;
Do
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

Don't
String name = 'Leo';
Do
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

Don't
int total;
System.out.println(total);
Do
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.

Fill in the blankseasy

Complete the declarations.

 score = 10;
 player = "Mia";
Multiple choiceeasy

Which type should store the value true?

Predict the outputmedium

What does this print?

double d = 7.8;
int i = (int) d;
System.out.println(i);
Predict the outputmedium

What does this print?

String a = "5";
int b = 5;
System.out.println(a + b);
Predict the outputmedium

What does this print?

int a = 7;
double b = a;
System.out.println(b);

Java Variables Quiz

5 questions to check what you learned.

  1. Which keyword makes a variable impossible to change?

    • static
    • final
    • const
    • fixed
  2. How is a single character written in Java?

    • "A"
    • A
    • (A)
    • 'A'
  3. Why does String start 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
  4. 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");
  5. Which keyword makes a variable's value unchangeable?

    • final
    • static
    • const
    • fixed