Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

java 9 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...