Search code examples
javacmdclasspathscjp

How to run java class command line?


I have the following test question:

Given:

1. package com.company.application;
2.
3. public class MainClass {
4. public static void main(String[] args) {}
5. }

And MainClass exists in the /apps/com/company/application directory. Assume the CLASSPATH environment variable is set to "." (current directory).Which two java commands entered at the command line will run MainClass? (Choose two.)

A. java MainClass if run from the /apps directory
B. java com.company.application.MainClass if run from the /apps directory
C. java -classpath /apps com.company.application.MainClass if run from any directory
D. java -classpath . MainClass if run from the /apps/com/company/application directory
E. java -classpath /apps/com/company/application:. MainClass if run from the /apps directory
F. java com.company.application.MainClass if run from the /apps/com/company/application directory

I think the correct are D and E but the are B and C and I am wondering why?


Solution

  • You should execute a class using its full name. The full name of a class consists of:

    <package location> + <simple name of class>
    

    With this in mind, MainClass full name is com.company.application.MainClass.

    Java can locate this class from the directory that contains the top directory in the package tree. From the example, the root directory is /apps:

    apps <-- root
    + com <-- here the package starts
      + company
        + application
          - MainClass.class
    

    So this root directory should be in the classpath in order that Java program (the JVM) can access to the compiled classes and the entry point of the app.


    From the question:

    Assume the CLASSPATH environment variable is set to "." (current directory).

    Option B states:

    B. java com.company.application.MainClass if run from the /apps directory

    Since you're in /apps directory and the current directory is the CLASSPATH, so Java can locate the designated class to execute.

    Option C states:

    C. java -classpath /apps com.company.application.MainClass if run from any directory

    In this case, you're setting /apps as CLASSPATH, so Java can locate the designated class to execute.

    All the other options fails to accomplish the explanation above.