Getting JShell Error: ';' expected for basic HelloWorld.java program

789 views Asked by At

Only ever used IDEs for developing in Java and wanted to learn how to use JShell but I'm getting the following error for a basic hello world example and anything else I try. Don't understand where the ';' error is coming from.
|javac HelloWorld.java
| Error:
| ';' expected
| javac HelloWorld.java;

code for HelloWorld.java

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

2

There are 2 answers

0
Ori Marko On

You don't compile in JShell, you can add the main method and then call it

 public static void main(String[] args) {
     System.out.println("Hello World");
    }
 }

 main(null);

The following examples shows a method being defined and the method run:

jshell> String grade(int testScore) {
 .....
 jshell> grade(88)
0
Thufir On

Here are two different "hello world" programs:

thufir@dur:~/jshell$ 
thufir@dur:~/jshell$ java hello.java
Hello World from Java
thufir@dur:~/jshell$ 
thufir@dur:~/jshell$ cat hello.java
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World from Java");
  }
}


thufir@dur:~/jshell$ 
thufir@dur:~/jshell$ jshell hello.jsh
Hello World
thufir@dur:~/jshell$ 
thufir@dur:~/jshell$ ./hello.jsh 
jshell 11.0.1
Hello World
thufir@dur:~/jshell$ 
thufir@dur:~/jshell$ cat hello.jsh 
//usr/bin/env jshell --show-version "$0" "$@"; exit $?
System.out.println("Hello World")
/exit
thufir@dur:~/jshell$ 

the .jsh or JShell script is executable so can run a few ways. Hope that helps.