Old school Java programs without editor
I never thought I will write this. Computer programs are magic when there are abstractions on abstractions like my IntelliJ editor for Java apps. They give you a green play button to run your application, but this is making me feel unconfident about program I run. So I imagined what would it look like if we don’t have these feature loaded editors.
Let’s try to compile and launch two different programs with and without using package.
1. Simple program without packages
public class App {
public static void main(String[] args) {
System.out.println("Hello App!");
}
}
Compile
$ javac App.java
Launch
$ java App
Hello App!
2. App.java in a package
package mylibrary.learning;public class App {
public static void main(String[] args) {
System.out.println("Hello App!");
}
}
Compile
$ javac App.java
Launch (Failed)
$ java App
Error: Could not find or load main class App
Caused by: java.lang.NoClassDefFoundError: mylibrary/learning/App (wrong name: App
It didn’t make sense to me at first because I can see the App.class
file in the directory but it’s not running :( . After scratching and searching, I learned that the App.clas
file has to be generated in a directory so that the class loader can find the App.class in from path mentioned in package statement.
Compile attempt #2
$ javac App.java -d .
If you check the current working directory, you will now find that the java compiler generated the following directory and placed App.class in the path mentioned in your package statement.
$ tree
.
├── App.java
└── mylibrary
└── learning
└── App.class
Launch attempt #2
We will now have to launch with the full path of the package followed by app name.
$ java mylibrary.learning.App
Hello App!
Quick takeaway:
- Java compiler knows what directory need to be generated and place which files in what directory. Use
-d
option while compiling - Java launcher program need to know the location of the class to load and run your program. Use full package name followed by your App name.
I hope to cover more in the future without using editor.