Variables and Constants in Java

  • Last Updated: July 4, 2023
  • By: javahandson
  • Series
img

Variables and Constants in Java

Please check the previous article regarding data types in Java to understand this topic better. In this article, we will learn about variables and constants in Java with proper examples.

Variables

As we know data types in Java help us to allocate a sufficient amount of space in the main memory of the computer. This memory will store some value which we will provide.

This value in the memory can change from time to time hence they are called variables. In simple terms, the variable is an identifier whose value will change from time to time during the execution of a program.

Variable Declaration

The process of assigning a sufficient amount of memory space by giving some unique name to that space is known as variable declaration. This unique name will help us to identify the value that is stored in that memory space. The name given to this space is known as an identifier.

We have to declare the variable first before using it in the program else we will get a compile time exception.

Syntax: datatype var;

datatype can be a primitive, derived or a user defined one.

var is the variable name.

Ex. int result;

int is the datatype which decides the amount of memory to be reserved.

result is the variable name.

Variable Initialization

The process of assigning some user-defined values to the variable is known as variable initialization.

Ex. int result = 50;

If we do not provide any value then it will take the default value of that data type.

int result = 50;

int is the data type that decides the amount of memory to be reserved. int will reserve 4 bytes of memory. 50 will be stored in the memory location. The actual memory name will look something like 0X4560XT.

int 0X4560XT = 50

Using the actual memory name in the program is very difficult to remember because a program can hold hundreds of different variables. Hence we will make use of some identifiers which are easy to write and remember.

int result = 50;

Here result is the identifier or variable name which we will make use of in the program.

The identifier value i.e. 50 can change somewhere in the program hence it is known as a variable.

int result = 50;

result = result + 50; // Here the identifier value is updated

System.out.println(result);

Output : 100

Constants

A constant is a variable whose value cannot be changed during the execution of the program. We can make use of the final keyword in Java to make things constant.

We can use the final keyword in three places:

  • Final at variable level
  • Final at method level
  • Final at class level

Final at variable level

If we don’t want the value of a variable to change in the program then we can do that using the final keyword. For variables, we can use the final keyword in 2 ways:

While Declaration

We can use the final keyword while declaring the variable.

Ex. final int RESULT;

Once we declare the variable we will get a chance to do the assignment for only one time.

RESULT = 50;

After the first time assignment, we cannot change the value of the RESULT variable.

RESULT = RESULT + 10; // Invalid

While Initialization

We can use the final keyword when we initialize the variable directly.

Ex. final int RESULT = 50;

We cannot modify or reassign the value after the above step.

RESULT = RESULT + 10; // Invalid
package com.javahandson;

public class Addition {

    final int RESULT = 50;

    void calculate()
    {
        RESULT = RESULT + 50;
    }

    public static void main(String[] args) {

    }
}

Output : java: cannot assign a value to final variable RESULT 

Final at method level

If we want to perform any business operation then we will create a function to execute that logic. Function in Java is known as a method.

If we want to create a common utility method whose logic will not change then we can make that method as a constant. This can be done using the final keyword. The final method can be used by any programmer but they cannot modify or change it.

Ex. We will create a method that will add 2 numbers

int addition(int a, int b) {
    return a+b;
}

Will the logic of this addition method ever change? No, it will never hence we will make it final.

final int addition(int a, int b) {
    return a+b;
}

Once we make the method final then no one can override this method to give the custom implementation.

package com.javahandson;

public class Addition {

    final int addition(int a, int b)
    {
        return a+b;
    }
}

class Operation extends Addition {

    int addition(int a, int b)
    {
        return a*b;
    }
}

Output : java: addition(int,int) in com.javahandson.Operation cannot override addition(int,int) in com.javahandson.Addition overridden method is final

Final at class level

A class will have many features if we don’t want any other class to use the features of this class then we will make this class final.

package com.javahandson;

final public class Addition {

    int addition(int a, int b)
    {
        return a+b;
    }
}

class Operation extends Addition {

}

Output : java: cannot inherit from final com.javahandson.Addition

Conclusion on the final keyword

  • final variables cannot be modified
  • final methods cannot be overridden
  • final classes cannot be extended or reused.

7 Rules for Naming the Variables

1. The first letter of the variable should be an alphabet.

2. The first letter of the variable should be in small caps.

Ex. int result

3. If the variable name contains multiple words then the second word should start with a capital letter.

Ex. int studentResult;

4. Length of the variable should not exceed more than 32 characters.

5. We should not use any Java keywords as the variable names.

Ex. int Class; // Class is a keyword and cannot be used as a variable name.

6. We can only use an underscore in the variable name. We cannot use any other special symbols.

7. Variables with constant values should be written in capital letters. If there are multiple words in the variable name with constant values then they should be split using underscore.

Ex. final int RESULT = 50;

final int STUDENT_RESULT = 150;

So this is about Variables and Constants in Java. I hope you liked this article. If you have any question on this topic please add it below in the comment section. Thank you for reading this article.

Leave a Comment