Data types in Java
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}Priya got 88 marks Attendance 92.5%, grade A Passed: true
What this code does
- Each variable has a type that fits its value:
Stringfor text,intfor a whole number,doublefor a decimal,charfor one letter,booleanfor 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.
- Whole numbers:
byte,short,int,long(see Whole numbers (opens in a new tab)) - Decimal numbers:
float,double(see Decimal numbers (opens in a new tab)) - One character:
char, such as'A'(see char and boolean (opens in a new tab)) - True or false:
boolean
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.
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.
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