Getting Started with Java

Share this article

Looking to learn how to build dynamic Web sites? There are many options out there, the most popular of which include ASP, PHP, and other scripting languages. Another option is Java. Oh sure, Java began as a language for writing Web-based Applets and cross-platform applications, but in the past few years its role has been expanded to include server-side programming of Web pages. In fact, there is great demand in the job market for developers with experience in writing server-side Java applications. Your first step towards adding these skills to your résumé should be to pick up a basic understanding of the Java language in general.

This is the first in a series of articles that will teach you the Java programming language with an eye to features and techniques that are applicable to building dynamic Web sites. Specifically, after covering the basics of the language and the object-oriented concepts you need to use the language effectively, I’ll proceed to a discussion of Java Servlets and JavaServer Pages (JSP), the two technologies used to build dynamic, data-driven Web sites using Java. Along the way, I’ll introduce you to related technologies, like Java Database Connectivity (JDBC). But before I get too bogged down in a description of things to come, let me turn your attention to the object of this article: an introduction to the basics of the Java language.

What Is Java?

Java is a full-featured programming language like C/C++, but simpler and more tightly structured. Like C++, Java is an object-oriented programming language, which is a concept I’ll expand on in the next article in this series. In basic terms, however, Java programs are written by creating a structured set of software components that interact with each other to produce the desired effect. These components are called objects, and the fundamental task of a Java developer is to determine the best object structure to achieve a system that works as required, as efficiently as possible and, wherever possible, producing components that may be reused in similar applications.

If all that sounds a little scary, don’t worry; it’ll all make sense once you’ve learned it. For now, we’ll proceed in baby steps.

Java programs, instead of running directly on a computer’s operating system, run on a “Java Virtual Machine” (JVM), which itself is a program that runs on the computer’s operating system. Since the production of Java Virtual Machines is highly standardized, incompatibilities between different platforms are minimal. This means that, in theory, any operating system that has a JVM (pretty much all major operating systems these days) can run any Java program, with no need to recompile the program for each platform. This leads to one of the most attractive features of the Java language: “Write Once, Run Anywhere” (WORA). The disadvantage is that Java programs tend to run slower because the Virtual Machine has to convert Java program instructions and pass them to the operating system on which it is running.

Most current Web browsers can also run Java programs that are downloaded from the Web, either using a JVM built into the browser (as in Netscape 4 and Internet Explorer browsers), or by interfacing with a standard JVM installed separately (as in Netscape 6 and Opera browsers). Java programs designed to run in Web browsers are called Java Applets. When Java was originally released, much of the marketing hype surrounding the language centred on these little programs that run in Web browsers. Over the years, however, the focus of Java on the Web has shifted to server-side applications (including Servlets and JSP), and Java applets have been replaced in many instances by more nimble technologies like Dynamic HTML and Flash. Common uses of Java applets these days include Web-based chat programs and online games.

Now that you know what you’re getting yourself into, it’s time for you to get a hold of the tools you’ll need to get started with your Java development efforts.

What You’ll Need

Everything you need to develop and run Java programs may be freely downloaded from the Sun Java Web site at www.javasoft.com. The main package you’ll need is the Java 2 Software Development Kit (SDK), Standard Edition. The SDK contains both the development tools for creating Java programs and the Java Runtime Environment (JRE) for running Java programs. The JRE includes the JVM and various supporting files. Barring Java applets, which run using the internal JVM’s of some browsers, anyone who wants to run a Java program will need to install the JRE, which may be downloaded separately from the SDK as well. To write your own Java programs, however, you need the full SDK. You’ll also want to pick up a copy of the Java 2 Platform Documentation package, which includes a comprehensive reference of all the built-in functionality that Java provides for you. Once you get familiar with the basics of the language and are ready to write real-world programs, this documentation will be your very best friend.

Detailed installation instructions are provided for each of those packages, and I highly recommend you follow them to the letter. Many people who install the Windows version simply download and run the setup program and neglect to complete the additional task of setting up critical environment variables to allow Java to operate correctly. The only omission in the provided installation instructions is a method to add/edit environment variables in Windows ME and Windows 2000. The methods provided in the instructions work for Windows 95/98/NT, but in Windows ME you need to click Start, Run…, and then type msconfig to launch Windows ME’s System Configuration Utility. The system environment variables may be adjusted on the Environment tab. In Windows 2000, the procedure they provide is almost right. Once you run the System Control Panel icon, proceed to the Advanced tab and click the Environment Variables button, then proceed according to the instructions.

