Search code examples
javaclassconsolecmdpackage

Opening class in package from console in Java


So when i try to open a java class that's not in a package from the command prompt it all works fine, but when I try to open a class that's in a package it gives me NoClassDefFoundError. And when I list the package when I try to open the class (java somepackage/someclass) it says that it can't load or find the main class.

Any help?


Solution

  • What I can infer is, you have two classes:

    Test.java:

    // no package defined here
    
    class Test{
        public static void main(String[] args){
            System.out.println("Test");
        }
    }
    

    so you can compile and run it using:

    javac Test.java
    java Test
    

    Another class:

    Test.java:

    package test; // package defined here
    
    class Test{
        public static void main(String[] args){
            System.out.println("Test");
        }
    }
    

    And thus doing same thing gives you error. For this you need to be in the parent directory of 'test' folder in your terminal or cmd and use:

    java test.Test
    

    No problem with compiler. You can compile as usual using javac Test.java from inside 'test' folder.