Java

Variables & Data Types

Data is king! Learn how to store information using variables and explore Java's primitive and reference data types.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Data is king! Learn how to store information using variables and explore Java's primitive and reference data types. This hands-on tutorial focuses on practical implementation of variables & data types concepts.

Variables & Data Types

Variables are containers for storing data values. In Java, because it is statically typed, you must define the type of the variable before using it.

Declaring Variables

Syntax: type variableName = value;

int myAge = 25;
String myName = "John";

Type Inference (Java 10+)

You can use the var keyword to let the compiler infer the type.

var city = "New York"; // Inferred as String
var population = 8000000; // Inferred as int

Constants

Use the final keyword to create variables that cannot be changed (constants).

final double PI = 3.14159;
// PI = 3.14; // Error: cannot assign a value to final variable

Data Types in Java

Java has two main categories of data types:

1. Primitive Data Types

There are 8 primitive types. They store simple values.

TypeSizeDescriptionExample
byte1 byteStores whole numbers from -128 to 127byte b = 100;
short2 bytesStores whole numbers from -32,768 to 32,767short s = 5000;
int4 bytesStores whole numbers (most common)int i = 100000;
long8 bytesStores large whole numberslong l = 15000000000L;
float4 bytesStores fractional numbersfloat f = 5.75f;
double8 bytesStores fractional numbers (more precise)double d = 19.99;
boolean1 bitStores true or falseboolean isFun = true;
char2 bytesStores a single character/letterchar grade = 'A';

[!NOTE] long literals end with L and float literals end with f.

2. Non-Primitive (Reference) Data Types

These refer to objects.

  • String (Sequence of characters)
  • Arrays
  • Classes
  • Interfaces

Type Casting

Converting a value from one data type to another.

  1. Widening Casting (Automatic): Smaller type to larger type. byte -> short -> char -> int -> long -> float -> double

    int myInt = 9;
    double myDouble = myInt; // Automatic casting: 9.0
    
  2. Narrowing Casting (Manual): Larger type to smaller type.

    double myDouble = 9.78d;
    int myInt = (int) myDouble; // Manual casting: 9
    

Interactive Example

Play with different data types!

JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Java primitive types, reference types and type casting"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 4

How many primitive data types are there in Java?

6
8
10
Unlimited

Next Steps

Now that we have variables, let's learn how to manipulate them using Operators.