MENU
The instructor was extremely organized and knowledgeable about Microsoft Project, and her class has enabled me...More Testimonials »

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 an Integrated Development Environment

Duration: 30 to 40 minutes.

Integrated Development Environments, or IDEs, can greatly facilitate the task of creating applications. Mid-level code editors, such as Crimson Editor, TextPad, or Edit-Plus, provide syntax highlighting, automatic indenting, parentheses and curly-brace matching, and may have tools to compile and execute programs.

High-end environments, such as Eclipse, NetBeans, or JDeveloper, offer many additional features, such as project management, automatic deployment for web applications, code refactoring, code assist, etc. But, these additional capabilities come with the price of additional complexity in the environment, particularly because they force you to create projects for even the simplest applications.

To use the class files in these environments, we must first have a workspace, which is a collection of projects. Workspaces have various configuration settings that will cut across all projects within all projects they contain, such as which version of Java is in use, any added libraries, etc. (a project is usually one application).

Both Eclipse and NetBeans use the workspace concept, but you can start with any empty directory - the IDE will add its own special files as you create projects.

In the Windows Explorer, navigate to your ClassFiles directory. If it does not contain a Workspace subdirectory, create it.

To use Eclipse with the class files, you can direct it to the workspace (ClassFiles/Workspace) when it opens (if it asks), or use File, Switch Workspace if Eclipse is already running. Each chapter's demo folder should be treated as a project, as should each Solution folder.

One limitation of these environments is that no project can contain the same Java class twice, so our progressive versions of the Payroll application solution require their own individual project. Also, due to the way Java's package structures work, each Demo folder must be a separate project, as with each subdirectory under Solutions.

To use the Exercises folder as an Eclipse project:

  1. Select File > New > Java Project
  2. Enter Exercises for the project name
  3. Click Finished
  4. In the Package Explorer pane, right-click on the src folder under the Exercises folder
  5. Select Import from the context menu
  6. Select File System from the tree in the Select dialog box
  7. Click Next
  8. Using the Browse button, navigate to and select c:/ClassFiles/Exercises. (Note: this path might be different depending on where you extracted the class zip file)
  9. Make sure the Exercises check box is selected and click Finished
  10. Expand the src folder in the Package Explorer and then expand the default package folder
  11. Right-click on the file Welcome.java
  12. From the context menu select Run As... > Java Application
  13. Note the output is displayed in the Console at the bottom of the Eclipse workbench

As we encounter each chapter, we can create a project using the Demos directory for that chapter the same way we just created the Exercises project..

To create a Java class within a project, use File, New , and then Class if that is available, or Other... and then Class . Provide a name and then OK .

In general, with the several applications that we will build upon progressively (Game and Payroll), you can continue to work with the same files, and add to them as we cover additional topics. If you want to check the solutions, you can either open those files in a separate editor, like Notepad, or create a project for that Solutions subdirectory. If you wish to save a particular stage of the application for future reference, you can just make a copy of the Exercises directory.

The examples and instructions provided use a more basic text editor (Chrimson) and an OS console for clarity. You are free to choose which tool to use. If Eclipse becomes a problem, move to a simple editor. The focus of this course is on the Java Programming Language and not a particular tool.

First Java Program

Duration: 5 to 15 minutes.
  1. Create a file called Hello.java.
  2. Enter the following code:
    public class Hello {
    	public static void main(String[] args) {
    		System.out.println("Hello World");
    	}
    }
  3. Save the file.
  4. In a command prompt window, change to the directory where Hello.java is stored and type the following:
    javac Hello.java
    1. A prompt on the next line without any error messages indicates success.
  5. Type:
    java Hello
  6. Press Enter.
    1. You should see the message Hello World print in the window.
public class Hello
  • All Java code must be within a class definition.
  • A class defines a type of object.
  • A public class can be accessed by any other class.
  • A public class must be in its own file, whose name is the name of the class, plus a dot and an file extension of java (e.g., Hello.java ).
    {
    	. . .
    }
  • Curly braces denote a block of code (the code inside the braces).
  • Code within braces usually belongs to whatever immediately precedes them.
    public static void main(String[] args) {
  • Words followed by parentheses denote a function.
  • To be executable by itself, a class must have a function defined in this fashion; the name main means that execution will start with the first step of this function, and will end when the last step is done.
  • It is public because it needs to be executed by other Java objects (the JVM itself is a running Java program, and it launches your program and calls its main function).
  • It is static because it needs to exist even before one of these objects has been created.
  • It does not return an answer when it is done; the absence of data is called void.
  • The String[] args represents the additional data that might have been entered on the command line.
System.out.println("Hello World!");
  • System is an class within the JVM that represents system resources.
  • It contains an object called out, which represents output to the screen (what many environments call standard out).
  • Note that an object's ownership of an element is denoted by using the name of the object, a dot, and then the name of the element.
  • out in turn contains a function, println, that prints a line onto the screen (and appends a newline at the end).
  • A function call is denoted by the function name followed by parentheses; any information inside the parentheses is used as input to the function (called arguments or parameters to the function).
  • The argument passed to println() is the string of text "Hello World!".
  • Note that the statement ends in a semicolon (as all do Java statements).

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:

Java Basics →

Client Success
  1. Compare Us
  2. Client List
  3. Testimonials
Join The Team
  1. Learn how you can become a Webucator Trainer
  2. Career Opportunities
Locations
© Webucator, Inc. All rights reserved. |Toll Free: 1-877-932-8228Toll Free: 1-877-932-8228 |Outside the USA: 315-849-2724|Fax: 315-849-2723