Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final variables are not functioning well in jshell

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?

like image 431
KayV Avatar asked Dec 19 '17 05:12

KayV


People also ask

How do you make a local variable effectively final?

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.

How do you use the final variable in lambda?

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.

What are final variables?

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.

How and why final variables are used?

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.


1 Answers

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, and final 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:

enter image description here

like image 110
Naman Avatar answered Sep 27 '22 23:09

Naman