1-1 Getting Started

Life Before Java

Computer science is about solving problems through the design and analysis of algorithms. Like a cooking recipe, an algorithm is a series of tasks performed in a particular order to solve a problem. Two of the most common types of problems solved by algorithms involve searching and sorting of data – ever heard of Google?

Once an algorithm has been designed, it can be coded using a variety of programming languages such as Python, C/C++, or Java. Like human languages, programming languages share a lot of similarities but often have keyword, punctuation, and style differences that make them unique.

A program is simply a text file (editable with any text editor) that contains human-readable instructions that tell a computer what to do. To run (or “execute”) a program one needs to translate it into machine language (binary 0’s and 1’s) that is understood by the Central Processing Unit (CPU).

1-1-Compiling1

This translation from a human-readable form to machine-executable binary instructions is done by an application called a compiler (or interpreter, depending on the language). Every family of CPU (e.g., Intel and Apple Ax-series) understands its unique machine language. For this reason, you cannot directly run your favourite iPhone app on your PC.

Java’s Greatest Strength

The limitation of the compiled approach above is Java’s greatest strength. Java was designed from the beginning (1995) as a “write-once, run-anywhere” language.  It accomplishes this by adding an extra translation step in the execution process.

1-1-Compiling2

Here, a Java program (a text file with a .java extension) is compiled into an intermediate form called bytecode (a binary file with a .class extension). Like machine language, bytecode is binary (0’s and 1’s) but is in a more general form that cannot run directly on any particular CPU.

To execute the bytecode (.class file) one has to translate the generic bytecode into machine language for a particular CPU family. This happens using another application called a Java Virtual Machine (JVM). The result of all this is that a .class file can be run on any computer that has a JVM installed without having to be recompiled and without having to distribute your original Java source code – this benefit is called platform independence. These steps might seem complicated but they only take a few button clicks in a program editor.

One last thing I’ll mention here: Most programming languages are based on others that came before. In the case of Java, it borrows heavily from C and C++. The nice thing about this is that if you already know one of these languages then learning Java is much easier, and vice versa.

JDK vs. JRE

1-1-JDKvsJREThe Java Runtime Environment (JRE) includes the JVM and important Java class libraries. The JRE is necessary if you simply want to run a Java application as a user. Most operating systems come with the JRE installed.

To program our Java applications we will need the Java Development Kit (JDK). The JDK includes everything that the JRE provides plus the Java compiler (to produce .class files).

Oracle maintains and provides the JRE and JDK for free on their Web site.

Tools You’ll Need

The first tool you’ll need to install is the Java Development Kit. As of this writing, JDK version 1.8 (update 181) is the current stable release. Oracle puts out fairly frequent updates, usually with minor security, performance, and bug fixes. You are welcome to use a more recent version of the JDK, all of my examples should work just fine. Oracle has been pretty good about maintaining backward compatibility.

The second thing you’ll need to install is an editor where we can edit, compile, and run our Java programs – also known as an Integrated Development Environment (IDE). There are many options out there! As a beginner, I am going to recommend that you use a free IDE called Dr Java. Dr Java was designed with students in mind and was written in Java itself.

Sometimes students ask why I don’t recommend more “professional” grade tools like IntelliJ, NetBeans, or Eclipse. The analogy I give is learning to be a carpenter – when you start you need to master simple hand tools to build your skills before moving on to power tools. In particular, these professional-grade IDEs include a feature called “code completion” which tries to predict what keyword you might need to type next in your program. As a learner, this will hamper your mastery of Java syntax. That said, all of my examples will work regardless of the IDE you choose.

The installation processes for the tools above are pretty straightforward and you can find lots of help online if you need it so I will not provide instructions here.

The Java Bible

Apart from my notes, I recommend that you bookmark the Java Application Programming Interface (API). This is a free, authoritative reference for all of the class libraries included with the JDK. As Java programmers, this will be our “Bible” and official reference. I will include links to the Java API throughout my notes.

Hello Java!

Let’s write our first Java program.

Wow, 14 lines! There’s a lot to say about this program.

