Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jshell

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");
  }
}

like image 493
Alexander Wilson Avatar asked Sep 11 '25 14:09

Alexander Wilson


2 Answers

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)
like image 136
user7294900 Avatar answered Sep 13 '25 03:09

user7294900


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.

like image 38
Thufir Avatar answered Sep 13 '25 04:09

Thufir