Pages

Friday, September 9, 2016

Hello World (Java)

Creating and running your first Hello World program in Java, a programming language originally developed by James Gosling at Sun Microsystems, isn't terribly difficult. But there are several pieces to the puzzle that you need to understand:
  1. Although not required by The Java Language Specification, Java programs are typically stored in files with a .java filename extension, which may be created and maintained using any text editor.
  2. Once the source code for a Java program is ready to be processed, a Java compiler may be used to convert source code stored in .java files into Java bytecode stored in files with a .class filename extension.
  3. Then an interpreter can be used to interpret the .class files. A Java compiler (e.g. javac.exe) and interpreter (e.g. java.exe) come with freely available Java Development Kits (JDKs), such as the JDKs supplied by Oracle Corporation. (Oracle Corporation acquired Sun Microsystems in 2010.)
Portable bytecode produced by a Java compiler is supposed to conform to the Java Virtual Machine Specification (JVMS). Therefore, it should, in theory at least, be possible to move code compiled on one system to another system and run it without having to recompile the original source code. (Whether this always works perfectly in practice depends on how perfectly various relevant parties have done their jobs!) This important feature of Java programs was designed deliberately and has significant implications:
  • On the one hand, developers of Java programs don't necessarily have to maintain more than one compiled version of a given version of source code when deploying compiled code to computers with different instruction set architectures (ISAs), such as Advanced RISC Machine (ARM) vs. x86 computers.
  • On the other hand, interpreted bytecode can't run as fast as source code written in a programming language, such as C, that has been compiled into the native machine language of a particular computer's ISA. A Java program might also be more likely to consume more system resources when it runs than an equivalent program written in a language like C.
The value of portable bytecode and the importance of the performance of a Java program or the resource requirements of such a program are potentially debatable matters that really depend on the situation and therefore may be easier to consider given some context. In any event, as long as you're coding in Java, some things just are what they are, so say your favorite version of the Serenity Prayer if you need to and let it go.

In a nutshell: to write and run our first Hello World program in Java, we'll need a text editor, a Java compiler, a Java interpreter, and a mechanism for invoking the compiler and interpreter. EasyPeasy, Japanesey. Right? Let's find out! . . .

A Text Editor

The character encoding of our source code files can affect which command line options need to be supplied when compiling a Java program. Therefore, one of the first gotchya's (a gotchya is a potential problem or source of trouble) that we need to keep an eye out for involves the character encoding options that may or may not be provided (more or less obviously) by the text editor we're using. For example, when using Notepad's Save As feature, you can observe or change the encoding of a file:


Notepad++ is a freely available, relatively simple text editor that also allows you to observe and manage the character encoding of a file. If the editor you're using does provide this capability, then you may need to make use of a tool like Notepad or Notepad++, at least temporarily, in the event you encounter encoding/compiling issues.

Java Development Kit (JDK)

A version of a JDK may or may not already be installed on your computer. On computers running a recent version of the Microsoft Windows operating system (which I'll henceforth assume you are using for the sake of this discussion), a JDK might be found in the directory 'c:\Program Files'. Look for a folder named 'Java' in this directory. If you can't find the folder 'c:\Program Files\Java' on your computer, then a JDK might not be installed yet; in that case, you might want to download the most recent JDK from Oracle and install it if you have permission to do so on the computer you are using.

Assuming a JDK is installed and the version of the JDK is, say 1.7.0, then you will likely find the Java compiler (javac.exe) and the Java interpreter (java.exe) in the directory 'c:\Program Files\Java\jdk1.7.0\bin'. This directory may or may not be included in the PATH system variable. If it is not, then you need to somehow tell the computer's operating system exactly where the program (javac.exe, java.exe, etc.) is located when invoking the program from a command line. We'll discuss this some more shortly.

Running a Java Compiler or Interpreter from a Command Line

On a Windows system there are several different ways to start a program. For example, if you want to run Notepad, you could use the Windows Explorer program, navigate to the directory 'c:\Windows\System32', and double click on the file named notepad.exe. Alternatively, you could use the program PowerShell and type 'c:\Windows\System32\notepad.exe' at the command prompt. Note that typing the file extension '.exe' might be optional.

But what if you want to simultaneously start Notepad and open a particular file in the executing instance of Notepad that you just started? If you are are starting Notepad from the command line, then you can do this by passing the name of the file you want to open as the value of the first command line argument, like this:
PS C:\Users\jspurgeon> C:\Windows\System32\notepad.exe '\\jupiter\vol1\Users\jspurgeon\My Documents\SomeFile.txt'
Note the use of opening and closing single quotes around the complete pathname of the file to be opened. Why might quotes be necessary in this particular case? Are quotes always necessary? What would happen if the quotes were omitted in the example above? It's very important that you understand the answers to these questions as they related to the general concepts of arguments and parameters. (What's the difference between an argument and a parameter? You should learn the difference if you don't already know it!)

The ability to pass argument values to a command when we execute the command is a very useful and sometimes essential capability. When we compile a Java program (a file containing source code and ending in with the '.java' filename extension), we need to be able to simultaneously start the compiler (javac.exe) and tell the compiler what file contains the source code to be compiled. We might even need to tell the compiler what type of encoding was used when the source code file was last saved!

Useful PowerShell Commands and "Tricks"

If you are using Windows PowerShell to compile and execute Java programs, there are several basic commands or command aliases that you should become very familiar with. In very rough, subjective priority order, this include (but are not limited to):

  • alias
  • help
  • pwd
  • dir (or 'ls' if you prefer)
  • cd
When you start to get tired of typing the same thing over and over again, you will want to master the arts of:
  • using the tab key to "auto-complete" pathnames that you are trying to type or discover
  • using the up and down arrow keys to scroll through previously typed commands
  • using the set-alias command to create or reset aliases (instead of having to type the complete pathname of the Java compiler and interpreter, for example)
  • using the export-alias and import-alias commands to save and restore aliases (instead of typing the same set-alias commands day after day)
The need to employ some of these tricks could be possibly avoided through the use of other tricks, such as permanently modifying the PATH variable instead of using the export- and import-alias commands. For better or worse, you might not have the access needed to do certain things on certain computers, so it's important that you learn how to make do with what you've got the best of your ability.

Are we there yet?

Almost! Now that we've covered the basic tools and techniques needed to write your first Java program, it's time to tell you how to do it—in Java!

With almost no further ado, put the following code or something like it (it is your first program) in a file named HelloWorld.java:
public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.print("Goodnight, Moon");
    }
}
After saving the file containing your source code, try to compile it using the javac.exe program. If the program compiles successfully, then the javac program should produce a new file called HelloWorld.class. Now try to execute your program using the java.exe interpreter. Can you do it?

Yes you can!