Chapter 1

Introducing Java

Today Java is one of the most popular programming languages for everything from programming games to creating mission-critical applications such as those for trading on Wall Street or controlling Mars rovers. In this lesson you are introduced to some of the very basic Java terms, and you will download and install the Java Development Kit (JDK) and compile your first program.

Why Learn Java?

The Java programming language was originally created in 1995 by James Gosling from Sun Microsystems (currently a subsidiary of Oracle Corporation). The goal was to provide a simpler and platform-independent alternative to C++. You’ll see what platform independence means a little later, in the section “The Life Cycle of a Java Program.” For now, let’s look at some of the reasons why Java can be your language of choice.

Java is a general-purpose programming language that’s used in all industries for almost any type of application. If you master it, your chances of getting employed as a software developer will be higher than if you specialize in some domain-specific programming languages.

There are around six million professional Java developers in the world and the majority of them are ready to share their knowledge by posting blogs and articles or simply answering technical questions online. If you get stuck solving some problem in Java, the chances are very high that you’ll find the solution on the Internet.

Since the pool of Java developers is huge, project managers of large and small corporations like to use Java for the development of new projects — if you decide to leave the project for whatever reason, it’s not difficult to find another Java programmer to replace you. At this point you may ask, “Does that also mean that my Java skills will be easily replaceable?” To improve your value and employability you need to master not only the syntax of the language, but also the right set of Java-related technologies that are in demand (you’ll learn them in this book).

Not only is Java open-source, but there are millions of open-source projects being developed in Java. Joining one of these projects is the best way to get familiar with the process of project development and secure your very first job without having any prior real-world experience as a programmer.

The Java language is object-oriented (OO), which allows you to easily relate program constructs to objects from the real world (more on this in Lessons 3–7).

There are plenty of technical features that make Java the right choice for many projects, and you’ll have a chance to see this for yourself while reading this book, watching the screencasts from the accompanying DVD, and deploying all code samples from the book on your computer.

Setting the Goals

The goal of this rather slim tutorial is to give you just enough information about most of the Java language elements, techniques, and technologies that are currently being used in the real world. The first half of the book is more about the Java language itself, while the second is about server-side Java technologies, and this is where Java shines in the enterprise world.

The brevity of some of the lessons may make you wonder if it’s even possible to explain a subject in just 10 pages while there are whole books devoted for the same topic. My approach is to cover just enough for you to understand the concept, important terms, and best practices. Prerecorded screencasts on the DVD will help you to repeat the techniques explained in the lesson on your own.

There are plenty of additional materials online that will help you to study any specific topic more deeply. But you’ll get a working and practical knowledge about Java just by using the materials included with this book.

The goal of this book is not just to get you familiar with the syntax of the Java language, but to give you practical Java skills that will allow you to develop business applications either on your own or by working as a team member in a larger-scale project.

The Life Cycle of a Java Program

There are different types of programming languages. In some of them you write the text of the program (aka the source code) and can execute this program right away. These are interpreted languages (e.g., JavaScript).

But Java requires the source code of your program to be compiled first. It gets converted to either machine-specific code or a bytecode that is understood by some run-time engine or a virtual machine.

Not only will the program be checked for syntax errors by a Java compiler, but some other libraries of Java code can be added (linked) to your program after the compilation is complete (deployment stage).

In this lesson you write a very basic Java program that will output the words “Hello World” on your computer’s screen.

Technically you can write the source code of your Java program in any plain text editor that you prefer (Notepad, TextEdit, vi, etc.), but to compile your program you’ll need additional tools and code libraries that are included in the Java Development Kit (JDK).

JDK and JRE

If you are planning to use a specific computer to develop Java programs, you’ll need to download and install JDK. If you are planning to use this computer only to run Java programs that were compiled somewhere else, you just need the Java Runtime Environment (JRE).

If you have JDK installed on your machine, it includes JRE.

Java’s platform independence comes from the fact that your Java program doesn’t know under which operating system (OS) or on which hardware it’s being executed. It operates inside the preinstalled JRE that is pretty much the same on every platform.

Since you’ll be learning how to develop Java programs, download JDK from the following website: http://www.oracle.com/technetwork/java/javase/downloads/jdk6-jsp-136632.html.

Java SE and EE

But before rushing to the downloading process, you need to get familiar with two more terms: Java SE (Standard Edition) and Java EE (Enterprise Edition). The latter includes the server-side tools and libraries that you’ll get familiar with starting in Lesson 26.

For now, just download the latest version of the JDK SE Development Kit. (The letter U followed by a number represents the update number of Java 6.)

Select the platform (Windows, Linux, Solaris) on which you are planning to develop Java programs and continue the download process.

note.ai

JDK for Mac OS X is preinstalled on Apple’s computers and no additional installing is required. The current version of JDK, which comes with computers running Snow Leopard, is JDK 6. It’s located in directory /Library/Java. In this book we’ll be using Java for the Windows OS, but Java is cross-platform and the book examples will work under MAC OS and Linux as well.

Downloading and Installing JDK in Windows

After selecting the Windows platform and clicking the Download button you’ll see a Login for Download screen, which is optional: You can skip this step.

Click Save File on the pop-up screen, as shown in Figure 1-1 (the file name depends on the version of JDK).

After the file is saved, start this executable and the installation wizard will lead you through the process. Read and accept the license agreement and click the button Next. Note the item at the bottom of the left box in Figure 1-2 — it is an open-source database management system (DBMS) called Java DB. You’ll need JavaDB for Lesson 22.

