Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jshell - unable to find printf

Why does my jshell instance (JDK Version 9-ea) unable to identify printf() statement ? Below is the error I observe,

jshell> printf("Print number one - %d",1)
|  Error:
|  cannot find symbol
|    symbol:   method printf(java.lang.String,int)
|  printf("Print number one - %d",1)
|  ^----^

I am able to access printf, provided I specify it in a regular way.

jshell> System.out.printf("Print number one - %d",1)
Print number one - 1$1 ==> java.io.PrintStream@1efbd816

Any pointers?

like image 622
R K Avatar asked May 05 '17 06:05

R K


3 Answers

An earlier version of JShell had a printf method pre-defined but it was removed from early access builds. You can of course define your own printf method:

jshell> void printf(String format, Object... args) { System.out.printf(format, args); }

Or you can get the printing methods that were in earlier builds back by starting JShell with:

jshell --start DEFAULT --start PRINTING

(If you use only --start PRINTING you won't get the default imports.)

For more information see bug JDK-8172102 in the Java bug database and changeset b2e915d476be which implemented it.

like image 142
David Conrad Avatar answered Nov 20 '22 06:11

David Conrad


Does it simply work without jshell? This can't work like this, since there is no such method defined outside PrintStream.

You could define your own printf like this:

jshell> private  void printf(String s) { System.out.println(s); }

And later use it :

jshell> printf("test")
test
like image 31
Eugene Avatar answered Oct 08 '22 20:10

Eugene


Java is an object-oriented language and you cannot call a non-static method without an object associated with this method. printf is a non-static method of the class PrintStream and you cannot call it without a PrintStream instance.

There are some PrintStream instances in the standard Java library like System.out and System.err, so you can call System.out.printf() or System.err.printf(), but plain printf() does not work because jshell does not know which object this printf() belongs to.

like image 44
ZhekaKozlov Avatar answered Nov 20 '22 05:11

ZhekaKozlov