1. java
  2. /basics
  3. /variables

The Essentials of Java Variables

What are Variables in Java and Why do They Matter?

Variables in Java are critical for storing and managing data. They act as temporary storage locations that hold data while our program is running. Aside from storing, we can modify and retrieve the data, thereby enabling us to perform various operations and calculations.

Declaring Variables in Java - Syntax and Naming Conventions

So, declaring a variable in Java involves specifying its data type and name, which tells the compiler the type of data it will store and how to reference it. Let's take a look at the general syntax for declaring variables.

dataType variableName;

Data Types and Naming Conventions

Java is a statically-typed language, which means that we must define the data type of a variable when we declare it. We'll encounter some common data types, each serving a specific purpose and optimized for memory usage and performance.

As for naming, we should follow some general conventions to improve our code readability and maintainability.

Consider opting for meaningful names that unmistakably convey the variable's purpose. Start with a lowercase letter, adopting camelCase for compound words (e.g., myVariableName), to maintain consistency. At the same time, refrain from beginning variable names with numbers or special characters, except for the underscore and currency signs, as it may lead to confusion or errors.

Lastly, we should avoid using reserved Java keywords, as they have predefined meanings in the language and can cause conflicts.

For instance, below we have an example of declaring a variable of type int.

int myAge;

Find out more about Java's syntax, identifiers, and keywords here

Feel free to explore Java's data types in detail in our beginner's guide

Initializing Variables

After declaring the variable, we can assign a value to it. The process is known as initialization. We can initialize a variable at the time of declaration or later on in the program. Let's take a look at both approaches.

Initializing at Declaration

To initialize a variable at the time of declaration, we can simply include an assignment statement with the = operator and a value.

dataType variableName = value;

For instance, we could initialize an int variable like so:

int myAge = 29;

Also, we can showcase initialized variables with some of the common data types that we mentioned earlier.

class Main {
  public static void main(String[] args) {

    // boolean
    boolean isRaining = true;

    // byte
    byte numberOfPages = 20;

    // int
    int population = 12345678;

    // float
    float distance = 5.67f;

    // double
    double pi = 3.14159265359;

    // char
    char letter = 'A';

    // string
    String greeting = "Welcome to Java!";

    System.out.println("boolean: " + isRaining);

    System.out.println("byte: " + numberOfPages);

    System.out.println("int: " + population);

    System.out.println("float: " + distance);

    System.out.println("double: " + pi);

    System.out.println("char: " + letter);

    System.out.println("String: " + greeting);
  }

}

Observe the output below.

boolean: true
byte: 20
int: 12345678
float: 5.67
double: 3.14159265359
char: A
String: Welcome to Java!

Initializing After the Declaration

If we need to assign a value to a variable later in your program, we can do so using a separate assignment statement:

variableName = value;

For example, you might first declare an int variable and then assign a value to it:

int myAge;
myAge = 29;

Changing a Value in a Variable

Once a variable is declared and initialized, its value can be changed throughout the program's execution. This is one of the primary reasons for using variables, as they allow us to store and manipulate data dynamically. To change a variable's value, we simply need to assign it a new value using the assignment operator = that we used before.

int numberOfItems = 10; // Initial value
System.out.println("Initial number of items: " + numberOfItems);

numberOfItems = 15; // Changing the value
System.out.println("Updated number of items: " + numberOfItems);

Output:

Initial number of items: 10
Updated number of items: 15

Now that we've briefly explored declaration, initialization, and changes let's discuss the concept of variable scope and how it affects visibility within your program.

Variables Types and Scope

Variable scope determines the visibility and accessibility of a variable within your Java program. Understanding the concept of scope is essential for managing your variables effectively and avoiding potential issues, such as naming conflicts or unintended modifications. In Java, there are three main types of variable scope.

Local Scope

When we declare variables within a method, block, or constructor, we call them local variables. These variables are only accessible within the scope they are declared in, and once the block or method has finished executing, the variables are destroyed, and their memory is freed. It's important to note that we must initialize local variables before using them within their defined scope.

public void myMethod() {
    int localVar = 10; // Local variable, accessible only within myMethod
}

Instance Scope

Instance variables, also known as fields, member variables, or non-static variables, are declared within a class but outside any method, constructor, or block. We can access these variables through any method within the class, and they are associated with objects or instances of the class. Each object has its own copy of instance variables, allowing for unique values per instance. We usually initialize instance variables using constructors while creating an object, but we can also use instance blocks for initialization.

public class MyClass {
    double instanceVar; // Instance variable, accessible within any method in MyClass
}

Class Scope

Class variables, also known as static variables, are declared within a class using the static keyword, outside of any method, constructor, or block. These variables are associated with the class itself, not individual instances. We can only have one copy of a static variable per class, regardless of how many objects we create. Static variables are created at the start of program execution and destroyed automatically when execution ends. We can access class variables directly using the class name, and changes to static variables will be reflected in all objects of a class, as they share the same copy.

public class MyClass {
    static String classVar; // Class variable, accessible within MyClass and other classes
}

Keep in mind that these mock examples are primarily intended to illustrate the basic concepts of scope. Real-world scenarios would be more elaborate, but for now, we can focus on grasping the fundamentals.

Final Thoughts

So far, we've gone through the core aspects of variables. We discussed declaration, initialization, and naming, and offered a brief overview of the different scopes. There are more nuances to how they work, and the complexity will naturally grow as you progress. To expand your knowledge of the closely-related concepts we mentioned, consider checking out the resources below.

Useful Resources

Java Data Types - A Beginner's Guide

The Basics of Java Syntax

An Introduction to Java Output

Insight on Local Variable Type Inference in JDK10 and later versions