πŸ“ 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