Every Java program includes instructions that get compiled into bytecode and comments that are written by the programmer to help others read and understand the program.

Lines 1 to 7 are called a multi-line comment. A multi-line comment starts with a /* and ends with a */, the *’s on lines 2 through 6 are optional (but look nice). It’s good practice to include a multi-line comment at the top of every Java source file you create that includes your name, the date the code was written, and a brief description of it.

Line 10 is a single-line comment. A single line comment can appear on a line by itself or at the end of a line of code. Everything following the // to the end of the line is ignored by the Java compiler. Single line comments should be used to explain the code immediately following it.

Java code is organized into classes, methods, and blocks. Curly braces denote a block of code { .. } and identify the start and end of classes, methods, and control structures that we’ll discuss later. Although the Java compiler does not care about indentation it is very important to indent for human readability. Every time you start a block of code, all code following the opening { until the closing } should be indented 4 spaces. To automatically re-indent an entire program in Dr Java: Select All (Control-A), and press the tab key.

The statement on line 12 is the heart of this program. You can think of a statement in Java-like a complete sentence in English except they are always terminated with a semi-colon (;) instead of a period (.). When the program is executed the string “Hello Java!” will be displayed on a line by itself. A string in Java is a sequence of characters enclosed with double quotation marks ().

The syntax of a programming language is a precise set of rules that defines how the keywords and symbols can be combined to create a properly structured program. Another way to think about this is like spelling and grammar in English. While the Java compiler ignores comments (even if you misspell something), if you mistype code it will cause a compiler error called a syntax error. A program with syntax errors cannot be executed until they have been fixed. Most IDEs automatically colour highlight the syntax for improved readability.

A method is a named block of code that performs a task — here the method name is main(). In Java, every program must have one method called main() which gets executed first by the JVM. Apart from main() most non-trivial programs will have many other methods.

A class is a collection of methods. It’s critical that the name of your class (Hello in this case) and its code filename (Hello.java) match, including case. We’ll get into the nuts and bolts of classes and methods in much great detail later. I would recommend using the code above as a starting template for all of your Java programs in this course, simply update the header comment and insert your custom code at line 12.

Some Humble Advice

At the end of the notes for each topic are exercises for you to apply what you’ve learned and expand your knowledge. If you’re serious about learning Java you need to at least attempt every problem. Just like mastering an instrument, you can’t learn to program by only reading about it, you must practice.

You Try!

Cut and paste the “Hello Java!” code above into Dr Java and save the source as Hello.java. To run the program is a two-step process. First, click the CompileButton button in Dr Java; this will generate a bytecode file called Hello.class in the same directory as your Hello.java file. This bytecode file can be shared and run on any computer with a JVM installed without having to provide your Hello.java source file or recompile the code. To execute the bytecode click the RunButtom button. This will execute the program using the JVM installed on your computer. The output is what you might expect:

Hello Java!

If this simple program does not compile and run, then it’s likely that your JDK was not installed correctly or Dr Java is not configured properly.

Here are some other ways to expand your Java knowledge:

    1. A very important part of the learning process is recording and reflecting on what you are learning!  Create a new Google doc named “Learning Journal“. Be sure to add today’s date and the title “1-1 Getting Started” at the top of your entry. Carefully read the notes above and answer the following questions in your Learning Journal:
      1. The primary benefit of writing Java code is that it is platform-independent. Using Google, research 2-3 other strengths of Java.
      2. No programming language is perfect.  What is Java’s greatest weakness?
      3. Like any field, Computer Science has a lot of important terminology.  Create a glossary of terms that are unfamiliar to you based on today’s notes.
    2. The best way to master a programming language is to experiment! Try making changes to the code above using Dr Java, and recompile; for example, edit the comments, change the output message, and try causing syntax errors by changing or removing a Java keyword or symbol to see what happens. What 3 useful pieces of information are given in a compiler error message?
    3. The following program runs but is very hard to read. Properly indent and comment the code in Dr Java.
    4. Install the JDK (choose the x64 Installer for Windows) and Dr Java on your home computer. Test your installation using the program you just worked on.