Java Introduction
- About the Java Runtime Environment and how a Java program is created, compiled, and run
- How to download, install, and set up the Java Development Kit Standard Edition
- 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.
Obtaining The Java Environment
You can download the SDK (software development kit) including the compiler and runtime engine from Sun at: http://java.sun.com/javase.
- look for the download of J2SE 1.6.0.10 (or the latest release version).
You can also download the API documentation and even the source code.
- 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 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 form different sources, you must set an additional environment variable or two.
- 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:
- right-click on My Computer
- choose Properties
- select the Advanced tab
- click the Environment Variables button at the bottom
- check both the User and System variable lists to see if JAVA_HOME or PATH already exist
- if JAVA_HOME exists, check to see that it matches your most recent JDK
(or the one you wish to use)
- it is probably better to set this as a System variable
- if it exists, click Edit, if not, click Add
- for the variable name, enter JAVA_HOME
- for the value, enter your JDK directory, such as
Error. This text should not be shown. Please email courseware@webucator.com to report it:
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 Error. This text should not be shown. Please email courseware@webucator.com to report it: 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_14Error. This text should not be shown. Please email courseware@webucator.com to report it: 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)
- 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 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 version s 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 the class has been instantiated technically, even though you may run the class as a program, that doesn't mean that any object of that class is ever instantiated - you must instantiate one explicitly if you want to have one.
- 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:
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 ClassName
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 onto 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.
Exercise: First Java Program
- Create a file called Hello.java.
- Enter the following code:
public class Hello { public static void main(String[] args) { System.out.println("Hello World"); } } - Save the file.
- In a command prompt window, change to the directory where Hello.java is stored and type the following:
javac Hello.java
- A prompt on the next line without any error messages indicates success.
- Type:
java Hello
- 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
Sun provides extensive documentation of the API (library of available classes). The document ion for version 6 is available at http://java.sun.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 of the Java tutorial, you have learned:
Java Introduction Conclusion
- About the Java Runtime Environment
- How to download, install, and set up the Java Development Kit Standard Edition
- How to create a simple Java program