Constants

constants

package main;

import java.util.*;

/**
 * Java supports constants of character, string, boolean,
 * and numeric values.
 */
public class Constants {

    // 'final' keyword declares a constant value.
    public static final String S = "constant";

    public static void main(String[] args) {
        System.out.println(S);

        // A 'final' statement can appear anywhere.
        final int N = 500000000;

        // Constant expressions perform arithmetic with arbitrary precision.
        double D = 3e20 / N;
        System.out.println(D);

        // A numeric constant has no type until it’s given one, such as by an explicit conversion.
        System.out.println((long) D);

        // A number can be given a type by using it in a context that requires one,
        // such as a variable assignment or function call.
        // For example, here Math.sin expects a double.
        System.out.println(Math.sin(N));
    }
}

To run the program, compile the code and then use java to execute it.

$ javac Constants.java
$ java Constants
constant
6.0E11
600000000000
-0.28470407323754404

Now that we can run and build basic Java programs, let’s learn more about the language.