facebook twitter
Webucator's Free Java Tutorial

Lesson: Java Introduction

Welcome to our free Java tutorial. This tutorial is based on Webucator's Introduction to Java Training course.

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

Don't worry if some (or all) of the terms in the table above don't make sense right now - we'll cover all of this material in detail as we move through the course.

The Java Environment - Overview

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

Traditional programs are invoked through the operating system (OS).

  • 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 programmer's 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. The following command, run from the command line (the "Command Prompt", also known as "cmd", on a Windows computer; "Terminal" on a Mac), would compile the source-code file MyClass.java into the bytecode file MyClass.class:

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. This command runs the compiled bytecode:

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, for free from oracle.com at: http://www.oracle.com/technetwork/java/javase/downloads/index.html. Look for the download of the latest release of Java SE. You want the Java Development Kit (JDK) download:

Oracle JDK download screenshot

From the next page, accept the license agreement and choose the JDK appropriate for your operating system. Windows users would select the last item:

Oracle JDK download screenshot - OS-specific

Run the installer, accepting the default directory locations and options.

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 (https://docs.oracle.com/javase/10/docs/api/overview-summary.html) 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.

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 instructions below will help you to create a JAVA_HOME environment variable and add a PATH entry from JAVA_HOME.

  1. First, find the full path of the directory in which the JDK was installed:
    • JDK installation path
    • The screenshot above shows the path after we accepted the default location when installing the JDK; in this example, the path is C:\Program Files\Java\jdk-10.0.2
  2. Search for Environment Variables (on an older PC, right-click on My Computer, choose Properties, select the Advanced tab):
    • Windows Environment Variables
  3. Check both the User and System variable lists to see if JAVA_HOME or PATH already exist.
  4. If JAVA_HOME exists, check to see that it matches the JDK path from the installation - in our example above, that would be the path C:\Program Files\Java\jdk-10.0.2
    1. If JAVA_HOME exists under System variables, click Edit, if not, click Add
    2. For Variable name, enter JAVA_HOME
    3. For Variable value, enter the JDK directory, such as C:\Program Files\Java\jdk-10.0.2:
    4. Windows - set JAVA_HOME environment variable
  5. Next, add an entry to the PATH to reference the JAVA_HOME system variable you just created:
    1. In the unlikely case that a PATH System variable does not already exist, create a new System variable; most likely you will be editing an existing PATH System variable
    2. If there isn't already a JDK bin directory mentioned in the PATH, it will work as a User variable.
    3. 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.
    4. Note that if the existing entry was created using JAVA_HOME, then we are already set correctly.
    5. If no entry exists already, add %JAVA_HOME%\bin as the new PATH entry.
    6. In the screenshot below, we edited the existing PATH System variable, adding a new entry that references the JAVA_HOME System variable we set previously: Windows - add PATH entry
  6. Once you have completed these steps, open a command line window and type javac -version and press enter; you should see a response like in the following screenshot: javac -version from command line If you don't see the version returned or if you see an error, then ask your instructor for assistance.

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 method declaration 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 states that there will be an array of String objects given to the method - these are the command line arguments.
  • To run the program, you would first compile a file named ClassName.java with the following from the command line:
    javac ClassName.java
                      
    and then use the following from the command line to run the program:
    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

As above, if terms like "static" and "instantiated" don't make too much sense right now, don't worry - we will cover these concepts in detail soon.

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

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 from the menu (if Java Project is not immediately available, choose Project ... first - the menu items are usage-sensitive).
  2. Name the project Exercises.
  3. check Create project from existing source .
  4. Browse to the Exercises directory, and OK it.
  5. You can then Finish the dialog box.

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 going forward in this course assume the use of a basic text editor and the command line. 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.

Running a Simple Java Program

Duration: 5 to 15 minutes.
  1. Use a text editor or IDE to open Java-Introduction/Exercises/Hello.java.
  2. Note that the file is intentionally blank.
  3. Enter the following code:
    public class Hello {
    	public static void main(String[] args) {
    		System.out.println("Hello World");
    	}
    }
  4. Save the file.
  5. In a command prompt window, change to the directory where Hello.java is stored and type the following
    javac Hello.java
    and press Enter. A prompt on the next line without any error messages indicates success.
  6. Next, type
    java Hello
  7. Press Enter. 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

Oracle provides extensive Java documentation. The homepage for Java documentation in English is at https://docs.oracle.com/en/java/. Documentation for the platform (JDK Standard Edition, or "SE") that you will use in this course is at https://docs.oracle.com/javase/10/ for the current version - version 10 as of this writing.

This page offer a wealth of resources - videos, downloadable books, etc. - to help you learn Java. Perhaps the most useful is the API reference - a detailed list of all of the built-in features of Java available to you when programming in the language:

https://docs.oracle.com/javase/10/docs/api/overview-summary.html

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 java.base, then java.lang, then out under "Field Summary" to get to this page:

https://docs.oracle.com/javase/10/docs/api/java/lang/System.html#out

From this page you can find the println methods we looked at above 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.