Skip to content

Beginner · Getting started with Java · topic 3 of 60 · 25 min

Variables and primitive types

Explanation

A variable has a type, a name and a value, and its type never changes. Java has eight primitive types: byte, short, int, long (whole numbers), float, double (decimals), char (one character) and boolean. Everything else, such as String, is a reference type. Use final for constants and var to let the compiler infer a local variable's type.

Why types?

Java is statically typed: every variable has a type that is fixed when you write the code and checked by the compiler. int count = "five"; does not compile. This catches many mistakes before the program ever runs, and it lets the JVM store values efficiently.

java
int quantity = 3;              // declare and assign
double price = 249.50;
String item = "Steel bottle";  // String is a class (reference type), note the capital S
boolean inStock = true;
char grade = 'A';              // single quotes for one character
System.out.println(item + " x" + quantity + " = " + (price * quantity));
Prints Steel bottle x3 = 748.5

The eight primitive types

TypeSizeRange / meaningExample
byte1 byte-128 to 127byte level = 5;
short2 bytes-32,768 to 32,767short year = 2026;
int4 bytesabout ±2.1 billion (-2,147,483,648 to 2,147,483,647)int marks = 92;
long8 bytesabout ±9.2 × 10^18long population = 1_420_000_000L;
float4 bytes~7 decimal digits of precisionfloat rate = 7.5f;
double8 bytes~15–16 decimal digits of precisiondouble pi = 3.14159;
char2 bytesone UTF-16 characterchar c = 'क';
boolean(JVM-dependent)true or falseboolean paid = false;

Use int for most whole numbers and double for most decimals. Use long when values can exceed about 2.1 billion (milliseconds, phone numbers stored as numbers, large money totals in paise). Underscores make big literals readable: 1_00_000 is one lakh.

Literals

  • 100 is an int; 100L is a long (use capital L; small l looks like 1).
  • 3.5 is a double; 3.5f is a float.
  • 'A' is a char; "A" is a String.
  • 0x1F is hexadecimal (31); 0b1010 is binary (10).

Primitive versus reference types

A primitive variable holds the value itself. A reference variable (String, arrays, every object) holds a reference to an object stored elsewhere in memory (the heap). A reference can be null, meaning it points to nothing; a primitive can never be null.

final and var

java
final double GST_RATE = 18.0;   // a constant: cannot be reassigned
// GST_RATE = 5;                 // compile error

var city = "Chennai";           // Java 10+: the compiler infers String
var count = 10;                 // inferred int
// var x;                        // compile error: var needs a value to infer from

var only works for local variables with an initial value. The type is still fixed: city = 5; would not compile. Use var when the type is obvious from the right-hand side, and write the type when it helps the reader.

Naming conventions

  • Variables and methods: camelCase (totalAmount, isPaid).
  • Classes: PascalCase (BankAccount).
  • Constants: UPPER_SNAKE_CASE (MAX_RETRIES).
  • Names are case-sensitive and cannot start with a digit or be keywords (class, int, new…).
Careful: A local variable must be given a value before it is read: int total; System.out.println(total); is a compile error ("variable total might not have been initialized"). Fields of a class get default values (0, false, null) but local variables do not.
Think of it like this: Types are like labelled containers in a kitchen: a milk can, a rice bin, a spice jar. You cannot pour rice into the milk can by mistake, because the label (type) is checked before anything is poured.
Tip: Do not use double for exact money calculations in real systems; use long paise or the BigDecimal class (used by banks). For learning, double is fine.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Variables and primitive types · 1/6

Variables and types

In this lesson you will store values in typed variables.

Prefer a video by a teacher? Find free videos on “java variables primitive data types int double char boolean tutorial” on YouTube ↗

In real life: A mobile recharge record

A recharge app stores each transaction with the right types: the phone number as a String (it is an identifier, and may start with +91), the amount in paise as a long, the validity in days as an int, and whether it succeeded as a boolean.

java
public class Recharge {
    public static void main(String[] args) {
        String phone = "+919876543210";
        long amountPaise = 29_900L;     // Rs 299.00
        int validityDays = 28;
        boolean success = true;
        System.out.println(phone + " | Rs " + amountPaise / 100 + " | " + validityDays + " days | " + success);
    }
}
Prints +919876543210 | Rs 299 | 28 days | true

Practice (0/3 done)

Task 1 · Question

Which declaration does NOT compile?

Task 2 · Question

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

Task 3 · Practice

Write StudentCard.java that stores a student's name (String), roll number (int), percentage (double), section (char) and whether fees are paid (boolean), and prints them on one line. Make the school name a final constant.

Quick quiz

Question 1

1.How many primitive types does Java have?

Question 2

2.Which type should hold true or false?

Question 3

3.What is the difference between 'A' and "A"?

Question 4

4.var x; on its own line gives…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How many primitive types does Java have?

Answer: 8

byte, short, int, long, float, double, char, boolean.

Which type should hold true or false?

Answer: boolean

boolean holds exactly true or false.

What is the difference between 'A' and "A"?

Answer: 'A' is a char; "A" is a String

Single quotes for char, double quotes for String.

var x; on its own line gives…

Answer: A compile error: cannot infer type

var needs an initial value to infer the type.

Which type holds true or false?Related

Answer: bool

bool has exactly two values: true and false.

From Types and variables

Which of these is NOT a primitive type?Related

Answer: array

Arrays are objects. The primitives are string, number, bigint, boolean, undefined, null and symbol.

From Values and types

Which type forces you to check a value before using it?Related

Answer: unknown

unknown accepts anything but blocks use until narrowed.

From Basic types and inference

What is in an int variable declared inside main with int n; and no value?Related

Answer: Garbage: reading it is undefined behaviour

Local variables are not set to zero automatically. Always initialise them.

From Variables, types and constants

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Getting started with Java” before its exam: Operators and expressions, Type conversion and reading input.
  2. Module 1 exam: Getting started with Java · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Control flow and methods. 60 topics left in the course before the final exam.

← Previous: Installing the JDK and your first program