Java Program to Demonstrate Example of Final Variable

You are currently viewing Java Program to Demonstrate Example of Final Variable

Java program to demonstrate example of final variable

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());
        }
    }
}
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

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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply