×

Java Programs

Java Practice

Java program to demonstrate example of final variable

Final Variable:

The final variable is just like a constant in C language, the final keyword is used to make a variable final (constant) and the value of the final variable can't be changed.

Program:

import java.util.*;

public class FinalVar {
    public static void main(String[] s) {
        try {
            // final integer variable
            final int max_user = 10;
            System.out.println("Value of max_user is: " + max_user);
        } catch (Exception Ex) {
            System.out.println("Oops Exception Occured - " + Ex.toString());
        }
    }
}

Output

Value of max_user is: 10

Now change the value of final variable

import java.util.*;

public class FinalVar {
    public static void main(String[] s) {
        try {
            //final integer variable
            final int max_user = 10;

            //try to change value of max_user
            max_user = 20;
            System.out.println("Value of max_user is: " + max_user);
        } catch (Exception Ex) {
            System.out.println("Oops Exception Occured - " + Ex.toString());
        }
    }
}

Output

/FinalVar.java:10: error: cannot assign a value to final variable max_user
            max_user = 20;
            ^
1 error

Java Final Variable, Class, & Method Programs »





Comments and Discussions!

Load comments ↻





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