Nearby lessons

11 of 125

Java - Variables and Data Types

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

Variables and Data Types is a core concept of the Java language. This lesson explains Data Types with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Data Types

A data type tells the computer what kind of value a variable can hold and how much memory it needs. Java data types are of two big categories:

  • Primitive types — 8 basic types built into the language (int, float, boolean, etc.).
  • Reference (non-primitive) types — types made from classes and interfaces (String, arrays, user-defined classes).

The 8 primitive types with their sizes and ranges:

Data typeSizeRange (simple words)
byte1 byte-128 to 127
short2 bytes-32,768 to 32,767
int4 bytes-2,147,483,648 to 2,147,483,647 (approx -214 crores to +214 crores)
long8 bytesvery big range (approx -922 lakh crore to +922 lakh crore)
float4 bytesup to 7 decimal digits (approx)
double8 bytesup to 15 decimal digits (approx) — default for decimals
char2 bytes0 to 65,535 (holds one UNICODE character)
boolean1 bit (size depends)true or false only
Example01
JCode Cell
1class DataTypeDemo {
2 public static void main(String[] args) {
3 byte b = 100; // OK
4 int age = 25;
5 long phone = 9876543210L; // L is needed for big numbers
6 float price = 99.99f; // f is needed
7 double pi = 3.141592653589;
8 char grade = 'A';
9 boolean passed = true;
10 System.out.println(age + " " + passed + " " + grade);
11 }
12}
Output
25 true A
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1