0

My code like this

//package com.web_tomorrow;

public class RunThis1 {

    public static void main(String[] args) {
        System.out.println("Run ....RunThis1");

    }
}

When I run javac command with "package com.web_tomorrow" package name commented or not commented in both cases it can compile well. But When I run java command with "package com.web_tomorrow" package name, I mean not commented, it shows the Error: Could not find or load main class RunThis1 And if I comment/ remove the package name and then run the java command it executes.

Could anyone plz explain why java cant find RunThis1.class file while javac can find RunThis1.java from the same folder which is web_tomorrow ?

C:\JavaPractices\CPTest\src\com\web_tomorrow>java RunThis1 Error: Could not find or load main class RunThis1

C:\JavaPractices\CPTest\src\com\web_tomorrow>javac RunThis1.java

C:\JavaPractices\CPTest\src\com\web_tomorrow>java RunThis1 Run ....RunThis1

How java command is related to package name ? How package name is affecting java to find main class ?

My Envr variable classpath value is .

SayedRakib
  • 181
  • 1
  • 2
  • 10

2 Answers2

2

Java packages are like directory. So if you have your class file MyClass.java in package like com.myfirm.pack then this should be in src directory like:

src
   com
      myfirm
          pack
              MyClass.java

if you wish to compile your java code (assuming you are at src folder) you need to do the following:

c:\src> javac com\myfirm\pack\MyClass.java

While if you want to run it, you need to do:

c:\src> java -cp . com.myfirm.pack.MyClass

SMA
  • 36,381
  • 8
  • 49
  • 73
  • C:\JavaPractices\CPTest\src\com\web_tomorrow>javac RunThis1.java C:\JavaPractices\CPTest\src\com\web_tomorrow>java -cp . RunThis1 Error: Could not find or load main class RunThis1 – SayedRakib Nov 06 '14 at 12:55
  • Try following commands: cd C:\JavaPractices\CPTest\src; javac com\web_tomorrow\RunThis1.java;java -cp . com.web_tomorrow.RunThis1 – SMA Nov 06 '14 at 12:55
  • Can I run Java from pack directory, if YES then How ? I can compile from pack directory but can not run java from pack directory – SayedRakib Nov 06 '14 at 13:01
  • Yes if you want to run from web_tommorow use: java -cp c:\JavaPractices\CPTest\src com.web_tomorrow.RunThis1 – SMA Nov 06 '14 at 13:04
  • Yes, it works, Thanks. But why javac can compile from web_tomorrow directory without -cp while java can not find from same directry ? why compiling and running find/manage to the file path in different ways, although .class and .java files are in same directory ? – SayedRakib Nov 06 '14 at 13:12
  • That's a new follow up question. I would suggest you open new question and close this one. – SMA Nov 06 '14 at 17:44
0

to compile this sources, you have to go into your src-directory. Look here for a detailed explanation.

Community
  • 1
  • 1
Turing85
  • 18,217
  • 7
  • 33
  • 58