A couple of minutes into the installation process you’ll see a pop-up window asking you where to install JRE. I’ll assume that you’ve accepted the default directory (c:Program FilesJavajre6), but you can select a different one. Shortly, you should see a message telling you that installation was successful. Click Finish.

At the end of the installation process you’ll see a website suggesting you register the install. This step is optional.

If you have previous versions of JDK installed on your computer, each of them will be sitting in its own directory, e.g., c:Program FilesJavajdk1.6.0_019. But for a sanity check, I always open a command line window and enter java –version at the command prompt. Figure 1-3 shows the confirmation that I really have JRE 1.6.0_19 (Java 6 is also referred to as Java 1.6).

Congratulations! Your JDK and JRE are installed.

Your First Java Program: Hello World

Historically, the first program you write while learning a new programming language is the program Hello World. If you visit the website www.helloworldexample.net/ you’ll see how to write this program in many different languages, including Java.

To start writing a Java program you could use any plain text editor — I’ll use Notepad. The file that contains Java code must be saved in a file with its name ending in .java.

Enter the following code in the text editor.

download.eps

Listing 1-1: HelloWorld.java

public class  HelloWorld {
 
   public static void main(String[] args){         
            System.out.println("Hello World");
   }
}

Create a directory, c:PracticalJavaLesson1, and save the program you just created in the file HelloWorld.java (if you use Notepad, select All Files in the Save as Type drop-down to avoid auto-attachment of the .txt suffix).

Keep in mind that Java is a case-sensitive language, which means that if you named the program HelloWorld with a capital H and a capital W, you should not try to start the program helloworld. Your first dozen syntax errors will be caused by improper capitalization.

What follows is a really short explanation of some of the terms and language elements used in the HelloWorld program. You’ll get more comfortable with them after mastering the first several lessons in this book.

Our first program contains a class, HelloWorld. Give the Java class and its file the same name. (There could be exceptions to this rule, but not in this simple program.) While writing Java programs you create classes, which often represent objects from real life. You’ll learn more about classes in Lesson 3.

The class HelloWorld contains a method, main(). Methods in Java classes represent functions (actions) that a class could perform. A Java class may have several methods, but if one of them is called main() and is declared (if it has a method signature), as in our class, this makes this Java class executable. If a class doesn’t have a method main(), it can be used from other classes, but you can’t run it as a program.

The method main() calls the method println() to display the text “Hello World” on the screen. Here is the method signature (similar to a title) of the method main():

public static void main(String[] args)

This method signature includes the access level (public), instructions on usage (static), return value type (void), name of the method (main), and argument list (String[] args).

  • The keyword public means that the method main() can be accessed by any other Java class.
  • The keyword static means that you don’t have to create an instance of this class to use this method.
  • The keyword void means that the method main() doesn’t return any value to the calling program.
  • The keyword String[] args tells us that this method will receive an array of characters as the argument (you can pass external data to this method from a command line).

The main() method is the starting point of your program. You can write a program in Java SE that consists of more than one class, but at least one of them has the method main(), otherwise the program won’t start. A Java class can have more than one method. For example, the class Employee can have the methods updateAddress(), raiseSalary(), changeName(), etc.

The body of the method main() contains the following line:

System.out.println("Hello World"); 

The preceding println() method is used to print data on the system console (command window). Java’s method names are always followed by parentheses.

System here represents another Java class.

The dot notation System.out means that the variable out is defined inside the class System.

out.println() tells you that there is an object represented by a variable called out and it has a method called println().

You will be using this dot notation to refer to class methods or variables.

Compiling and Running Hello World

Now you need to compile this program. The javac compiler is a part of JDK, so open a command window on your PC, change the current directory to c:PracticalJavaLesson1 and try to compile the program:

             cd PracticalJavaLesson1
              javac HelloWorld.java

Oops. I got an error telling me that javac is not recognized as an internal or external command, operable program, or batch file. The OS doesn’t know where javac is located. You need to add the directory in which the javac compiler resides to the system variable PATH. In Windows OS, go to Control Panel, click the System icon, select the tab Advanced, and click Environment Variables. Edit the system variable PATH so it starts with the following: C:Program FilesJavajdk1.6.0_19in; By the time you’ll be reading this book the Java version number may be different so check the name of the directory before modifying the system variable PATH.

Restart your command window and now the OS should be able to find javac. Get into the directory where HelloWorld.java is located and repeat the compilation command.

You won’t see any confirmation of a successful compilation; just type dir to confirm that a new file named HelloWorld.class has been created. This proves that your program has been successfully compiled.

If the program has syntax errors, the compiler prints error messages. In this case fix the errors, and recompile the program again. You may need to do it more than once until the file HelloWorld.class is successfully created.

Now run the program by typing the command

java HelloWorld      

Note that this time we used the term java, which starts the Java Virtual Machine (JVM). The words “Hello World” are displayed in the command window. In Figure 1-4 is a screenshot that shows the compilation command, the content of the folder after the compilation, and the output of the HelloWorld program.

Try It

In this lesson your goal is to write your first Java program that outputs the words “Hello World.”

Lesson Requirements

For this lesson download and install the current version of JDK from http://java.sun.com/javase/downloads/index.jsp. Set the value of the system PATH variable to include the bin directory, where your Java compiler (javac) and other executables were installed.

Step-by-Step

1. Open a plain text editor of your choice and enter the text of the Hello World program.

2. Save the program in the file HelloWorld.java.

3. Compile the program in the command window using the command javac HelloWorld.java.

4. Run the program by using the command java HelloWorld.

cd.ai

Please select Lesson 1 on the DVD with the print book, or watch online at www.wrox.com/go/fainjava to view the video that accompanies this lesson.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.192.71