×

Java Programs

Java Practice

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

Java Final Variable, Class, & Method Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.