1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Error after compile Exception in thread "main" java.lang.NoClassDefFoundErr

Discussion in 'Mac Programming' started by JoeCmis, Aug 21, 2007.

  1. macrumors newbie

    Hi I am very new to Java programming, right now I am using a mac os 10.49
    I can create java documents using bbedit and then they compile when i type

    But when i type java *.java I get the following error

    Exception in thread "main" java.lang.NoClassDefFoundError

    If I type java "filename"
    without the .java at the end of the file the terminal has no response

    I understand i am supposed to some how set the classpath but i do not know how to do this
    Also I can create and compile and then run my java in the eclipse program that i have installed, but not from terminal and im not sure why.

    I do have eclipse installed and my java will compile and run in eclipse with no problems.
    Thanks for the help.
  2. macrumors 6502a

    I had the same errors when I started using java from the command line in Terminal.

    When you compile, you supply the .java in your syntax. IE

    javac myfile.java

    However, when you run the program, you don't:

    java myfile

    Java will run the myfile.class file produced from the compile step. If you navigate to the folder where your class files are produced, you don't need the -classpath parameter on the "java" command, nor do you need to set a classpath environment variable. However, you should read up on the java command from Terminal:

    java -?

    to familiarize yourself with the command line options.

  3. macrumors 68020


    Here's a quick and dirty example.

    First, your source file. This is HelloWorld.java:

    class HelloWorld
      public static void main (String args[])  
        System.out.println("Hello, world!");
    Then in terminal, these are your commands:
    % javac HelloWorld.java
    % java -cp ./ HelloWorld
    The "-cp ./" is just to ensure that it looks in the local directory for the .class file to run. Some JVMs add automatically search there, but not all do, so it's usually a good practice to explicitly set the classpath.

    Hope this helps.
  4. macrumors 68000


    Welcome to Java. :)

    Yea, what's happening is you're not actually compiling the code. Running "java" in the terminal should execute a compiled Java class. "javac" is the command you're looking for, and stands for "java compiler."

    So when you have some java code in a .java file, like HelloWorld.java, you must compile it using "javac HelloWorld.java", and then run the .class file using "java HelloWorld" (notice no .class at the end, it's not required.)


Share This Page