Java Variables

In traditional programming languages, such as Java, a variable is a placeholder for storing a value of a particular type: a string, a number, or something else. This Java tutorial discusses what a variable is and the types of variables. Also, look at the example of how to declare a variable in Java. We will also see some best practices for naming the variables in Java.

The Java programming language uses both “fields” and “variables” as part of its terminology. Fields refer to variables declared outside methods, and variables are referred to declarations inside methods, including method arguments.

1. What is a Variable?

As the term suggests, a variable is a placeholder whose value can vary during the runtime. In Java, a variable is a named reference to a memory area where the value of the variable is stored.

Java Variable Example
How a variable works

1.1. How to Declare a Variable?

Every variable has a name (also known as an identifier) to distinguish it from others. Before you start using a variable, you must declare it.

The given syntax explains how to declare a variable in Java. The left part of this statement describes the variable, and the right part describes something that is assigned to it.

[data_type] [variable_name] = [variable_value];

  • data_type – refers to the type of information stored in the memory area. It determines the possible operations that can be performed on the variable and which values can be stored in it.
  • variable_name – refers to the name of the variable and distinguishes it from other variables. The name of a variable cannot start with a digit; it usually starts with a letter. Always try to choose meaningful and readable names for variables to make your code easy to understand.
  • variable_value – refers to the value to be stored in the memory area.

For example, the below statements are valid variable declarations in Java.

int i = 10;         //Variable of int type

String str = "howtodoinjava.com";   //Variable of String type

Object obj = new Object();      //Variable of Object type

int[] scores = [1,2,3,4,5,6,7,8,9];         //Variable of int array type

Java allows several flexible syntaxes for declaring the variables. For example, we can declare several variables of the same type as a single statement:

int i = 1, j = 2;

We can also separate the declaration and initialization in separate statements.

int i;
i = 1;

1.2. Example

Once a variable has been declared, its value can be accessed and modified using the name.  

In the following example below, we declare two ‘int‘ variables and assign their addition result to a third variable ‘sum‘.

int i = 10;
int j = 10;

int sum = i + j;

System.out.println( sum );  // Prints 20

There is one restriction for variables: you can only assign a value of the same type as the type of the initial variable. In the previous example, ‘sum‘ has to be int or other number type. It cannot be a String, Boolean or any other type.

2. Type Inference

Since Java 10, you can write var instead of a specific type to force automatic type inference based on the type of assigned value:

var [variable_name] = [variable_value];

Here are two examples below:

var language = "Java"; // String
var num = 1; // int

Although it allows the code to be more concise, it may affect the code readability in a bad way.

See Also: Java ‘var’ Keyword

3. Widening and Narrowing

3.1. Widening

When a small primitive type value is automatically accommodated in a bigger/wider primitive data type, this is called the widening of the variable. In given example, int type variable is assigned to long type variable without any data loss or error.

int i = 10;
long j = i;

System.out.println( i );
System.out.println( j );

Program output.

10
10

3.2. Narrowing

When a larger primitive type value is assigned in a smaller size primitive data type, this is called the narrowing of the variable. It can cause some data loss due to fewer bits available to store the data. It requires explicit type-casting to the required data type.

In the given example, int type variable is assigned to byte type variable with data loss.

int i=198;
byte j=(byte)i;  

System.out.println( i );
System.out.println( j );

Program output.

198
-58

4. Types of Variables in Java

In Java, there are four types of variables. These variables can be either of primitive types, class types or array types. All variables are divided based on the scope of variables where they can be accessed.

4.1. Instance Variables

Variables declared (in class) without static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class. They are also called state variables.

public class VariableExample
{
    int counter = 20;         //1 - Instance variable
}

4.2. Static Variables

Also, known as class variables. It is any field declared with the static modifier. It means that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

public class VariableExample
{
    static float PI = 3.14f;    //2 - Class variable
}

A variable declared as “public static” can be treated as global variable in java.

4.3. Local Variables

These are used inside methods as temporary variables exist during the method execution. The syntax for declaring a local variable is similar to declaring a field. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

public class VariableExample
{
    public static void main( String[] args ) {
 
        int age = 30;     //3 - Local variable (inside method body)
    }
}

4.4. Method Arguments

An argument is a variable that is passed to a method when the method is called. Arguments are also only accessible inside the method that declares them, although a value is assigned to them when the method is called.

public class VariableExample
{
    public static void main( String[] args ) {
 
        print( 40 );
    }
 
    public static void print ( int param ) {      //4 - Method Argument
 
        System.out.println ( param );
    }
}

5. Difference between Instance and Class Variables

  • Instance variables (non-static fields) are unique to each instance of a class.
  • Class variables (static fields) are fields declared with the static modifier; there is exactly one copy of a class variable, regardless of how many times the class has been instantiated.
  • To access the instance variable, you MUST create a new instance of the class. Class variables are accessible through class reference, and do not require creating an object instance. Take an example. We have a class Data with one instance variable and one class variable.
public class Data 
{
    int counter = 20;
 
    static float PI = 3.14f;
}

We can access both variables in a given way.

public class Main 
{
    public static void main(String[] args) 
    {
        Data dataInstance = new Data();
         
        //Need new instance
 
        System.out.println( dataInstance.counter );    //20
         
        //Can access using class reference
 
        System.out.println( Data.PI );                 //3.14 
    }
}

6. Variable Naming Conventions in Java

There are a few rules and conventions related to how to define variable names.

  • Java variable names are case-sensitive. The variable name employee is not the same as Employee or EMPLOYEE.
  • Java variable names must start with a letter, or the $ or _ character.
  • After the first character in a Java variable name, the name can also contain numbers, $ or _ characters.
  • Variable names cannot be reserved keywords in Java. For instance, the words break
    or continue are reserved words in Java. Therefore you cannot name your variables to them.
  • Variable names should written in lowercase. For instance, variable or apple.
  • If variable names consist of multiple words, then follow camelcase notation. For instance, deptName or firstName.
  • Static final fields (constants) should be named in all UPPERCASE, typically using an (underscore) _ to separate the words in the name. For example LOGGER or INTEREST_RATE.

7. Summary

Variables in Java are used to store values of different data types. They need to be declared with a type and a name. Variables can be modified after declaration, but the new value must be of the same type as the old one. In Java 10, the var keyword was introduced for automatic type inference.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.