Variables & Data Types

Introduction

Every program needs a way to store and work with information. An application may need to remember a product price, the number of items in a cart, a customer's name, or whether an order has been shipped. In Java, this information is stored in variables, and every variable has a data type that determines what kind of value it can hold.

Understanding variables and data types is one of the first important steps in learning Java because almost every Java program uses them.

What Is a Variable?

A variable is a named storage location used to hold a value while a program is running. A variable has a name, a data type, and a value. The name allows the program to access the stored value, the type determines what kind of value can be stored, and the value represents the data currently assigned to the variable.

For example:

int stockCount = 12;

Here, stockCount is the variable name, int is its data type, and 12 is its current value. The value stored in a variable can change during program execution, but the variable's declared type normally remains fixed.

Declaring and Initializing Variables

A variable can be declared first and assigned a value later, or both operations can be performed at the same time.

int stockCount;stockCount = 50;
double price = 29.99;

The first statement declares a variable without assigning an initial value. The second assigns a value to it. The third both declares and initializes the variable.

Initialization refers to giving a variable its first value. Assignment refers to putting a value into a variable after it has been declared. Therefore, initialization is a specific form of assignment.

You can also declare multiple variables of the same type on one line:

 int products = 10, orders = 5, customers = 20;

Although this is valid, declaring one variable per line is generally easier to read and maintain.

Local Variables and Default Values

Java treats local variables strictly. A local variable is declared inside a method, constructor, or block, and it must be assigned a value before the program reads it.

The compiler rejects this program because stockCount has not been assigned a value before it is used.

The corrected version is:

Fields declared inside a class receive default values automatically. Numeric fields receive zero, boolean fields receive false, and reference fields receive null. Local variables do not receive these automatic default values, so they must be initialized before use.

Java Is Statically Typed

Java is a statically typed programming language. This means the type of a variable is determined during compilation, and the compiler checks whether values being assigned to variables are compatible with their declared types.

For example:

int price = 100;price = "One Hundred";

This produces a compilation error because an integer variable cannot hold a text value.

The variable can instead be declared as a String when text is required:

String price = "One Hundred";

Static typing allows many type-related mistakes to be detected before the program runs. This provides greater predictability and helps developers identify problems earlier during development.

Java Data Types

Java divides data types into two major categories: primitive types and reference types.

Whiteboard
Whiteboard diagram

Primitive Data Types

Java provides exactly eight primitive data types. They represent simple values and are built directly into the language.

TypeUsed ForExample
byteSmall whole numbers byte age = 25;
shortWhole numbers with a small rangeshort year = 2026;
intCommon whole numbersint stock = 500;
longVery large whole numberslong views = 9000000000L;
floatDecimal values with less precisionfloat rating = 4.5f;
doubleDecimal values with greater precisiondouble price = 29.99;
charA single characterchar grade = 'A';
booleanTrue or false valuesboolean inStock = true;

The integer types are byte, short, int, and long. The floating-point types are float and double. The char type represents a single character, while boolean represents one of two logical values: true or false.

For most everyday integer calculations, int is the common choice. For decimal values, double is generally the default choice unless a specific reason exists to use float.

Reference Data Types

Reference types represent objects rather than primitive values. Common examples include String, arrays, and classes created by developers or provided by Java libraries.

String customerName = "Alex";int[] dailySales = new int[7];
Product product = new Product();

A variable using a reference type holds a reference to an object rather than storing the complete object directly in the same way a primitive variable stores its value. This distinction becomes increasingly important when working with objects, methods, arrays, and memory management.

Primitive Types vs Reference Types

The key difference is what the variable represents. Primitive variables represent simple values such as numbers, characters, and boolean values. Reference variables represent references to objects such as strings, arrays, and instances of classes.

Primitive types are the eight built-in types provided by Java, while reference types include objects created from classes and other object-based structures.

The var Keyword

