Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How to Define a Constant
2.1.
The Static Keyword 
2.2.
The Final Keyword
2.3.
Constant
3.
Types of Constants
3.1.
Numeric Constants
3.1.1.
Integer Constants
3.1.2.
Real Constants
3.2.
Non-Numeric Constants
3.2.1.
Character Constants
3.2.2.
String Constants
3.2.3.
Backslash Character Constants 
4.
Uses of Constants
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Constant

Author ANKIT KUMAR
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

The general meaning of constant is something that does not change. In Java, the variables are said to be constant if their values do not change throughout the execution of the program. 

As per the accepted convention, all the constants in Java are represented by capital letters. This helps in identifying them easily. 

In this article, we will learn everything about constants like:

  • How to define constants.
  • Types of constants.
  • Uses of constants.

Read More, addition of two numbers in java

How to Define a Constant

In Java, a chain of keywords “static final” is used to create a global variable with an unchangeable value.

If we want a value that cannot be changed and remain the same for every instance of the class, we need to combine the keyword static and final to achieve this in Java. The static keyword means the value is the same for every instance of the class. The final keyword means that once the variable is assigned a value, it can never be changed. 

The combination of the static final in Java is how we create a constant variable. It is to be understood that static and final are two different keywords in Java. They have different meanings. But when both are combined together, only then do we get a truly constant variable. 

The constants in Java are also known as identifiers as they are unique and can be identified easily.

Using only static or only final keywords for the variables will not make it completely constant. We shall see the same in the example later.

Syntax:

static final data_type CONSTANT_IDENTIFIER = value;

Example:

static final int demoVar = 18;

The Static Keyword 

In Java, a static member in a class simply means that it will be shared by all of the class's objects. For each instance of the class, a new variable will not be created. Being "static" in Java simply means that no object is required to access this field/method.

One may think that if a variable is static so every time we create an object of the class, a new copy of the variable will not be created, and therefore it can be said as a constant. However, this is not correct.

The problem is that although the new variable will not be created for every instance (object) of the class, if the value of the static variable is changed by one instance, the change is reflected for the other instance too. This is completely against the concept of constants, where we claim that the value of the identifier remains constant throughout the execution of the program.

Example:

public class CodingNinjas {


    //we create a static global variable with value=100
    static int demoVariable = 100;


    public static void main(String args[]) {


        //first instance of the class
        CodingNinjas object1 = new CodingNinjas();
        System.out.println("Value for the first instance:" + object1.demoVariable);


        //object1 changes the value of demoVariable to 200
        object1.demoVariable = 200;


        CodingNinjas object2 = new CodingNinjas();
        //Value accessed by the second object/instance is 200 and not 100.
        System.out.println("Value for the second instance:" + object2.demoVariable);
    }



}

Output: 

Value for the first instance:100
Value for the second instance:200

Explanation:

In the above code, we observe that when the first object (object1) of the class changes the value of the static variable to 200, the value accessed by the second object(object2) is 200. This proves that only making a variable static would not make it a constant.

You can also read about the topic of Java Destructor, Duck Number in Java

The Final Keyword

If a variable is declared final in Java, its value cannot be changed further in the entire code. Changing the value of a final variable will throw an error. However, using only the final keyword will not make a variable constant as per the definition we studied earlier.

The reason is that multiple instances of the same constant value will be created for every different object every time we create a new object. This means that not directly but indirectly, we can change the value of a final variable by creating a new object every time.

Example: 

public class CodingNinjas {


    //the final variable
    final int variable;


    //constructor to initialise the final variable
    public CodingNinjas(int val){
        this.variable=val;
    }


    public static void main(String args[]) {


        //first instance of the class
        CodingNinjas object1 = new CodingNinjas(100);
        System.out.println("Value of the final variable for the first instance:" + object1.variable);


        //second instance of the class
        CodingNinjas object2 = new CodingNinjas(200);
        System.out.println("Value of the final variable for the second instance:" + object2.variable);
    }


}

Output: 

Value of the final variable for the first instance:100
Value of the final variable for the second instance:200

Explanation:

  • In the above example, we have a global final variable "variable" which is initialised using the constructor.
  • For the first object, we pass 100 in the parameter. Therefore, the final variable gets the value 100.
  • For the second object, we pass 200 in the parameter. Therefore, the final variable gets the value 200.
  • We can see that although the variable has been marked as final but different instances of the class can have different values of the variable.

Constant

Now that we have discussed the static and final keywords and also why they are individually not sufficient to create a constant, let's try to define a constant with the help of an example.

Example 1:

public class CodingNinjas {
    static final int DEMO_VARIABLE = 100;
    public static void main(String args[]) {
        System.out.println("The value of the constant is: "+ DEMO_VARIABLE);
    }
}

Output: 

The value of the constant is: 100

Example 2:

