Concept Explanation
In Python, variables are like flexible bags you can throw anything into. In Java, variables are like Storage Crates with a specific label on the front (e.g., "Integers Only").
This is called Strong Typing. It might feel strict at first, but it prevents thousands of bugs because Java checks your data before the program even runs.
Syntax or Core Structure
Type variableName = value;
int score = 100; // Whole number
double price = 19.99; // Decimal
char grade = 'A'; // Single character (Single quotes!)
String message = "Hello"; // Text (Double quotes!)
boolean isWin = true; // Logic
The 'final' Keyword
If you want a variable to be a Constant (unchangeable), use final.
final double PI = 3.14159;
// PI = 3.0; // ❌ ERROR: Cannot change a final variable
Real World Example
A Bank Account:
long accountNumber: A large integer for the ID.double balance: Decimals for the money.String ownerName: Text for the name.boolean isFrozen: A simple flag to check account status.
Best Practices
- Descriptive Names: Don't use
int a = 5;. Useint userAge = 5;. - camelCase: Start with lowercase, and capitalize every word after (e.g.,
maxSpeedLimit). - Initialize before use: Java will complain if you try to use a variable that hasn't been given a value yet.
Practice Exercises
- The Profile Creator: Create variables for a movie (Title, Year, Rating, IsClassic) and print them in a formatted sentence.
- The Value Swapper: Create two integer variables
xandy. Use a third variabletempto swap their values. - The Final Challenge: Try to create a
finalvariable for your "Birth Year" and then write code to change it. Observe the error.