Variables and Data Types
Understanding Variables
Variables are containers for storing data values. In Java, every variable must be declared with a specific data type, which tells the computer what kind of data the variable will hold.
Common Data Types
int: Stores whole numbers, like 7 or -42.double: Stores decimal numbers, like 3.14 or -0.01.boolean: Storestrueorfalsevalues.char: Stores single characters, like 'A' or 'z'.String: Stores sequences of characters, like "Hello, Java!".
Declaring and Using Variables
To declare a variable, write the data type, then the variable name, and assign a value with =:
int age = 16;
double price = 9.99;
boolean isStudent = true;
char grade = 'A';
String name = "Alex";
Changing Values
You can change a variable's value at any time:
age = 17;
price = price - 2.00;
Why Variables Matter
Variables let programs remember information and perform calculations. They're the building blocks for everything in programming!
Real-World Analogy
Imagine variables as labeled jars in a kitchen. Each jar (variable) can hold a specific kind of ingredient (data type).
Common Mistakes
- Forgetting to declare the data type.
- Trying to store a string in an
intvariable.
Examples
Declaring an
intcalledscoreand setting it to 100.Using a
booleannamedisLoggedInto track user login status.
In a Nutshell
Variables store information; data types define what kind of information can be stored.