Modern Java allows local variables to be declared using var. With var, the compiler determines the variable's type from the value assigned to it.

var stockCount = 50;var price = 29.99;
var customerName = "Alex";

Using var does not make Java dynamically typed. The compiler still determines the type when the variable is declared, and that type remains fixed.

For example, the compiler determines that stockCount is an int and that price is a double. The advantage of var is mainly convenience, especially when the type is obvious from the value or when writing the complete type would make the declaration unnecessarily long.

Variable Scope

Scope determines where a variable can be accessed in a program. A variable declared inside a block is generally available only within that block and its nested blocks.

In this example, cartItems is declared inside main, so it can be accessed throughout that method. The discount variable is declared inside the if block, so it is available only within that block. Trying to access discount after the closing brace of the if block results in a compilation error.

Understanding scope becomes especially important as programs grow and begin using multiple methods, classes, loops, and conditional blocks.

Constants with final

Sometimes a value should not change after it has been assigned. Java provides the final keyword for this purpose.

Once a final variable has been assigned, it cannot be assigned another value.

final double TAX_RATE = 0.18;TAX_RATE = 0.20;

The second assignment produces a compilation error because the variable has already been assigned.

Constants are commonly written using uppercase letters with underscores between words, such as TAX_RATE or MAX_CART_SIZE. This naming convention makes them easy to recognize.

The final keyword can also be applied to fields, method parameters, methods, and classes, where it has additional meanings. At the variable level, its most important purpose is to prevent reassignment.

Choosing the Right Data Type

Choosing an appropriate data type makes Java programs easier to understand and maintain. Use int for common whole-number calculations, long when values can exceed the range of int, double for most decimal calculations, boolean for true-or-false conditions, char for individual characters, and String for text.

For example:

int quantity = 5;double price = 49.99;
boolean available = true;
char category = 'A';
String productName = "Laptop";

The type should describe the kind of information the variable represents. This makes the code clearer and allows the compiler to detect incompatible assignments.

Common Mistakes

One common mistake is trying to assign a value of the wrong type to a variable. Another is attempting to use a local variable before assigning a value to it. Beginners also frequently try to access variables outside the block in which they were declared.

Another mistake is assuming that var makes Java dynamically typed. It does not. The compiler still determines a fixed type for the variable during compilation.

Using final variables incorrectly can also cause confusion. A final variable can be assigned only once, so attempting to change its value later produces a compilation error.

Interview Tip

A common interview question is "What is a variable in Java?"

A strong answer is: A variable is a named storage location used to hold a value during program execution. Every Java variable has a type that determines what kind of value it can store.

Another common question is "What is the difference between primitive and reference types?"

Primitive types represent simple built-in values such as numbers, characters, and boolean values. Reference types represent objects such as strings, arrays, and instances of classes.

A third common question is "Is Java statically typed when using var?"

Yes. var only allows the compiler to infer the type of a local variable. The type is still determined at compile time and does not change afterward.

Key Takeaways

  • A variable stores a value under a name.
  • Every Java variable has a type.
  • Java is statically typed.
  • Local variables must be assigned before they are read.
  • Java has eight primitive data types.
  • Reference types represent objects such as strings, arrays, and custom classes.
  • var allows the compiler to infer the type of a local variable.
  • Scope determines where a variable can be accessed.
  • final prevents a variable from being reassigned after initialization.
  • Choosing the correct data type improves code clarity and type safety.

Conclusion

Variables and data types form the foundation of Java programming. Variables allow programs to store and manipulate information, while data types define what kind of information those variables can contain. Java's strong static type system allows many mistakes to be detected during compilation, making programs more predictable and easier to maintain.

As you progress through Java, these concepts will appear everywhere. Variables will hold object references, method results, user input, calculations, collections, and application state. Understanding how declaration, initialization, assignment, scope, primitive types, reference types, var, and final work will make the next stages of Java much easier to understand.