0

I want to compile and execute this program with "javac" and "java" commands :

package mypackage;

public class Myclass {

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

The problem I have : When I am in "mypackage" folder and I use "javac" in it, it produces the file "Myclass.class". But when I use the command "java Myclass" (I'm still in the "mypackage" folder), I have this message :

Error: Could not find or load main class Myclass
Caused by : java.lang.NoClassDefFoundError: mypackage/Myclass (wrong name: Myclass)

The solution I found : I should not go inside "mypackage" folder and execute "java Myclass" but go one folder up and execute "java mypackage.Myclass" (it works). https://stackoverflow.com/a/7509317/10104743

My question : I see some people who can run both "javac Myclass.java" and "java Myclass" commands directly without the need to go one folder up as I did. Why does it not work with me and what can I do to fix this ?

Spn
  • 410
  • 2
  • 7
  • 16
  • 2
    You’ve specified a package name for your class (`mypackage`) so `java` expects to find `Myclass` in a directory called `mypackage` – MTCoster Feb 07 '19 at 23:15
  • 1
    You should be in the directory that *contains* `mypackage`, and you should issue `javac mypackage/Myclass.java` and `java mypackage.Myclass`. What you've seen only works if there is no `package` statement. – user207421 Feb 07 '19 at 23:41
  • If you do not specify a package in your source, then you can use 'javac MyClass.java' to compile in the directory containing the source, and you can use 'java MyClass' to execute it in that directory. – FredK Feb 08 '19 at 00:10

0 Answers0