Java Variables

In this article of Java tutorial, we will inspect the Java variables. We will get a deep understanding of Java variables and how to use them in your application.

Java Variables

When developing applications, we always use variables throughout the development process because they are one of the basic building blocks of programing. Variables are the core component of the Java programming model.In this tutorial we will get a deeper understanding of the four Java variables that exist in Java and how we can leverage them when developing applications.

We will cover several sub-topics not limited to a detailed explanation of what are variables in Java, how to name variables, variable assignment, type inference, the syntax for creating each variable, an example showing how each variable is implemented using a specific data type, and what aspect of the variables differentiates them.

Variables are used to store data for our application. A variable is a combination of a location in the computer’s memory and an associated name that we can use in our code to refer to the data in that memory location. Specifically, Java variables help us to store state data. State data is data related to the current state of the program as it is running.

1. Java Variable Types

Java provides the following 4 types of variable which we will be covering in details in this section.

  1. Instance variables (Non-Static Fields).
  2. Class variables (Static Variables).
  3. Local variables.
  4. Parameters
Java Variables
Java Variables

2. Variable Assignment

To declare or define a Java variable, we specify the data type, the name of the variable, and any value we want to store in the variable.For example, here we declare an integer value with the name age that holds the value 42:

int age=42 // int is the data type and age is the variable name.
Java Variables
Java Variables Assignment

The reason we use the term “variable” is because it is able to vary. After we have declared it, we can easily change the value of the variable as many times as we like. Let’s see this in action:

int age=42;
age=43;
age=44;

These lines are referred to as assignment statements (because we are assigning the value on the right to the variable named on the left) and the = sign is called the assignment operator.

We will cover the assignment operators in more details under Java operators.

3. Java Variables Naming Convention

While naming the Java variables, we need to keep in mind certain rule. These rules will be validated by compiler and you will get compile time error in case we don’t follow these rules. Let’ take a closer look at the Java variables naming convention.

  1. The Java variable name is case sensitive.
  2. Variables names can either start with the dollar sign $, the underscore _ or a letter.
  3. The name that is chosen for a variable may be followed by letters, digits, dollar signs, or underscore characters.
  4. Keep variable name descriptive to make the code easier to read and understand.
  5. We can’t use java keywords or reserved words as variable names.
  6. When the name of the variable contains letters only, use the camel case format to name the variables. The camel case starts with lowercase letters and the following words are capitalized.
//camel case naming convention
int bookPrice=200;

When the variable is a constant, the leading and subsequent words should be capitalized and separated by an underscore. For Example:

final String PRODUCT_TYPE = “electronic”;

4. Local Variables

Local variables are variables located in a method and these variables can only be used within the method. The local variables do not have any keywords that differentiates them from other variables apart from the fact that their scope is inside a method.

public class Vehicle {
    public static String startVehicle() {
        String message = “vehicle started”; //local varilable declared inside method
        return message;
    }
    public static void main(String[] args) {
        System.out.println(startVehicle());
    }
}

4.1. Local Variable type Inference

In the Local variable example above, we have created a method named startVehicle() and added a local variable containing a string value:

String message = “vehicle started";

This declaration can be made much simpler by removing the string initializer String and replacing it with non-null initializer var.To achieve this, the language level must be Java 10 and above. The `var` identifier infers the type from the context and helps the developer to write code that is easy to read and understand.We can rewrite the local variable of the method using the var identifier as shown below.

public class Vehicle {
    public static String startVehicle() {
        var message = “vehicle started”;
        return message;
    }
    public static void main(String[] args) {
        System.out.println(startVehicle());
    }
}

The var identifier can be used as a variable, method, or package name because it is not a keyword but a reserved type name and this means using it as a class or interface will be affected requiring renaming of the class or interface.The different types of variables that can be used with the var identifier include: local variable with initializers, enhance for-loop indexes, index variables declared in traditional for loops, try-with-resources variable, and formal parameter declarations of implicitly typed lambda expressions.

5. Parameters

Parameters are variables that are passed as arguments to methods, constructors, and exception handlers. In the local variable example, we hard coded the value being returned by the method but this value could be coming from an external source such as the user input.

To ensure a value is passed to the method, we add a parameter of type string to the method and this can be separated using a comma delimited list if we have more than one parameter. The value of the parameter will be passed to the method when running the program as shown below.

public class Vehicle {
    public static String startVehicle(String message) {
        return message;
    }
    public static void main(String[] args) {
        System.out.println(startVehicle(“vehicle started”));
    }
}

6. Class Variables (Static Fields)

These are variables declared inside the class and contain a static keyword. This means that the application has one copy of the variable and no matter how many objects are created the variable will only have one copy. The `final` keyword is added to indicate that the value of the static variable will never change. This is the reason they are called class variables because they do not belong to any object but to the class.

public class Vehicle {
    static final int vehicleWheels = 4;
    public static void main(String[] args) {
        System.out.println(vehicleWheels);
    }
}

7. Instance Variable

Each instance of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable

public class InstanceVariableExample {
    String inVar = "instance";

    public static void main(String args[]) {
        InstanceVariableExample var1 = new InstanceVariableExample();
        InstanceVariableExample var2 = new InstanceVariableExample();

        System.out.println(var1.myVar);
        System.out.println(var2.myVar);


        var2.myVar = "New Instance";


        System.out.println(var1.myVar);
        System.out.println(var2.myVar);
    }
}

//output
instance
instance
New Instance
instance

Summary

In this tutorial, we have learned about the Java variables and how to use them when developing our applications. The different subtopics that we have covered include: variable assignment, naming convention of variables, local variable type inference, class variables, local variables, and parameters. Source code for all our articles is available on the GitHub repository.