Skip to lesson
MentorNxt home

Java Programming

Variables & Data Types

A data type tells Java what kind of value a variable holds: a whole number, a decimal number, one letter, true or false, or text.

What is a data type?

A college form holds a name, marks, attendance, a grade and "fees paid" (yes or no). You can add marks, but not names. A data type says what kind of value a variable holds.

Example · A student record

Student.javaJava
public class Student {    public static void main(String[] args) {        String name = "Priya";        int marks = 88;        double attendance = 92.5;        char grade = 'A';        boolean passed = true;        System.out.println(name + " got " + marks + " marks");        System.out.println("Attendance " + attendance + "%, grade " + grade);        System.out.println("Passed: " + passed);    }}
Output
Priya got 88 marks
Attendance 92.5%, grade A
Passed: true

What this code does

  • Each variable has a type that fits its value: String for text, int for a whole number, double for a decimal, char for one letter, boolean for true or false.
  • The type is fixed when the variable is made. int marks = "high"; does not compile, because "high" is text; Java catches this before the program runs.
  • + joins the text and the values into one line to print.

The 8 primitive types

Most values are simple: one number, one letter, or true or false. Java has 8 built-in primitive types for them, all written in small letters. A value typed straight into the code, like 85, 'A' or true, is a literal.

Four primitive types plus String are enough for most beginner programs: int, double, char, boolean and String.

String: text is a reference type

A name can be short or very long, so Java does not keep text in a fixed-size box. Text uses String, a class (a ready-made type that comes with Java), so it starts with a capital S.

A String variable holds a reference: a link to where the text is kept. Types like this are reference types. The String lesson (opens in a new tab) shows what you can do with text.

int marks = 85; makes a box that holds 85 itself. String name = "Priya"; makes a box that holds a reference: an arrow to the String object "Priya" kept elsewhere in memory.

Pick the right type

Before you create a variable, ask one question: what kind of value is it? A whole number, a decimal, yes/no, or text? Then pick the type that fits. Numbers bigger than about 2.1 billion need long, which Whole numbers (opens in a new tab) explains.

Classify

Pick the type

Tap a value, then tap the type that can hold it.

For beginner examples we use double to practise decimals. Money that must be exact needs more care: see Decimal numbers (opens in a new tab).

Next step

Check your understanding

8 quick questions