Skip to main content

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​

TypeScopeDefault Value
LocalDeclared inside a methodNo default
InstanceBelongs to an objectDepends
StaticBelongs 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​

  1. Declare three variables: int score, String playerName, boolean isAlive. Assign them values and print them.
  2. 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