Koray Tugay
Koray Tugay

Reputation: 23800

How can I put my class in a package when I compile from command line?

I have a TestClass java in folder:

c:\foo\bar\TestClass.java

The code looks like this:

public class TestClass {

    public static void main(String[] args){

        System.out.println("Hello World!");


    }
}

When I type

c:\foo\bar\javac TestClass.java 

then

c:\foo\bar\java TestClass

I see hello world fine.

But I want to append

 package bar; 

or

 package foo.bar;

to my class, because it is actually in folder: foo\bar

When I add

package bar;

and do this:

 c:\foo\javac bar\TestClass.java

compile is fine but when I try:

c:\foo\java bar\TestClass

I get: java.lang.NoClassDefFoundError because the package information is wrong I believe.

How can I make this work?

Upvotes: 0

Views: 64

Answers (2)

Stefan Freitag
Stefan Freitag

Reputation: 3608

If you want to call the main method in a specific class inside a package, please specify the full path to the class. In your case this would be bar.TestClass, i.e.

c:\foo>java bar.TestClass

As you can see I replaced the file separator (/) with a ..

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240898

do

c:\foo>java bar.TestClass

instead

compiled class is different than just TestClass it is now bar.TestClass fully qualified

Upvotes: 3

Related Questions