To double-check that the Java SDK is installed correctly on your computer, open a command prompt (i.e. the Command Prompt or MS-DOS Command Prompt in Windows, or XTerm under Linux). Try the two commands shown below. If you get similar output, you’re good to go. If your operating system doesn’t recognize the commands, you may need to reboot for changes to your environment variables to be detected.

C:> java –version  
java version "1.3.0"  
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)  
Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)  
 
C:> javac  
Usage: javac <options> <source files>  
where possible options include:  
 ...list of options...

Once you have the SDK (and, optionally, the documentation) installed, you’re ready to write your first Java program. Before you proceed, let me say a few words about Integrated Development Environments (IDE’s). You have probably seen ads for fancy development environments, both commercial and free, for writing Java programs. While these can be useful for the experienced Java developer (I myself make heavy use of IBM VisualAge for Java in my own projects), I strongly recommend that, as a beginner, you get started using the simple tools provided in the SDK.

My reasoning on this issue is that many of the features provided by Integrated Development Environments such as JBuilder and others are designed to provide shortcuts to get certain tasks done more quickly. The problem is that if you don’t understand the ‘long way’ of doing those tasks beforehand, you’re going to have a lot of trouble understanding the implications and pitfalls of using the automated methods provided by these tools. This issue is akin to choosing between a text editor like HotDog Pro and a WYSIWYG editor like Dreamweaver to build a Web site. While Dreamweaver can help you quickly produce some advanced effects, if you don’t understand how to hand-code those same effects beforehand, you’re going to have a hard time producing any advanced effects beyond the scope of those provided through Dreamweaver’s automated tools.

Your First Java Program

The goal of this section is to give you a feel for the process of writing, compiling, and running a Java program. You’ll also get to see what a Java program – if only a very basic one – looks like. I’ll explain everything in basic terms, but if something doesn’t make sense to you don’t worry about it too much. Some concepts will only be familiar to experienced programmers, and if that’s not you, don’t worry about it! At this stage it’s most important for you to get used to what needs to be done, not understand why.

Start by creating a new directory in a convenient place; in most cases, you’ll want the files for each of your Java programs to be stored in a separate directory. I’ll assume the directory you’re using is D:MyFirstJava, but you can call the directory anything you like. Under Linux, for example, you would probably create the directory as a subdirectory of your personal home directory (e.g. /home/kyank/MyFirstJava).

Using whichever text editor you prefer (NotePad under Windows will do fine, for example), create a file called Hello.java in that directory. Note the .java file extension. All files containing Java source code should be given the .java extension to identify them as Java source files. Note also that the filename is capitalized. This is important, so be sure to give the file that exact name. To save a file without a .txt extension in NotePad, be sure to select All Files in the Save As Type drop-down menu in the Save As dialog box; otherwise, NotePad will add .txt to the end of the filename (e.g. Hello.java.txt).

Type the following for the contents of Hello.java, then save the file. Note that the line numbers are provided only for your convenience; do not type the line numbers into the file!

1  /**   
2   * Hello.java  
3   * A simple Java program  
4   */  
5  
6  class Hello {  
7    public static void main(String[] args) {  
8      // Print a couple of one-line messages  
9      System.out.println("Hello, World!");  
10     System.out.println("This is a test.");  
11   }  
12 }

You’ve just written your first Java program! Before I show you how to compile and run it, I’ll step through the code line by line to explain, in general terms, what everything does.

  • Lines 1-4: The file starts out with a comment. This is a section of the code that is intended for people to read to help them better understand what the code does. Java actually ignores comments entirely, so the program would work exactly the same if these four lines were removed from the file (try it later if you like!), but it is good practice to always describe the contents of a file with a comment at the top. In Java, there are two ways to include comments in your files. This first method starts a comment with /* (pronounced ‘slash-star’) and ends it with */ (‘star-slash’). Everything between these two markers is ignored by Java. As you can see, a comment of this type can span multiple lines.

    I’ve formatted this comment in the standard style recommended by the Java documentation style guide. The comment begins with slash-star followed by another star and a line break, and then each line of the comment begins with a space followed by a star and another space. The comment ends with a space followed by the terminating star-slash appearing alone on a line. While this is the recommended commenting style, and will be the one I use throughout this series of articles, you or your company may develop an alternate style. Here are a couple of examples of alternate commenting styles:

    /*                           /*-----------------------*  
     Hello.java                  | Hello.java            |  
     A simple Java Program       | A simple Java program |  
    */                           *-----------------------*/

    Although they look very different, notice that they both start with /* and end with */. What comes between those two markers is of no consequence as far as how the program works – use whatever style you prefer.

  • Line 5: Blank lines are ignored, just like comments.
  • Line 6: I said earlier on that Java programs consist of a set of software components that work together to achieve the desired effect. This very simple program requires only one such component, and this line marks it’s beginning. The word class indicates that I am starting a new component (for now, you can take a class to mean a component), and the word Hello is the name of that component (or class). The opening brace ({) marks the beginning of the code that will define the new class.

    It’s no coincidence that the class (Hello) is named the same as the file in which it is defined (Hello.java). In fact, this is a requirement. Every class that you create must be defined in its own file with the same name as the class defined within. The two names must match exactly, right down to the case (you can’t define a class named MyClass in a file called myclass.java; rather, the file must be named MyClass.java).

    Class names in Java are capitalized by convention. That is to say, you could name a class myclass if you really, really wanted to, but other Java programmers are used to seeing class names capitalized, so your code will be a lot easier to read and maintain if you instead called the class MyClass.

  • Line 7: This line looks pretty tricky, and indeed it is the most complicated line in the program, as far as how much you need to know to understand it completely. Just as the previous line marked the beginning of a class, this line marks the beginning of a method. A method may be loosely defined as something that a class can do. If you’ve worked with other programming languages, methods are the Java equivalent of functions or subroutines.

    The words public, static, and void at the start of the line provide certain information about this method. Each of these has a fairly long story behind why it is required here; so don’t worry about these for now. The word main is the name of the method. Note that method names, unlike class names, are not capitalized. Once again, this is only a convention, but one that you should really stick to for the sake of others who may have to read your code.

    Depending on how much, if any, programming experience you have, the parenthesized portion of this line is either already familiar to you or pretty scary looking. Basically, it defines what information is required to make this method do its job, but for now you don’t need to worry about the details.

    This main method is actually rather special. When it first starts running a program, Java looks for a method called main with the words public static void in front of it in the class and uses it as the starting point of the program. So if you like, you can think of this whole line as a “magic formula” for saying “the program starts here”.

  • Line 8: This is another comment, a portion of the code that is included for the benefit of people who need to read the code. Once again, the program would function exactly the same if this line were removed. Notice that this comment doesn’t start and end with /* and */. This is an example of the second type of comments that Java allows you to use. When it encounters // (slash-slash) anywhere in your code, Java ignores the rest of that line. This type of comment is useful for quickly writing one-line comments in your code, or for adding a short explanation to the end of a particularly complicated line of code.
  • Line 9: This line is the first example of a Java statement in this program. A statement tells the program to do something; it is a command, instruction, or order if you prefer. Java statements take many different forms, but they all end with a semicolon (;). One of the most common mistakes that beginners make when writing Java programs is to forget the semicolons on the ends of their statements. Fortunately, Java is pretty good about spotting these mistakes and letting you know about them.

    This particular statement instructs your program to print the text Hello, World! on the screen. System.out.println means “print the following line of text on the screen,” while the rest of the line indicates what, precisely, should be printed.

  • Line 10: Much the same as the previous line, this statement tells the program to print the text This is a test. on the screen. Since the statements are executed one after another, this message should be printed on the screen right after the previous message.
  • Line 11: The closing brace on this line marks the end of the main method. When the program gets to this point, it stops running.
  • Line 12: The closing brace on this line marks the end of the Hello class.

Before I continue, a note on coding style. You probably noticed that some of the lines of this program have spaces in front of them, while others don’t. This coding style, known as indenting is intended to show off the structure of the code. That is, by indenting the main method (along with its closing brace on line 11) by two spaces, it makes clear the fact that the method is inside the Hello class. Likewise, by indenting lines 8-10 (the contents of the main method) by a further two spaces, it becomes clear that those lines belong to the main method. The code of the program could have been written without indenting (with every line starting at the left margin), and it would have worked just as well, but the structure of the program would not have been obvious at a glance. When you get to a stage where you’re writing complicated programs, it will not be uncommon for certain passages of your code to be indented five or even ten levels deep. By picking up this good habit now, it will ensure that your code is easy to read now and in future.

Compiling and Running your Program

With your first Java program written, you’re probably anxious to see it running. Before you can run your program, you must first convert it into a format that the Java Virtual Machine (JVM) can understand. This process, called compilation, involves running a program called the Java compiler that checks your Java code for mistakes (missing semicolons and whatnot) and then converts it into a binary format called Java bytecode that the JVM can understand. The Java compiler is run from the command line by typing javac, followed by the name of the Java code file that you want to compile.

To compile your Hello.java file, start by opening a command prompt and navigating to the directory containing the file to be compiled. On Windows, for example, to navigate to D:MyFirstJava, type the following commands (hitting Enter after each):

C:> d:    
   
D:> cd MyFirstJava    
   
D:MyFirstJava>

To compile Hello.java, type the following command:

D:MyFirstJava> javac Hello.java

If everything goes as planned, there should be a short delay followed by another prompt (no news is good news!). If the compiler finds anything wrong with your code, however, one or more errors or warnings will be displayed. In most cases, the exact line number and some clue as to the nature of the error will be given. Compare your code to that provided above and make sure they match exactly (remember, the line numbers are not part of the code).

Once you’ve successfully compiled your program, a file called Hello.class will have been created in the directory alongside your Hello.java file. This is the compiled version of your Java code, and contains a description of the Hello class that you defined in your file. Such files are called class files, for obvious reasons. That description is in binary format (specifically, in Java bytecode), and is ready to be run by the JVM.

Running a Java program is similar to compiling it, except that instead of using the Java compiler (javac), you use the Java Runtime Environment (JRE), which you can invoke using the java command, followed by the name of the class that contains the special main method. In this case, your class is called Hello, so to run your program you type the following command:

D:MyFirstJava> java Hello
Hello, World!
This is a test.

As expected, the two messages, Hello, World! and This is a test. are printed out. Your program is working! One important note: when running a program, you need to specify the name of the class (Hello), not the name of the class file (Hello.class). Java finds the class file automatically using the name of the class. If you told it to run Hello.class, it would be looking for a file containing a definition of a class called Hello.class, and you’d get an error like the following:

D:MyFirstJava> java Hello.class
Exception in thread "main" java.lang.NoClassDefFoundError: Hello/class

This NoClassDefFoundError indicates that Java couldn’t find a definition of the class it was looking for, in this case Hello.class (which it displays as Hello/class for reasons that I’ll explain in a future article).

Summary and Further Reading

In this article, I’ve provided an introduction to the Java programming language from the ground up. I covered the basics of what Java is and why it’s a useful tool to have under your belt, I explained what tools you need to write, compile, and run Java programs on your computer and where you can get them, and finally I walked you through the process of creating and running a very simple Java program.

As I said, this is only the first in a series of articles intended to bring you into the world of Java programming for the Web. In part 2, Java Language Baics, we’ll explore the language in greater detail, covering data types, operators, variables, and flow of control. In the meantime, if your ultimate goal is to learn to create dynamic Web sites using Java Servlets and JavaServer Pages (JSP), you can read my JSP Quick-Start Guide to set up the software you’ll need to produce server-side Java programs for the Web.

If you’re anxious to move forward with the Java language, there are some other resources you can refer to while awaiting additional instalments in this series. The Java Tutorial is the official online guide to learning most aspects of Java, and can be accessed free of charge. A better way to learn the language, however, is to pick up a good book on the subject. My best recommendation goes to “Beginning Java 2 – JDK 1.3 Edition” from WROX Press, and a complete review can be found here.

Kevin YankKevin Yank
View Author

Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn't stop at books, he's also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week