Lesson 17 min read
Variables & Data Types
Give your data a name and a home
What Is a Variable?
Think of a variable like a labeled jar on a shelf. The label is the variable's name, and the stuff inside is the value. In Java, you also have to say what kind of stuff goes in the jar — numbers? letters? true/false? That's the data type.
Java is a statically typed language, which means you pick the jar size before you put anything in it. Once you say "this jar holds integers," you can't suddenly shove a sentence in there.
Declaring & Initializing Variables
The Primitive Types — Java's Building Blocks
Java has 8 primitive types. Think of them as different-sized containers:
byte— tiny box (-128 to 127). Good for saving memory when you know values are small.short— small box (-32,768 to 32,767).int— the everyday box (-2 billion to 2 billion). This is your go-to for whole numbers.long— the giant box (up to about 9 quintillion). Add anLat the end:long big = 9999999999L;float— decimal number, less precise. Add anf:float pi = 3.14f;double— decimal number, more precise. This is your default for decimals.char— a single character in single quotes:'A'boolean— onlytrueorfalse. Like a light switch.
String is NOT a primitive — it's a class (notice the capital S) that internally uses a character array. But you'll use it constantly, so Java gives it special treatment.
Type Casting — Converting Between Types
The final Keyword — Constants
Note: Think of
final like writing with a permanent marker instead of a pencil. Once you write the value, it's stuck forever. Use it for things that should never change — like the speed of light or your tax rate.