简体   繁体   中英

compiling and running packages of Java classes in command line?

I have a helloworld.java in this directory structure.

    bash: ls
    com
    bash: ls com/
    stack
    bash: ls com/stack/
    prog
    bash: ls com/stack/prog/helloworld.java

To compile I did, javac com/stack/prog/helloworld.java but for running it I did, java com.stack.prog/helloworld

Why is it for compiling, the / are needed. but for running it . are needed.

When you compile your *.java file using CMD or Terminal you need to give its exact path to that file , and separate the directory structure in your path by using "\\" in Windows and "/" in Unix , So, when you compile you give the path, that's why slashes are used. And once the file is compiled ie *.class is made, to run the code you need to run it by specifying its package structure . And their has to be a difference in file systems path directory structure and the package structure of java. Java makers must have used dot(.) instead of slash to bring the difference in notice. It is same as you write the import statement in your code (in which packages are separated by the dot(.) and not slashes). This is because by slash it means you are entering in a simple filesystem directory and by dot(.) it means you are entering in a certain package to access a particular Java Class defined in that package.

When you are compiling you are pointing to a source file by its path (that uses slashes to separate folder names). When running you are using a java namespace (also called a package+Class name) which use dots. In Java the class name must exactly match the file name. There isn't the same requirement for packages and folders though it's a good idea for keeping code organized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM