Java programming: compiling and running

Following up yesterday’s post, the tutor offers basic instructions to compile and run a Java program.

I’ve never used a Java IDE; maybe I’ll try a few and write future posts about them. For now, my readers know that I use the command line.

Let’s imagine you’ve written a standalone Java class such as

class P0{
public static void main(String[] args){
System.out.println(“Congratulations from Java!”);
}
}

To succeed, the file needs to be saved with the .java file extension. Let’s imagine it’s saved P0.java in the folder java_demos. To compile it, you’d open the terminal, then enter that directory. Next, you’d key in

javac P0.java

If you get error messages, you’ll need to do some proofing. If the program compiles fine, you likely won’t get a message at all; rather, you’ll just see the command prompt appear on the next line.

Running the program can depend on your operating system.

From the Linux terminal, you can run the program thus:

java P0

However, from the Windows terminal, you might need to key in

java -cp . P0

In the case of yesterday’s post, there is a class that uses another. In that case, the compile command should indicate both files (the one containing the main() method, listed first):

javac MessagerDriver.java Messager.java

However, after a successful compile, the program can be run by calling only the first file:

(Linux)

java MessagerDriver

(Windows)

java -cp . MessagerDriver

Programs rarely compile and run the first try; usually, corrections need to be made because of missing parentheses, semicolons, or what have you. The compiler tries to tell what’s wrong, but in my experience, a missing bracket can lead to ten error messages as it tries to make sense of the code without it. Very often, one or two simple problems are all that’s wrong.

Good luck with your coding. I have so much to follow up from this post:)

Source:

Niemeyer, Patrick and Jonathan Knudsen. Learning Java. Sebastopol, CA: O’Reilly   Media, Inc, 2005.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply