Back to Study Material Java

Java Variables

A variable is a named storage location in memory that holds a value. In Java, every variable must be declared with a specific data type before it can be us...

Java Variables

Declaring, Initializing, and Using Variables

A variable is a named storage location in memory that holds a value. In Java, every variable must be declared with a specific data type before it can be used. This requirement is part of Java's statically typed design and allows the compiler to catch type errors before the program runs. Understanding how variables work — including their scope, lifetime, and default values — is fundamental to writing correct Java programs.

Declaring a variable means specifying its type and giving it a name: int score;. Initializing a variable means assigning it a value: score = 100;. These two operations can be combined in a single statement: int score = 100;. A variable must be initialized before its value is read; the compiler will report an error if you try to use a local variable that has not been assigned a value.

Java has three categories of variables. Local variables are declared inside a method or block and exist only while that method or block is executing. They have no default value and must be explicitly initialized. Instance variables (also called fields) are declared inside a class but outside any method. Each object of the class gets its own copy of instance variables, which are initialized to default values if not explicitly set (zero for numeric types, false for boolean, null for reference types). Static variables (also called class variables) are declared with the static keyword and are shared across all instances of a class. There is only one copy of a static variable per class, regardless of how many objects are created.

Variable names in Java must begin with a letter, underscore, or dollar sign, and can contain digits after the first character. By convention, variable names use lowerCamelCase: firstName, totalAmount, numberOfStudents. Names should be descriptive enough to convey the variable's purpose without requiring a comment.

Since Java 10, you can declare local variables using the var keyword and let the compiler infer the type: var count = 5; is equivalent to int count = 5;. Type inference with var only works for local variables where the initial value makes the type obvious; it cannot be used for instance variables or method parameters.

Interview tip: Be prepared to explain the difference between primitive variables and reference variables. A primitive variable directly stores its value (e.g., int x = 5 stores the number 5 in memory). A reference variable stores a memory address pointing to an object on the heap. This distinction becomes critical when discussing pass-by-value semantics and understanding why modifying an object inside a method can affect the caller while reassigning a reference inside a method does not.