Lærne
Lærne

Reputation: 3142

Why does the `package` instruction in java make the class file impossible to run?

I'm trying to compile a java file with a package directive. However, when adding the directive to the most simple program stub, I get an error and cannot launch the program anymore... What's wrong ?

Dummy0:

class Dummy0 {
  public static void main( String[] args ) {
    System.out.println("Hello, world!");
  }
}

Dummy1:

package de.train;

class Dummy1 {
  public static void main( String[] args ) {
    System.out.println("Hello, world!");
  }
}

And here is the output I had. Everything compiled fine. But I cannot run the class de.train.Dummy1, although it's obviously there.

$ javac Dummy*.java
$ java Dummy0
Hello, world!
$ java Dummy1
Error: Could not find or load main class Dummy1
$ java de.train.Dummy1
Error: Could not find or load main class de.train.Dummy1
$ javap Dummy1.class
Compiled from "Dummy1.java"
class de.train.Dummy1 {
  de.train.Dummy1();
  public static void main(java.lang.String[]);
}

I'm under windows for this project. Is this some security restriction? How to remove it?

Upvotes: 1

Views: 328

Answers (2)

Shriram
Shriram

Reputation: 4411

If you are executing a java program without packages it will try to locate the classes in the same folder/directory. Package is nothing but the directory structure in windows. If you want to execute a class in some other folder you have to specify the complete package and execute.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500913

It's looking for the class de.train.Dummy1, which means it will look for a file called Dummy1.class in a directory de\train - but the file will actually be in the current directory.

Options:

  • Keep your source code where it is, but get the compiler to generate the directory structure for you:

    > javac -d . Dummy*.java
    > java de.train.Dummy1
    
  • Move Dummy1.java into a de\train directory:

    > javac de\train\Dummy*.java
    > java de.train.Dummy1
    

Upvotes: 2

Related Questions