Sign up for a free trial of our self-paced courses.

Java Tutorial

Java Introduction

In this lesson, you will learn the tools to get you started within the Java Runtime Environment.

Lesson Goals

  • Learn about the Java Runtime Environment and how a Java program is created, compiled, and run.
  • Learn how to download, install, and set up the Java Development Kit Standard Edition.
  • Learn how to create a simple Java program.

Conventions in These Notes

Code is listed in a monospace font, both for code examples and for Java keywords mentioned in the text.

The standard Java convention for names is used:

  • Class names are listed with an initial uppercase letter.
  • Variable and function names are listed with an initial lowercase letter.
  • The first letters of inner words are capitalized (e.g., maxValue).

For syntax definitions:

  • Terms you must use as is are listed in normal monospace type.
  • Terms that you must substitute for, either one of a set of allowable values, or a name of your own, or code, listed in italics.
  • The following generic terms are used - you must substitute an appropriate term.
Generic Terms Substitution Options
access An access word from: public, protected, private, or it can be omitted
modifiers one or more terms that modify a declaration; these include the access terms as well as terms like: static, transient, or volatile
dataType A data type word; this can be a primitive, such as int, or the name of a class, such as Object; variants of this include: returnType and paramType
variableName The name of a variable; variants on this include paramName and functionName
ClassName The name of a class; there will be variants of this used for different types of examples, such as: BaseClassName, DerivedClassName, InterfaceName, and ExceptionClassName
code Executable code goes here
. . . In an example, omitted code not related to the topic

The Java Environment - Overview

A Java program is run differently than a traditional executable program.

Traditional programs are invoked through the operating system.

  • They occupy their own memory space.
  • They are tracked as an individual process by the OS.

Traditional programs are compiled from source code into a machine and OS-specific binary executable file.

  • To run the program in different environments, the source code would be compiled for that specific target environment.

When you run a Java program, the OS is actually running the Java Runtime Engine, or JRE, as an executable program; it processes your compiled code through the Java Virtual Machine (usually referred to as the JVM).

A Java source code file is compiled into a bytecode file.

  • You can consider bytecode as a sort of generic machine language.
  • The compiled bytecode is read by the JVM as a data file.
  • The JVM interprets the bytecode at runtime, performing a final mapping of bytecode to machine language for whatever platform it is running on.
  • Thus, Java programs are portable - they can be written in any environment, compiled in any environment, and run in any environment (as long as a JVM is available for that environment).
  • The JVM manages its own memory area and allocates it to your program as necessary.
  • Although this involves more steps at runtime, Java is still very efficient, much more so than completely interpreted languages like JavaScript, since the time-consuming parsing of the source code is done in advance.

Writing a Java Program

Java source code is written in plain text, using a text editor.

  • This could range from a plain text editor like Notepad, to a programmers' editor such as TextPad, EditPlus, or Crimson Editor, to a complex integrated development environment (IDE) like NetBeans, Eclipse, or JDeveloper.
  • The source code file should have a .java extension.

The javac compiler is then used to compile the source code into bytecode.

javac MyClass.java
  • The bytecode is stored in a file with an extension .class
  • Bytecode is universal - one bytecode file will run on any supported platform.

You then run the java runtime engine, which will then interpret the bytecode to execute the program.

java MyClass
  • The executable program you are running is: java.
  • The class name tells the JVM what class to load and run the main method for.
  • You must have a JVM made specifically for your hardware/OS platform.JVM Diagram

Obtaining the Java Environment

You can download the SDK (software development kit) including the compiler and runtime engine from Oracle at: http://www.oracle.com/technetwork/java/javase/downloads/index.html . Look for the download of JavaSE 1.6.0.10 (or the latest release of that version).

You can also download the API documentation and even the source code. Note that:

  • The documentation lists all the standard classes in the API, with their data fields and methods, as well as other information necessary to use the class. You will find this documentation helpful as you work through some of the exercises.
  • You can view the docs online, but it is worth downloading it so that you don't have to be connected to the internet to use it.

Setting up Your Java Environment

Java programs are compiled and run from an operating system prompt, unless you have installed an IDE that will do this for you directly. If you create an applet, this would run inside a web page in a browser.

After you have installed the JDK, you will need to set at least one environment variable in order to be able to compile and run Java programs.

For more complex projects that pull together elements from different sources, you must set an additional environment variable or two. Note that:

  • a PATH environment variable enables the operating system to find the JDK executables when your working directory is not the JDK's binary directory.
  • CLASSPATH is Java's analog to PATH, the compiler and JVM use it to locate Java classes.
    • Often you will not need to set this, since the default setting is to use the JDK's library jar file and the current working directory.
    • But, if you have additional Java classes located in another directory (a third-party library, perhaps), you will need to create a classpath that includes not only that library, but the current working directory as well (the current directory is represented as a dot).
  • Many IDE's and servers expect to find a JAVA_HOME environment variable.
    • This would be the JDK directory (the one that contains bin and lib).
    • The PATH is then set from JAVA_HOME plus \bin.
    • This makes it easy to upgrade your JDK, since there is only one entry you will need to change.

Best Practice: Setting PATH from JAVA_HOME

The procedure to permanently set the environment variables varies slightly from one version of Windows to another; the following will work in many, including Windows XP. The process for Vista is similar, but slightly different:

  1. Right-click on My Computer.
  2. Choose Properties.
  3. Select the Advanced tab.
  4. Click the Environment Variables button at the bottom.
  5. Check both the User and System variable lists to see if JAVA_HOME or PATH already exist.
  6. If JAVA_HOME exists, check to see that it matches your most recent JDK (or the one you wish to use).
    1. It is probably better to set this as a System variable.
    2. If it exists, click Edit, if not, click Add.
    3. For the variable name, enter JAVA_HOME.
    4. For the value, enter your JDK directory, such as C:\Program Files\Java\jdk1.5.0_14.
      • Note that the space in the name can sometimes cause problems.
      • One solution is to put quote marks around the entry, as in "C:\Program Files\Java\jdk1.5.0_14".
      • An even better solution would be to use the 8-character form of the directory name, such as C:\Progra~1\Java\jdk1.5.0_14 (you can check if this works in your system by typing it into the address bar of a My Computer window).
    Adding A JAVA_HOME Environment Variable
  7. for PATH, again select either Add or Edit.
    • You could do this either as a User variable or a System variable.
    • If there isn't already a JDK bin directory mentioned in the PATH, it will work as a User variable.
    • If there is already a JDK mentioned, you would want to ensure that this new entry preceded the existing entry, so you would edit that variable.
    • Note that if the existing entry was created using JAVA_HOME, then we are already set correctly .
    • If you "prepend" an entry to PATH , it will be found first, and therefore supercede any other directory - if you append to path, your directory won't be found if an earlier entry JDK entry exists (the following image shows a prepend).
    • Also note that System variables precede User variables, so they will be found first.
    Setting a PATH Environment Variable

Setting Environment Variables from a Command Prompt

If you set the variables from a command prompt, they will only hold for that session, but you could create a batch file that you could run each time you open a command prompt window.

To set the PATH from a command prompt or batch file:

set PATH=C:\Progra~1\Java\jdk1.6.0_10\bin;%PATH%

If you need to set the CLASSPATH:

set CLASSPATH=.;%CLASSPATH%
  • Early versions of the JDK required you to include the JDK's lib directory in the CLASSPATH; this is no longer necessary .
  • Note that UNIX environments use $PATH and $CLASSPATH instead of %PATH% and %CLASSPATH%, and that the path element separator is a colon instead of a semicolon.

Creating a Class that Can Run as a Program

The main() Method

In order to run as a program, a class must contain a method named main, with a particular argument list. This is similar to the C and C++ languages.

The definition goes inside your class definition, and looks like:

public static void main(String[] args) {
	(code goes here)
}
  • It must be public, because it will be called from outside your class (by the JVM).
  • The static keyword defines an element (could be data or functional) that will exist regardless of whether an object of a class has been instantiated. In other words, declaring main as static allows the JVM to call the method and therefore execute the program. That doesn't mean that an object of that class cannot be instantiated, it is just not required.
  • The String[] args parameter list states that there will be an array of String objects given to the method - these are the command line arguments.
  • To run the program, use the following from the command line if you are running it from the console:
    java ClassName
    For example, if we had an executable class called Hello, in a file called Hello.java that compiled to Hello.class, you could run it with:
    java Hello

Useful Stuff Necessary to Go Further

System.out.println()

In order to see something happen, we need to be able to print to the screen.

There is a System class that is automatically available when your program runs (everything in it is static).

  • it contains, among other things, input and output streams that match stdin, stdout, and stderr (standard output, standard input, and standard error).

System.out is a static reference to the standard output stream.

As an object, System.out contains a println(String) method that accepts a String object, and prints that text to the screen, ending with a newline (linefeed).

  • There is also a print(String) method that does not place a newline at the end.

You can print a String directly, or you can build one from pieces.

  • It is worth noting that a String will automatically be created from a quote-delimited series of characters.
  • Values can be appended to a String by using the + sign; if one item is a String or quote-delimited series of characters, then the rest can be any other type of data.

Using the Java Documentation

Sun provides extensive documentation of the API (library of available classes). The documentation for version 6 is available at http://download.oracle.com/javase/6/docs/api/

If you view that page, you will see a list of classes on the left as hyperlinks. Clicking a class name will bring up the documentation for that class on the right.

For example, click on System. The page on the right contains documentation on the elements of the class, categorized by type of element (there are links at the top for fields, constructors, methods, etc.).

Try to locate the out field - note that the field types, parameter types and return types are hyperlinked, and that out is a PrintStream. Click that, and find the println methods in a table with short descriptions. Select one to see the detailed description. The multiple versions are an example of method overloading, which we will cover in an upcoming lesson. Another lesson will cover documenting your own classes with the same tool that created this documentation.

In this lesson, you have learned: