Posts

Showing posts with the label Java Final Variable

Final Keyword in Java Explained with Examples

  Final Keyword in Java The final keyword in Java is used to make a variable’s value constant, meaning the value cannot be changed once assigned. Final Variables When a variable is declared as final: The variable must be initialized once Reinitialization is not allowed Any attempt to change the value results in a compile-time error Example : final int x = 10; // x = 20; // Compile-time error Final with Static and Instance Variables When a static variable or instance variable is declared as final, it does not support default values Such variables must be declared and initialized together The value must be assigned only once Valid syntax: class Example {     static final int A = 100;     final int B = 50; } Purpose of Final Keyword The final keyword is used to: Create constant values Prevent accidental modification of variables Improve code readability and safety