Variables & Data Types
Data is king! Learn how to store information using variables and explore Java's primitive and reference data types.
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.
| Type | Size | Description | Example |
|---|---|---|---|
byte | 1 byte | Stores whole numbers from -128 to 127 | byte b = 100; |
short | 2 bytes | Stores whole numbers from -32,768 to 32,767 | short s = 5000; |
int | 4 bytes | Stores whole numbers (most common) | int i = 100000; |
long | 8 bytes | Stores large whole numbers | long l = 15000000000L; |
float | 4 bytes | Stores fractional numbers | float f = 5.75f; |
double | 8 bytes | Stores fractional numbers (more precise) | double d = 19.99; |
boolean | 1 bit | Stores true or false | boolean isFun = true; |
char | 2 bytes | Stores a single character/letter | char grade = 'A'; |
[!NOTE]
longliterals end withLandfloatliterals end withf.
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.
-
Widening Casting (Automatic): Smaller type to larger type.
byte->short->char->int->long->float->doubleint myInt = 9; double myDouble = myInt; // Automatic casting: 9.0 -
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!
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 4How many primitive data types are there in Java?
Next Steps
Now that we have variables, let's learn how to manipulate them using Operators.