public class CodingNinjas {


    //creating a constant by using staic and final keywords
    static final int DEMO_VARIABLE = 100;
    public static void main(String args[]) {


        //first instance of the class
        CodingNinjas object1= new CodingNinjas();
        System.out.println("Value for the first object is: "+object1.DEMO_VARIABLE);


        object1.DEMO_VARIABLE= 150; //java: cannot assign a value to final variable DEMO_VARIABLE error


        //second instance of the class
        CodingNinjas object2= new CodingNinjas();
        System.out.println("Value for the second object is: "+object2.DEMO_VARIABLE);
    }
}

Output: 

java: cannot assign a value to final variable DEMO_VARIABLE

Explanation:

  • Since the identifier DEMO_VARIABLE is a constant when the first object tries to change the value of the identifier, the error is shown at the console.

Example:

public class CodingNinjas {


    //creating a constant by using staic and final keywords
    static final int DEMO_VARIABLE = 100;
    public static void main(String args[]) {


        //first instance of the class
        CodingNinjas object1= new CodingNinjas();
        System.out.println("Value for the first object is: "+object1.DEMO_VARIABLE);


        //second instance of the class
        CodingNinjas object2= new CodingNinjas();
        System.out.println("Value for the second object is: "+object2.DEMO_VARIABLE);
    }
}

Output: 

Value for the first object is: 100
Value for the second object is: 100

Explanation:

  • When we removed the line object1.DEMO_VARIABLE= 150; the error was removed. This is because now, no attempt was made to change the constant identifier. 
  • The value of DEMO_VARIABLE  is 100 for both instances. This proves that DEMO_VARIABLE is a constant.

 

You can practice by yourself with the help of online Java Compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Constants

Different types of constants in Java are:

Numeric Constants

Numeric constants are those constants that contain numerals. It may or may not have a leading sign and decimal point.

The numeric constants are further classified into:

Integer Constants

Integer constants contain only the digits from 0 to 9. They do not have any decimal point, and by default, their data type is int.

  • Decimal Constants

It contains numeric digits ranging from 0 to 9. However, it should not start with 0.

Example: 100, 23456, 756782

  • Octal Constants

The octal constants contain digits between 0 to 7 and mandatorily begin with 0.

Example: 032, 075

  • Hexadecimal Constants 

Hexadecimal constants contain digits from 0 to 9 and letters "a" to "f" or from "A" to "F". It must begin with 0X or 0x. 

Example: 0x12, 0X72

Real Constants

Numeric constants with a decimal point are called real or floating-point constants. Their default data type is double. To represent a real constant, there should be at least one digit, and it should have a decimal point. However, it is not necessary to add digits before the decimal point.

Example: 2.567, 0.678, .67

A real constant can be represented in exponential form also. We use the character ‘e’ for the representation.

Example: 976.426 can be represented as 9.76426e2

Non-Numeric Constants

Non-numeric constants are exactly the opposite of numeric constants. They do not contain any digits.

The various non-numeric constants are:

Character Constants

A character constant has a maximum size of one. It can be any digit, alphabet, or special symbol. The character constants are included in single quotes.

Example: ‘d’, ‘6’, ‘$’

String Constants

String constants are made up of zero or more characters surrounded by double quotes (""). The compiler inserts the null character, i.e. '\0', at the end of the string automatically.

Example: “CodingNinjas”, “CSE”, “007”

Backslash Character Constants 

The backslash character constants are used in output methods. Each escape sequence has a Unicode value. This character constant cannot be printed.

Examples:

Uses of Constants

  • It makes it easy to understand as each constant has a unique name, and value does not change.
  • Change has to be made in only one place instead of changing in every place.
  • Since each constant has a specific meaning associated with it, it reduces programming mistakes.

Also see, Hashcode Method in Java and Swap Function in Java

FAQs

1.What are constants in Java?

Ans: In Java,  a constant is an entity that is immutable. Constants have a unique value and cannot be changed.

2. What is the syntax of declaring a constant in Java?

Ans: static final data_type CONSTANT_IDENTIFIER = value;

3. What are the various types of constants?

Ans: The various constants are integer constants, real constants, character constants, String constants, and backslash character constants.

4. Which keywords are necessary to make a variable a constant?

Ans: The static and final keywords.

5. What will happen if we try to change the value of a constant in Java?

Ans: It will show an error at the console.

Key Takeaways

In this article, we have extensively discussed constants in Java and their examples in the Java programming language.

  •  In Java,  a constant is an entity that is immutable. Constants have a unique value and cannot be changed.
  • The various constants are integer constants, real constants, character constants, String constants, and backslash character constants.

We hope that this blog has helped you enhance your knowledge regarding constants in Java and if you would like to learn more, check out our articles here

Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Difference between List and Set in Java
Next article
How to Create Immutable Class in Java
Live masterclass