Search code examples
javacommand-linecpscjp

Execute java compiled class command line


I have the following question. Given a correctly compiled class whose source code is:

1. package com.sun.sjcp;
2.
3. public class Commander {
4.     public static void main(String[] args) {
5.         // more code here
6.     }
7. }

Assume that the class file is located in /foo/com/sun/sjcp/, the current directory is /foo/, and that the classpath contains "." (current directory). Which command line correctly runs Commander?

A. java Commander
B. java com.sun.sjcp.Commander
C. java com/sun/sjcp/Commander
D. java -cp com.sun.sjcp Commander
E. java -cp com/sun/sjcp Commander

Answer: B

A. We are in the root dir, so we can't see the file from /foo/com/sun/sjcp/ directly

B. is correct

C. I think is correct too ???

D. We are in /foo/com/sun/sjcp/ and there is only class file with package package com.sun.sjcp; so the compiler can't find it. If the file was without package declaration and was build in this dir then it will work if we try to run it in this way.

E. The same as D - does not work

The only answer given is B. Where am I making a mistake?


Solution

  • C is incorrect because "com/sun/sjcp/Commander" isn't a valid class name. Path to a file and class name are not the same things.

    (edited): It's appeared "that the jvm allows you to use a forward slash in place of a dot in the fully qualified name of the class to run" (but you must use only forward slashes). So it seems that C is also correct