Compiling and Running
This section is used for you to use Java at home and understand the basics of how things are done.
After creating a simple application that prints something to the screen, you need to compile your code an run it.
It shouldn't really matter if you use Linux, Mac or Windows. You need to have a console and you need to have the following commands available in order to compile and run Java.
- java (or java.exe)
- javac (or javac.exe)
In order for those to be available you must download and install JDK (Java Development Kit).
If we take the code from the previous lesson and put it in a file called MyFirstClass.java, in order to compile it we need to run:
javac MyFirstClass.java
This is create a file called MyFirstClass.class that holds the compiled java code.
To run it, we need to run java with the name of the class as the argument (Not the file!)
Wrong
java MyFirstClass.class
Right!
java MyFirstClass
Compiling with Java 11
If you are running Java 11, there is a new feature that allows single source file execution. Prior to Java 11, to run your code you have to first compile it, then you can run it. Here's an example:
javac MyFirstClass.java
java MyFirstClass
Since Java 11, you can still do javac + java , or you can run java by itself to compile and auto-run your code. Note that no .class file will be generated. Here's an example:
java MyFirstClass.java
Arguments
The main methods get an array of strings as an argument, these are the command line arguments you may pass to your program.
Every array in java holds a variable called length that says how many elements are within that array.
We can go over the arguments with a simple for
public class Arguments {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
And o run it with arguments:
javac Arguments.java
java Arguments arg0 arg1 arg2
Exercise
Create a program that prints the arguments of our program. Write one argument per line.