Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new for Java. I followed some tutorial to build a simple Java program using Eclipse as below:

C#
package samplelib;

public class samplelib {
    public static void main (String[] args) {
        System.out.println ("sample lib");
    }
}


I ran it inside Eclipse successfully. But when I compiled it at command line using 'javac' and then ran it using 'java' command, I got message like "Wrong: can't find or unable to load main class samplelib".
I deleted the first line "package samplelib", used 'javac'/'java' commands again. It rans successfully.
Then, I went back to Eclipse and ran it, I got the following error message:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at samplelib.samplelib.main(samplelib.java:4)

So, how come sometimes we need 'package statement' but sometimes we don't? Thanks.
Posted

1 solution

A package is somewhat like a folder, where a set of common files are kept together. All classes in a package are kept together, as described at http://docs.oracle.com/javase/tutorial/java/package/index.html[^]. When you build a Java program that has a package statement, then the compiled class is expected to be stored in a subdirectory with the same name. You then call java to execute it from its parent with a command line of the form:
java packagename/classname

You can also use the -classpath option to tell Java where your classes are stored.
 
Share this answer
 
Comments
CPallini 22-Dec-14 5:16am    
5.
Stan Huang 22-Dec-14 5:33am    
Thanks Richard MacCutchan. Your command works. But there is still a pending question: how come Eclipse can't accept a Java program without package statement?
Richard MacCutchan 22-Dec-14 6:41am    
I think that because using package is the 'normally accepted' method, that eclipse enforces it. It is probably a good idea to stick with it as all your programs will follow a standard model.
Stan Huang 22-Dec-14 19:41pm    
Thanks Richard very much. I will keep it in mind.
Richard MacCutchan 22-Dec-14 6:42am    
Thanks Carlo, have a good Christmas.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900