Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run echo example from Jshell [duplicate]

Tags:

java

jshell

I read such a command line arguments example:

public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

It runs properly from command line, how could I run it from Jshell?

jshell> Echo.main testing
|  created variable testing, however, it cannot be referenced until class main is declared

It report error that failed to be referenced.

like image 270
AbstProcDo Avatar asked Apr 20 '26 15:04

AbstProcDo


1 Answers

You invoke it as any other static method:

Echo.main(new String[] { "hello", "world" });

Full session:

$ jshell
|  Welcome to JShell -- Version 11.0.8
|  For an introduction type: /help intro

jshell> public class Echo {
   ...>     public static void main (String[] args) {
   ...>         for (String s: args) {
   ...>             System.out.println(s);
   ...>         }
   ...>     }
   ...> }
|  created class Echo

jshell> Echo.main(new String[] { "hello", "world" });
hello
world

Note that you can declare your main method as follows:

public static void main(String... args) { ... }

This is binary compatible with String[] args syntax, but would allow you to invoke it as follows:

Echo.main("hello", "world");
like image 98
aioobe Avatar answered Apr 23 '26 05:04

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!