1

I write a simple program using java language, then try to compile and run it on Windows console, the compile is ok, but when I try to run it with command line '>java HelloWorld', the console reports 'Error: Could not find or load main class', this is my code(c:\Sample\HelloWorld.java) as below:

package com.sample.test;

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

If I comment out the line "package com.sample.test", try the compile and run command lines again, everything is ok, I can't understand why. Here is the environment variables in my computer:

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_40
Path=%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;
CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar

My question is if I still want to reserve the package declaration, how can I run my program?

sunjinbo
  • 2,137
  • 4
  • 22
  • 45
  • 1
    Did you *compile* your code using `javac` at any point? – Matti Virkkunen Feb 24 '16 at 03:53
  • @MattiVirkkunen what he said. Also, make sure you set the cmd to the location of your file. So like `cd C://Users//Me//Desktop` (if its on the desktop) then do `javac HelloWorld.java`. Finally do `java HelloWorld`. Also, just to ensure that your path is set correctly. Try typing `javac` in the cmd and make sure it shows a usage dialog thing with parameters and stuff rather then an error of some sort. – Ashwin Gupta Feb 24 '16 at 04:01

1 Answers1

2

If you want to put your main class into a package, then you also have to give that package name when running it:

java com.sample.test.HelloWorld

And you have to make sure the class file can be found. You cannot run java from the directory that contains HelloWorld.class. You have to run it from the directory that contains the com folder (or adjust your classpath).

Thilo
  • 257,207
  • 101
  • 511
  • 656