0
/home/thiru/VS Code Files/Java Files
├── F
│   ├── test.class
│   └── test.java
└── G
    ├── c.class
    └── c.java

c.java imports F package and has main function

When I use javac and java :

  • :~/VS Code Files/Java Files/G$ javac -cp /home/thiru/VS\ Code\ Files/Java\ Files/ c.java

  • :~/VS Code Files/Java Files/G$ java -cp /home/thiru/VS\ Code\ Files/Java\ Files/ c

  • Error: Could not find or load main class c

  • Caused by: java.lang.ClassNotFoundException: c

When I simply use java command :

  • :~/VS Code Files/Java Files/G$ java -cp /home/thiru/VS\ Code\ Files/Java\ Files/ c.java

    Thirumal

test.java :

package F;

public class test{

    public static void d(){
        System.out.println("Thirumal");
    }

}

c.java :

import F.test;

public class c{

    public static void main(String[] args){
        test.d();
    }
}

What's the difference?

7
  • 3
    Your c.java has no package declaration, so there’s no reason for java c to look inside the G directory. Using java sourcecode.java is an entirely different beast. You specified a source code file and the launcher will compile it and run the first class found in it, regardless of its name or package. Commented Dec 11, 2024 at 12:16
  • Use code block format for the command prompts too. The characters in there are confusing Stack Overflow formatting, and it will be more readable too. Commented Dec 11, 2024 at 12:18
  • @Holger, But I'm compiling and runing that file from G directory, why doesn't it work? Commented Dec 12, 2024 at 6:10
  • 1
    The current directory doesn’t matter when you tell java to run a class name c, because you specified -cp /home/thiru/VS\ Code\ Files/Java\ Files/ so classes are resolved against that path. Commented Dec 12, 2024 at 9:54
  • 1
    Basically, yes. The standard loading strategy is to first check whether there’s a system class with that name and if not, resolution against the class path is attempted. When the class path has multiple entries, they are checked in the specified order. However, the module system supersedes this mechanism. When the class’s package belongs to a named module, the class is loaded directly from the module’s source. But that’s just for completeness as a class named c (not having a package) can’t belong to a named module. Commented Dec 12, 2024 at 13:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.