Unable to find or load the class

Solved
bilach -  
KX Posted messages 19031 Status Modérateur -
Hello,

I just started with Java and here’s my first problem. I get the message “cannot find or load the main class” followed by the class name
when I run the “JAVA” command in the command prompt.
I first compiled the .java file with the JAVAC command.
No errors were reported when executing this command.

Since I’m just starting, I’m not really sure if it’s right or wrong, but here is my very small first program (source code):

public class HelloImad { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("Hello World !"); i++; } } }


Please help me.

9 réponses

MagicSonic Posted messages 1 Status Membre 6
 
Hi everyone!

I might be able to help you because my problem was similar to yours... (compilation works but execution won't start: "I can't find the static function or the class that contains it blablabla" <- I don't care, it just has to work!).

For everything to work properly, you need to check the following points:
  • Your PATH variable properly contains the path to the bin folder of the JDK (for me it's "C:\Program Files\Java\jdk1.6.0_45\bin"). It's fine on your side since you were able to compile (if you get an error message saying that javac, java... cannot be found or is not a recognized command, your first issue comes from here).
  • A simple thing, but make sure that your class containing the public static main function is indeed public (the compiler won’t tell you anything :/):


public class Main { public static void main(String args[]) { System.out.println("Hello world!"); } }
  • Finally, the commands to execute for compiling everything are (on Windows):


cd TheFolderContainingYourClasses // For me cd Desktop\TestJava java -cp "%cd%" YourClassName // In the example it’s Main (without the class!)


The first command places you in the folder where your .class files (obtained from compiling using javac) are located. This is essential.

The second command starts the execution. The cp flag means classpath (this way we explicitly tell Java where our .class files are). The value "%cd%" is the absolute path to the folder TheFolderContainingYourClasses (I put it in quotes because otherwise the command is misinterpreted).
Then YourClassName is the .class file containing the static main function.

There you go, I hope I was able to help you or that it can help others.

Have a nice day everyone!
11