Q:

Java program to demonstrate example of final variable

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now