I am working with jshell of JDK9.
I just created a final variable and assigned a value to it. And in the next line i just modified the value. And to my surprise, there was no error when modifying the final variables.
Here is the code snippets:
jshell> final int r = 0;
| Warning:
| Modifier 'final' not permitted in top-level declarations, ignored
| final int r = 0;
| ^---^
r ==> 0
jshell> r = 1;
r ==> 1
jshell> System.out.println("r = "+r)
r = 1
Is it what is expected from jshell? or there is some other way to work with final variables in jshell?
3.1. JLS 4.12. 4 states that if we remove the final modifier from a method parameter or a local variable without introducing compile-time errors, then it's effectively final. Moreover, if we add the final keyword to a variable's declaration in a valid program, then it's effectively final.
The local variables that a lambda expression may use are referred to as “effectively final”. An effectively final variable is one whose value doesn't change after it's first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.
You can declare a variable in any scope to be final. . The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages.
Final variables can be used to construct trees of immutable objects. Once constructed, these objects are guaranteed not to change anymore. To achieve this, an immutable class must only have final fields, and these final fields may only have immutable types themselves.
While creating a final variable at the top-level is not supposed to be practiced. But I guess there is no hard way of restricting such usages.
From the documentation around JShell.eval
The modifiers
public
,protected
,private
,static
, andfinal
are not allowed on op-level declarations and are ignored with a warning.Synchronized, native, abstract, and default top-level methods are not allowed and are errors.
If a previous definition of a declaration is overwritten then there will be an event showing its status changed to OVERWRITTEN, this will not occur for dropped, rejected, or already overwritten declarations.
The warning stated above is quite visible when you execute jshell
in verbose mode as follows:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With