Openjdk初体验

Page content

3 Billion Devices Run Jvav

1. Create a new .java file

vim /path/to/your/project/Main.java

2. Fill in the Hello World code:

public class Main {  
    public static void main(String[] args) {  
        System.out.println("hello,,,");  
    }  
}  

3. Quit and save

:wq

4. Compile

docker run --rm -v /path/to/your/project:/Project -w /Project openjdk javac Main.java  

After that, you can see a new file called Main.class.

5. Run

docker run --rm -v /path/to/your/project:/Project -w /Project openjdk java Main  

6. Enjoy coding with java.


While running the hello world with the OpenJDK, I have encountered a problem.

When I tried to compile the source code, javac popped the following error and exit.

bash-4.4# javac hello.java   
hello.java:1: error: class Main is public, should be declared in a file named Main.java  
public class Main {  
       ^  
1 error  

Solution:
Rename the .java file to match the public class XXX.
If your class is called Foo, your file name must be Foo.java.
In my case, I wrote public class Main {}, so the .java file must be Main.java.


ref: Error: class X is public should be declared in a file named X.java