Ch 3 · Variables — Your Data Containers · Java

Topic 3 of 13 in Java — Complete Tutorial (Beginner) — 4 lessons.

What is a Variable?

Imagine you are playing a video game and your character earns points. The game needs to remember your score at all times — it needs somewhere to store that number. In programming, we use a variable for exactly this. A variable is a named storage location in the computer's memory that holds a piece of data.

Declaring, Assigning, and final

When you create a variable you "declare" it (state its type and name) and usually "assign" it a value at the same time. Later you can change the value of a normal variable as often as you like by assigning again — but the type can never change. If you want a value that must never change, put the keyword final in front: Java will then refuse to let anyone reassign it, which protects important fixed values.

Naming Conventions

A good variable name tells the reader exactly what it holds — numberOfStudents, not x. Java uses camelCase for variables and methods: the first word is lowercase and every following word starts with a capital letter, with no spaces, like firstName, totalScore, isLoggedIn. Class names use PascalCase (every word capitalised, like StudentRecord), and constants use UPPER_SNAKE_CASE. Following these conventions makes your code look professional and instantly readable to other Java programmers.

Variables in Action: A Full Example

Let us bring everything together in a real mini-program. Notice how each variable has a clear type and a clear name, so the code almost reads like plain English. This is a full program, including the class and main, so you can run it as-is.

All topics in Java Beginner

  1. Introduction to Programming & Java
  2. Your First Java Program
  3. Variables — Your Data Containers
  4. Data Types — Kinds of Values
  5. Operators & Expressions
  6. Conditional Statements
  7. Loops & Iterations
  8. Methods
  9. Arrays & Lists
  10. Objects & Classes
  11. Strings — Working with Text
  12. Exception Handling
  13. Mini-Projects & Practice