ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.