Variables & Data Types

Java · Lesson 5 of 32 8 min read Updated

Programs work with data: a student's name, a train fare, a cricket score, whether a seat is booked. A variable is a named box in memory that holds one piece of data. In Java, every variable has a type that decides what kind of value it can hold and how much memory it uses.

In this lesson you will declare variables, learn Java's eight primitive types, use var to let the compiler work out a type, create constants with final, and convert values from one type to another.

Declaring and using variables

To create a variable, write its type, its name, and usually a starting value. Giving a variable its first value is called initialising it.

Java
public class Student {
    public static void main(String[] args) {
        String name = "Ananya";
        int age = 19;
        double cgpa = 8.75;
        char section = 'B';
        boolean hostelResident = true;

        System.out.println(name + " is " + age + " years old.");
        System.out.println("CGPA: " + cgpa + ", Section: " + section);
        System.out.println("Lives in hostel? " + hostelResident);

        age = 20;               // a birthday: change the value
        System.out.println("Next year: " + age);
    }
}
Output
Ananya is 19 years old.
CGPA: 8.75, Section: B
Lives in hostel? true
Next year: 20

The = sign means assign: put the value on the right into the variable on the left. When you change age, you do not repeat the type, because the variable already exists. Text in double quotes is a String; a single character in single quotes is a char.

The eight primitive types

Java has eight primitive types. A primitive variable stores the value itself, directly in the box. Four are for whole numbers, two for decimals, one for characters and one for true or false.

TypeSizeHoldsExample
byte8 bitswhole numbers from -128 to 127byte floor = 12;
short16 bits-32,768 to 32,767short year = 2026;
int32 bitsabout -2.1 billion to 2.1 billionint marks = 437;
long64 bitsvery large whole numberslong views = 9_000_000_000L;
float32 bitsdecimals, about 7 digits of precisionfloat discount = 12.5f;
double64 bitsdecimals, about 15 digits of precisiondouble gst = 0.18;
char16 bitsone Unicode characterchar grade = 'A';
booleannot fixedtrue or falseboolean paid = false;

In everyday code you mostly use int for whole numbers, double for decimals, boolean for yes/no values and long when numbers may pass two billion (such as file sizes or phone numbers stored as numbers).

Java
public class Types {
    public static void main(String[] args) {
        byte floor = 12;
        short pinPart = 1240;
        int monthlyVisitors = 1_42_00_000;      // underscores make big numbers readable
        long indiaPopulation = 1_45_00_00_000L; // note the L
        float discount = 12.5f;                 // note the f
        double gstRate = 0.18;

        System.out.println(floor + " " + pinPart);
        System.out.println(monthlyVisitors);
        System.out.println(indiaPopulation);
        System.out.println(discount + " " + gstRate);
        System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
        System.out.println("long max: " + Long.MAX_VALUE);
    }
}
Output
12 1240
14200000
1450000000
12.5 0.18
int range: -2147483648 to 2147483647
long max: 9223372036854775807

Underscores between digits are ignored by the compiler, so you can group digits the Indian way (1_42_00_000 for 1.42 crore) or the international way. A whole-number literal larger than the int range needs an L at the end, and a decimal literal stored in a float needs an f, because Java treats plain decimals as double.

Reference types and String

Everything that is not one of the eight primitives is a reference type: String, arrays, and every class you will write. A reference variable does not hold the object itself; it holds a reference (an address) that points to an object stored elsewhere in memory. A reference variable can also hold null, which means "points to nothing".

String is the reference type you will use most. Type names of reference types start with a capital letter (String, Scanner), while primitive type names are all lowercase (int, double). You will study strings in depth in Strings & Text Blocks and references in Classes, Objects & static.

Let the compiler infer the type with var

Since Java 10 you can write var instead of the type for a local variable (a variable inside a method). The compiler looks at the value on the right and works out the type for you. This is called type inference.

Java
import java.util.ArrayList;

public class VarDemo {
    public static void main(String[] args) {
        var city = "Pune";          // String
        var pincode = 411001;       // int
        var fare = 245.50;          // double
        var stations = new ArrayList<String>();
        stations.add("Shivajinagar");
        stations.add("Swargate");

        System.out.println(city + " " + pincode + " " + fare);
        System.out.println(stations);
    }
}
Output
Pune 411001 245.5
[Shivajinagar, Swargate]

var does not make Java dynamically typed. city is still a String forever; assigning a number to it later is a compile error. var only saves typing, and it shines when the type name is long. Use it when the type is obvious from the right-hand side, and write the type out when it helps the reader. You cannot use var without an initial value, and you cannot use it for fields or method parameters.

Constants with final

Add final to a variable and it can be assigned only once. Use it for values that must never change. By convention, constants that belong to a class are written as static final with UPPER\_SNAKE\_CASE names:

Java
static final double GST_RATE = 0.18;
static final int MAX_SEATS_PER_BOOKING = 6;

Trying to change a final variable gives error: cannot assign a value to final variable.

Type casting and conversion

Sometimes you need a value of one type as another type. Java converts automatically when nothing can be lost, such as int to long or int to double. This is a widening conversion. Going the other way, from double to int, could lose information, so you must ask for it with a cast: the target type in brackets. This is a narrowing conversion.

To turn text into numbers, use Integer.parseInt and Double.parseDouble; to turn anything into text, use String.valueOf.

Java
public class Cast {
    public static void main(String[] args) {
        int marks = 437;
        double asDouble = marks;            // widening: automatic
        System.out.println(asDouble);

        double price = 1299.99;
        int rupees = (int) price;           // narrowing: you must cast
        System.out.println(rupees);

        int big = 200;
        byte small = (byte) big;            // does not fit in a byte!
        System.out.println(small);

        char grade = 'A';
        int code = grade;                   // a char is a number underneath
        System.out.println(code);
        System.out.println((char) (code + 1));

        int pin = Integer.parseInt("124001");
        double weight = Double.parseDouble("62.5");
        String text = String.valueOf(pin);
        System.out.println(pin + 1);
        System.out.println(weight * 2);
        System.out.println(text + 1);
    }
}
Output
437.0
1299
-56
65
B
124002
125.0
1240011

Three lessons hide in this output. First, casting 1299.99 to int cuts off the decimals; it does not round. Second, 200 does not fit in a byte, so the cast silently wraps around to -56. A cast tells the compiler "trust me", so make sure the value really fits. Third, text + 1 joins strings, giving 1240011, while pin + 1 adds numbers.

Common mistakes

  • Using a variable before giving it a value. int total; System.out.println(total); fails with error: variable total might not have been initialized.
  • Forgetting L on a big number. long distance = 3000000000; fails with error: integer number too large. Write 3000000000L.
  • Forgetting f on a float. float pi = 3.14; fails with error: incompatible types: possible lossy conversion from double to float. Write 3.14f, or simply use double.
  • Expecting a cast to round. (int) 9.99 is 9. Use Math.round when you want rounding (see Operators & Math).
  • Parsing text that is not a number. Integer.parseInt("12a") stops the program with NumberFormatException. You will learn to handle this in Exceptions.

Key points

  • A variable has a type, a name and a value: int age = 19;.
  • Java has eight primitive types; use int, double, boolean and char most often, and long for very big whole numbers.
  • String, arrays and objects are reference types; their variables hold references and can be null.
  • var (Java 10+) infers a local variable's type from its value, but the type is still fixed.
  • final makes a variable a constant; class constants are static final with UPPER\_SNAKE\_CASE names.
  • Widening conversions are automatic; narrowing needs a cast and may lose data.

Exercise

Write a program Recharge.java for a mobile recharge. Store the customer name (Farhan), the plan price 299.0, the validity in days 28, and whether the plan includes OTT apps (true). Use var for at least two variables. Print all the details, then calculate and print the price per day as a double, and also the price per day cut down to whole rupees using a cast.

Show solution
Java
public class Recharge {
    public static void main(String[] args) {
        var customer = "Farhan";
        double price = 299.0;
        var validityDays = 28;
        boolean includesOtt = true;

        System.out.println("Customer: " + customer);
        System.out.println("Plan: Rs " + price + " for " + validityDays + " days");
        System.out.println("OTT apps included: " + includesOtt);

        double perDay = price / validityDays;
        int perDayWhole = (int) perDay;
        System.out.println("Per day: Rs " + perDay);
        System.out.println("Per day (whole rupees): Rs " + perDayWhole);
    }
}
Output
Customer: Farhan
Plan: Rs 299.0 for 28 days
OTT apps included: true
Per day: Rs 10.678571428571429
Per day (whole rupees): Rs 10

Because price is a double, the division gives a decimal result. The cast (int) perDay drops the decimal part. You will learn to print a tidy 10.68 with String.format in the strings lesson.

Quick Quiz

1. Which type should store whether a ticket is confirmed?

2. What does (int) 7.9 give?

3. Which line does NOT compile?

4. String s = "10"; int n = 10; What does s + n give?

Learn Java with a mentor

Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call