π What Youβll Learn
- What variables are
- How to declare and assign values
- Variable naming rules
- Constants with
final
- Intro to
var
(type inference)
π¦ What is a Variable?
A variable is a name that refers to a value stored in memory. It's like a labeled box that holds data your program needs.
int age = 25;
String name = "Alice";
βοΈ Declaring a Variable
Syntax:
type variableName = value;
Examples:
int number = 10;
String city = "Tokyo";
π Updating Variables
int score = 100;
score = 150; // updated value
You can declare first, assign later:
int level;
level = 5;
π« Constants with final
Use the final
keyword to make a variable read-only after itβs assigned.
final double PI = 3.14159;
// PI = 3.14; β Error β cannot reassign
β
Constants are usually written in UPPERCASE with underscores: MAX_SPEED
, DEFAULT_TIMEOUT
.
π€ Type Inference (Java 10+)
If you're using Java 10 or newer, you can use var
to let the compiler infer the type:
var name = "Java"; // String
var count = 5; // int
β οΈ Note: var
must be initialized on declaration.
β Naming Rules & Best Practices
- Must start with a letter,
_
, or$
- Can contain letters and numbers
- Cannot use spaces or start with a digit
- Avoid Java reserved words like
int
,class
,public
, etc.
β Good names:
userAge, totalScore, MAX_VALUE
β Avoid:
int, 2cool, user age
π Recap
- Variables store values that your program uses and updates
- Declare them with a type, or use
var
in modern Java - Use
final
for constants - Follow naming rules and use descriptive names