-2

I following this post and this post to build an java app.

Here is all the content in my company/HelloWorld.java

package company;

public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello, World");
   }
}

Classically, running a java program needs 2 steps:

  1. javac the file, for example javac company/HelloWorld.java
  2. java the class file, for example java company.HelloWorld

which gave me "Hello, World", as expected.

It seems java -cp could do the 2 steps above in a batch, although it seems that my env does not recognize this command

java -cp company.HelloWorld

and outputs

Usage: java [-options] class [args...]

this is another version, according to @hayrettinm's answer.

package company.HelloWorld;

didn't work either. what am I missing?

Why do I thought java -cp could do compile and run? this post gives this example

PS C:\Lecture_java\Lecture001\Hello> & 'C:\Users\ubuntu\.vscode\extensions\vscjava.vscode-java-debug-0.23.0\scripts\launcher.bat' 'C:\Program Files\Java\jdk-13.0.1\bin\java' '-Dfile.encoding=UTF-8' '-cp' 'C:\Lecture_java\Lecture001\Hello\bin' 'app.App'

after the experiment, I guess java -cp company.HelloWorld could not compile and run, it just run an java application. Could someone give a double confirmation.

JJJohn
  • 915
  • 8
  • 26
  • `-cp` expects a list of directories and jar file where java will load classes from. Exampe: `java -cp .:some/directory:somelibrary.jar com.mycompany.myproject.Main` – JB Nizet Dec 07 '19 at 00:12
  • @JBNizet thanks for your comments. regarding my particular case, what should I put in the "some/directory:somelibrary.jar" placeholder? – JJJohn Dec 07 '19 at 00:32
  • Nothing since you have no additional classes for the hello world. – Delfic Aug 09 '21 at 12:36

1 Answers1

0

java -cp doesn't do what you write.

javac executable is the compiler that compiles your class to bytecode, java executable is basically the runtime that understands the bytecode you have compiled.

Besides,

If you want to use package com.company.HelloWorld you have to write package decleration like this in your class:

package com.company.HelloWorld;
hayrettinm
  • 72
  • 5
  • thanks for your answer. I've updated my post. didn't work either. – JJJohn Dec 07 '19 at 00:32
  • @fuDL Ok, lets get it clear. You cannot compile & run your class in one go. You have to use javac to compile your code and java to run your program. So you have to run like you first mentioned : `javac company/HelloWorld.java` and `java company.HelloWorld` Regarding -cp flag, [here](https://stackoverflow.com/questions/11922681/differences-between-java-cp-and-java-jar) is a good discussion I believe you can get some insight. For your basic HelloWorld scenario, if you use other classes/jars which are out of your current running directory you can use -cp flag. – hayrettinm Dec 07 '19 at 21:30