Java Variables
π§ Definitionβ
A variable in Java is a container that holds data during the execution of a program. Each variable has a data type, which defines the kind of data it can store (e.g., integer, string).
Variables are the named memory locations used to store values for processing.
βοΈ Syntaxβ
dataType variableName = value;
Example:β
int age = 25;
String name = "Alice";
boolean isJavaFun = true;
π Real-World Analogyβ
Think of a variable like a labeled jar β if you put "sugar" in a jar labeled "SweetStuff", you can refer to it easily later.
| Label (variableName) | Contents (value) | Type of Contents (dataType) |
|----------------------|------------------|------------------------------|
| age | 25 | int |
| name | "Alice" | String |
| isJavaFun | true | boolean |
π§ Explain Like I'm Fiveβ
"Imagine you have a toy box labeled βLegoβ. If you want to play, you look at the box name to know what's inside. Java does something similar with variables!"
π― Types of Variables in Javaβ
| Type | Scope | Default Value |
|---|---|---|
| Local | Declared inside a method | No default |
| Instance | Belongs to an object | Depends |
| Static | Belongs to a class (not instances) | Depends |
π Example with Different Variablesβ
public class VariableDemo {
int instanceVar = 10; // Instance variable
static int staticVar = 20; // Static variable
void method() {
int localVar = 5; // Local variable
System.out.println(localVar);
}
public static void main(String[] args) {
VariableDemo obj = new VariableDemo();
obj.method();
System.out.println(obj.instanceVar);
System.out.println(staticVar);
}
}
β Exerciseβ
- Declare three variables:
int score,String playerName,boolean isAlive. Assign them values and print them. - Create a class with one static and one instance variable. Access both in
main().
π Fun Factβ
Did you know? Java is a statically typed language, which means you have to declare the type of a variable before using it. Unlike Python, where you can just do x = 5, in Java you must write int x = 5;.
π Quick Recapβ
- Variables store data
- Must be declared with a type
- Can be local, instance, or static
- Are essential building blocks in any Java program