Introduction
So you want to learn how to program Java. Well, you've come to the right place. This primer is here to teach Java to anyone with a little time, motivation, and at least a basic level of practical computer knowledge. You don't need any prior programming experience to use this primer, but this will also not be an exhaustive programming course. It should, however, be enough to get you writing some basic to intermediate programs. I'll be publishing the primer in parts, starting with part one (this document). I will publish them as frequently as possible - hopefully no less then one per month. I expect to progress from very basic concepts all the way to intermediate and graphical programming. I also want this to be an interactive learning experience, so there will be a discussion forum at Tech-Unity devoted to each part of this primer. How far I go with this project will depend on the interest level in, and the success of, this primer. So, please participate and offer your questions, comments, or suggestions. Let's get started.
Programming Languages
Computers speak one language: binary. Binary (or base-2) is a number system which is composed of only the two numbers, 0 and 1. Compare that with our decimal number system (or base-10), which is composed of the ten numbers in the set 0 through 9. In computer language, strings of zeroes and ones have meaning. Each zero or one represents one bit. Eight bits together represent one byte. While it's probably possible to write programs in binary, it wouldn't be very easy, to say the least. That's why programming languages were created.
Machine Language
Machine languages are just one step above writing in binary. They have a very small set of instructions that represent basic "tasks" to the computer, such as "add", "subtract", "read", etc. Because the instructions are so elementary, it would take a long time to tell the computer to do something as simple as print a sentence. Machine languages are also written for specific types of computers, so your machine language program on your Windows PC would not work on your friend's Mac. So machine language programs are neither time efficient, nor portable. To solve some of these problems, high-level programming languages were created.
High-Level Languages
High level languages often have keywords that look like English words or phrases and typically have meaning similar to their English language counterparts. For instance, the BASIC programming language uses the keyword "goto", which tells the computer to go to a specific line in the program and execute that line. As you can probably tell from that example, each keyword in a high-level language often represents several machine instructions, which can make programming much easier. But how do we get from high-level languages to machine languages? And what about the several different machine languages? That's where compilers come in.
Compilers
Programs written in high-level languages have to be compiled, or translated into machine language, before they can be understood by a computer. Different types of computers "speak" different machine languages, therefore each high-level language must have a separate compiler for each type of computer. And very often programs must still be partially rewritten before being compiled into different machine languages. This can be inconvenient and often results in a delay in applications being available for certain platforms, such as Macintosh. Java was created, in part, to address this issue.
Intermediately Compiled Languages
Unlike most high-level languages, Java does not compile directly from source code (the un-compiled program) to machine language. Instead, Java compiles to an intermediate language that is somewhere between the source code and the machine language. Then Java relies on the Java Virtual Machine (JVM) on each computer to compile the intermediate code into machine code and run the program. There are a number of JVMs for different types of computers and each translates the Java intermediate code into the specific machine language needed for that computer. So, Java programs are truly portable.
Why Java?
Of the many good programming languages out there, Java is ideal for beginners for several reasons. First - as mentioned in the previous section - Java is portable in nature. So Java programs written on one platform can be transported to another platform with no changes. So your programs will work on Unix, Windows, and Macintosh1 without any source code changes. You'll hear this referred to as WORA, or Write Once Run Anywhere. Second, Java was built from the beginning to be object oriented. There are many advantages to using object oriented programming, including code efficiency, and increased maintainability. I'll talk more about object oriented programming (OOP) later. Third, everything you need to write and run a Java program (including documentation) is freely available for download. In the next section I'll talk briefly on how to get Java for your platform.
Getting Java
The Java programming language was created by Sun Microsystems, who has made it free to download and use. Java is highly modular, meaning it has many components that can function independently of each other. The following is a very basic breakdown of the Java platform.
Java Editions
Java comes in two main editions: Java 2 Standard Edition (J2SE) and Java 2 Enterprise Edition (J2EE). J2SE can be used to write many types of programs, including graphical desktop applications, networking applications, and "applets" which are often integrated into web pages. J2EE is used to develop component-based, multi-tier enterprise applications, which are way beyond the scope of anything we'll be learning here. So, J2SE is what I'll be using from here on.
The Java Runtime
In order to run Java applications, a computer has to have the J2SE Runtime Environment (JRE) installed. The JRE includes the Java Virtual Machine (JVM). As mentioned previously the JVM is the software that translates Java into your machine's native language. So, someone running Windows on an Intel x86 machine, would install the Windows version of the JRE.
The Java Development Kit
As a programmer, you'll also need the J2SE Development Kit (JDK). The JDK includes everything you need to compile, debug, and run your Java applications. I'll be using JDK version 5 (also called version 1.5). Because of the many new features in version 5, it's important that you have this version installed to take full advantage of this primer.
Confused? Don't sweat it. Getting Java ready to run on your system is easy. First, I'd recommend that you uninstall any old versions of the JRE or JDK from your system. Once you've removed old versions, you'll only need to download and install the JDK for your system. The JDK also includes the JVM, so you shouldn't need to download the JRE.
One Final Addition:
The only other thing that you'll need is a plain text editor like Notepad, vi, or emacs. I would not recommend using Microsoft Word or similar word processors, as they might add invisible formatting characters that will cause your Java program not to compile. Later on we'll use more sophisticated Java code editors that can save us time by doing a lot of the work for us, but for learning purposes we'll start off doing things manually.
Typographical Conventions
To increase readability, the formatting of certain types of text will be different from others. The following conventions will be used for the remainder of this primer.
Source Code Examples
When I give examples using actual source code I will enclose them in an inset box with a white background. The example will be color coded to highlight the different parts of the language. For instance, Java keywords will be blue and comments will be green. Example:Source Code will go here
Keywords will be blue and bold
Comments will be green and italicized
Java classes will be red
etc...
Input and Output
Initially most of the input and output will be done via a text-only command console. When describing this type of input/output here I'll enclose it in an inset box with a black background, meant to look like a generic command console. Text that is input by keyboard will be colored yellow and preceded by a forward slash and greater-then symbol, meant to represent a generic command prompt. Output will be represented by white text. Example:/> commands input via keyboard
output from those commandsTypographical conventions for input/output of graphical programs will be described later.
Inline Code Examples
Often I'll talk about a piece of code, a filename, or something similar, without enclosing it in an inset box as above. In these instances, I'll highlight the words in bold, navy blue "courier" font. Examples:fileName.java,/directoryName/anotherFileName.txt,public class SomeClass, etc.
Acronyms
You may have noticed a lot of acronyms in this document so far. If you work in IT, or another technical field you're probably used to the alphabet soup. In this document selected acronyms will have a red, dashed underline. When you hover your mouse over these acronyms you'll notice your cursor will change and a tool tip will pop up and tell what the acronym stands for. This way you won't have to keep scrolling back up the page to see what one stands for every time its referenced. Examples:WWW, WYSIWYG, TANSTAAFL
Footnotes
Footnotes will be denoted by a small, red, superscript number after the relevant word. Clicking these will take you to the bottom "footnotes" section where you'll see the corresponding number and accompanying explanation. Clicking the number in the footnotes section will take you back to the place you came from. Alternately, hitting the "back" button on your browser will accomplish the same task. Example:Trying to make this page render properly in Mozilla Firefox and Internet Explorer is almost enough to make me want to defenestrate2 my computer.
Hello World
No beginner's programming tutorial would be complete without the a "Hello World!" program. So, in keeping with tradition, I will include one here. If you've never programmed before, much - or all - of this program will be a mystery to you. Don't worry. I'll give a brief description of the components that make up this simple program, but the concepts will be covered in detail later. For now we'll use it as a preview of what's to come and a means to test our JDK installation.
The first thing to do is
create a new directory (folder) called JavaProjects. I wouldn't recommend putting it inside your
Java installation directory. This will be your main project directory. Inside this directory, create a subdirectory
called HelloWorld. This is the directory for your first Java project (In this case the project will
only consist of one program). Next, open a plain text editor and type (or copy/paste) the following code into it.
Save the file as HelloWorld.java inside your JavaProjects/HelloWorld directory. Mind your
upper and lower cases. Java is case-sensitive, so helloworld is not the same as HelloWorld.
Make sure the case of your file name matches the HelloWorld which is in your code.
This is a block comment
*/
// This is an inline comment.
public class HelloWorld
// File name must be exactly the same "HelloWorld.java"
{
public static void main( String args[] )
{
System.out.println( "Hello World!" );
} // End of main() block
} // End of HelloWorld block
Brief Explanation (optional)
This section attempts to briefly explain how the preceding code works. This is optional, so if you are curious then read on. Otherwise go on ahead to the next section. Don't worry. Everything here is explained, in detail, later. At the very top of my source code example, you'll notice that there are two comments (in green italics). The first is a block comment and the second is an inline comment. The start of a block comment is denoted by,
/*and the end is denoted by,*/. Anything between these two delimiters is a comment and is will be ignored by the Java compiler. Be careful when using block comments. If you forget the ending delimiter, everything after the start delimiter to the end of your program will be considered a comment. The start of an inline comment is denoted by,//. Inline comments don't need an end delimiter. Instead, the end of that line is considered the end of the inline comment.Moving down to the next statement, you'll see the words
public class HelloWorldfollowed by the open brace,{, on the next line.HelloWorldis the name of the class we are defining here and,{denotes the beginning of the block of code, which is the definition of the class. Every open brace must be paired with a closing brace to denote the end of that code block. Code blocks may also be "nested", or placed inside other code blocks, such as the next code block in our program.The start of the
main()block is indented one level (with tabs or spaces) to show that it is nested within theHelloWorldblock. Somain()is considered part of theHelloWorldclass. Inside themain()block is the statementSystem.out.println( "Hello World!" );. This simply outputs the text that is inside the quotes to the console. On the next line is the closing brace for themain()block, followed by the closing brace for theHelloWorldblock. Notice that each opening and closing brace pair are at the same indentation level. This is not mandatory, but is considered good programming practice because it makes the code more readable.Don't worry if you didn't get all of that. I included the explanation, as promised, for completeness. Everything in this program, and much more, will be covered in detail in later parts of this primer. Now, it's time for the payoff.
Running and Compiling
All that's left to do is compile and run your program. Open a command console window3 and navigate to the directory that contains your
HelloWorld.javafile. Type the following commands (in yellow) and you should see the output (in white):
/> java HelloWorld Hello World!
The first command, javac, compiles the HelloWorld.java and saves it as
HelloWorld.class. The second command, java, runs the program.
If it worked, congratulations! If not, don't sweat it. First go back and make sure you typed everything in exactly as I
have it. Just to make sure, copy and paste from this page directly into your file. Also check to make sure the
name of the file exactly matches HelloWorld.java. Remember, upper and lowercase are important.
If you have any questions or comments, feel free to post them at the Dream.In.Code Java forum.

