Variables in Java - Fun & Easy Guide
1. What is a Variable?
A variable in Java is like a container (or labeled box) used to store data in memory.
This data can be numbers, words, characters, etc., and we can use, change, and print this data while our
program runs.
Think of your brain as a fridge and variables as labeled boxes inside it:
- int mangoes = 5; -> A box of 5 mangoes
- String juice = "Maaza"; -> A bottle labeled Maaza
- boolean isThirsty = true; -> A yes/no switch on the fridge door
These boxes = VARIABLES. And the stuff inside = VALUES.
2. Java Variable Syntax
Java Variable Syntax:
---------------------
dataType variableName = value;
Examples:
---------
int age = 21;
String name = "Rehman";
boolean isSmart = true;
double pi = 3.14;
3. Types of Variables
Types of Variables in Java:
Variables in Java - Fun & Easy Guide
---------------------------
- int : Whole numbers -> int apples = 5;
- double : Decimal numbers -> double temp = 98.6;
- char : Single characters -> char grade = 'A';
- String : Text -> String name = "Zara";
- boolean : true/false -> boolean isHappy = true;
4. Rules for Variable Naming
Variable Naming Rules (Java Police ):
--------------------------------------
1. Can't start with a number 2cool
2. No spaces my name myName
3. No special characters (except _ or $)
4. Be meaningful! studentMarks instead of x
5. Fun Java Code Example
Real Java Code Example:
-----------------------
public class FunWithVariables {
public static void main(String[] args) {
String hero = "Iron Man";
int age = 45;
boolean isAlive = false;
System.out.println(hero + " was " + age + " years old.");
System.out.println("Is he alive? " + isAlive);
}
Variables in Java - Fun & Easy Guide
6. WhatsApp Channel Quiz Questions
WhatsApp Channel Quiz Questions (Java Style & Fun)
--------------------------------------------------
Q1: What will be printed?
-------------------------
int x = 10;
x = x + 5;
System.out.println(x);
a) 10 b) 15 c) x d) Error
Answer: b) 15
Q2: Which one is a valid variable name?
---------------------------------------
a) 2cool b) my-name c) myName d) class
Answer: c) myName
Q3: Which data type is correct for this?
----------------------------------------
____ planet = "Earth";
a) int b) char c) String d) boolean
Answer: c) String
Funny Fill in the Blank:
------------------------
A variable is like a ______ that stores stuff in your brain!
Answers from friends: pocket, locker, pet, exs memory