Home » Java programs » Java programs (final keyword)

Declaring a constant in Java

Here, we are going to learn how to declare a constant in Java. In the given program, we are going to declare multiple types of constants in Java.
Submitted by IncludeHelp, on July 14, 2019

Since, Java does not support constant declaration directly like other programming languages, to make a variable constant; we can declare a variable static final.

The static defines that variable can be accessed without loading the instant of the class and final defines that the value cannot be changed during the program execution.

Syntax:

    final static datatype constant_name = value;

Note: While declaring a constant – it is mandatory to assign the value.

Example:

    final static int MAX = 100;

Java code to declare and print the constant

// Java code to declare and print the constant
public class Main {
    //integer constant
    final static int MAX = 100;
    //string constant
    final static String DEFAULT = "N/A";
    //float constant
    final static float PI = 3.14f;

    public static void main(String[] args) {
        //printing the constant values
        System.out.println("value of MAX = " + MAX);
        System.out.println("value of DEFAULT = " + DEFAULT);
        System.out.println("value of PI = " + PI);
    }
}

Output

value of MAX = 100
value of DEFAULT = N/A
value of PI = 3.14




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.