Part I: Java Foundation
1 Introduction to Java
2 Keywords, Data Types, and Variables
3 Operators
4 Flow Control
5 Methods
Chapter 1. Introduction to Java
You will learn about the following in this chapter:
What is Java?
Setting up a Java programming environment
Writing your first Java program
Welcome to Java!
This chapter will take you through a brief introduction to the Java language, including all the benefits of the language and answer the question: Why would you want to use Java? It will talk a little about Java';s history, and then get you up and running with your first Java application!
What Is Java?
Java is a high-level programming language that has many functions. It is used to develop applets that reside on Web pages, applications that run on your desktop, server-side middleware that are used to communicate between clients and server resources. Java is also used on Web servers and in embedded systems and smart devices, just to name a few of its many functions. The practical applications of Java can be found in Web browser applets and in server-side applications (Web and enterprise-wide).
History
The following is a short history of the Java programming language and the reasons for its inception. In 1991, a research group working as part of Sun Microsystems';s "Green" project, was developing software to control consumer electronic devices. The goal was to develop a programming language that could be used to control and network "smart" devices, such as televisions, toasters, and even buildings. These devices would all coexist and communicate with one another.
The first prototype that Sun came out with was a device called the Star7—a device, similar to a remote control, that could communicate with other Star7 devices. The initial intent was to use C++ to control the Star7, but as a result of frustration with that language, Green project member James Gosling developed a new language called Oak to control the Star7. The title Oak came from a tree that Gosling could see from his office window while developing the language. Sun later replaced the name with Java because Oak was already being used.
As a result of Oak, or Java, being designed to run on small appliances, the language had the following inherent benefits:
It was small, so it could run on the limited memory of small appliances.
It was efficient and reliable, so it could function as a small appliance—we are all used to computer crashes, but a microwave oven crash is not acceptable.
It was portable, so it could run on different pieces of hardware.
In 1994, the members of the Green project developed a World Wide Web (WWW) browser completely in Java that could run Java applets to demonstrate the power of the language. The browser was originally called WebRunner, but is now known as HotJava. Java came alive in 1995, however, when Netscape licensed the Java programming language and included support for it in its Navigator product.
In 1997, Sun released the Servlet API, which revolutionized server-side Web development and moved it away from monolithic CGI scripts or proprietary solutions. In 1999, Sun released the first version of the Java 2, Enterprise Edition (J2EE) specification that included JavaServer Pages (JSP) and Enterprise JavaBeans (EJB) in a highly distributed enterprise middleware. Since then the J2EE specification, along with the JSP, Servlet, and EJB specifications, have evolved into a very powerful programming paradigm.
Why Use Java?
You might have heard some of the geeks in your office talking about Java, or maybe you are taking a Java class in school, or perhaps you already know what Java is, but aren';t too sure why you would want to use it. Here are some reasons to learn Java, regardless of which category you fall under.
Java is a truly object-oriented programming language, perfect for modeling the real world and solving real-world problems. It will adapt to the latest design methodologies, and it provides extensibility so that your large project will be manageable.
Java is platform independent, so the same semicompiled byte code will work on Microsoft Windows, Unix, Apple Macintosh, Linux, and any future Wiz-bang operating system that implements a Java virtual machine.
Java can add interactivity to your Web pages. Java applets provide much of the functionality you are probably already familiar with, such as menus, data entry forms, and other user interface components as well as some of the neat drawings and animated graphics that are found on most Web pages.
With increasing CPU speeds, Java is becoming more feasible for building usable applications.
Java';s new SWING libraries rival components you see in the Microsoft Windows operating systems: tree controls, tab controls, list controls, tables, and so on.
Java has an incredible future in the upcoming decade! There is more and more talk about "intelligent devices" hosting a Java virtual machine that can run Java programs. These devices, such as smart toasters, smart televisions, and smart houses, will be networked together so that your television can tell your VCR to tell your toaster to start toasting! Java is the forefront technology of this exciting, evolving field.
Java has existed in its infancy for the past couple years, demonstrating conceptual leaps and bounds and accomplishing the unthinkable. As it evolves and matures, it is more and more apparent that Java will become the prevalent development language of the future. Learning Java will not only help you develop incredible applets and applications now, it will also prepare you for the future of computer and device programming!
Java Buzzwords
The following buzzwords are associated with Java; this section defines those buzzwords and explains how they are applicable to Java:
Simple
Object oriented
Distributed
Robust
Secure
Architecture neutral
Portable
Interpreted
Multithreaded
Simple
Java is simple to learn and simple to implement. Its syntax is very similar to C++ and C#, and it touts all the standard programming paradigms in an easy-to-use fashion. In fact, one of Java';s goals is to enable its developers to be up-and-running fast. Furthermore, it is consistent; when you learn how something works, you can rest assured that it will not change on you as you encounter a similar topic.
Object Oriented
Java is a truly object-oriented programming language that supports objects, inheritance, and polymorphism; this makes it ideal for establishing a good foundation in computer programming. We will discuss objects and object-oriented programming starting in Chapter 6, "Classes," but the main benefit of it is that you can model your Java programs after real-life objects, such as an apple, a car, or a person. This programming paradigm helps bridge the gap between the way a machine thinks and the way you do.
Distributed
Connectivity between components has been a basic tenet of the Java programming language since its inception. Java';s developers have remained true to this belief as the technology has evolved. Hence, developing applications that run on multiple machines concurrently and communicate with one another is far easier and efficient using Java than with many other programming languages.
Robust
Java';s modest beginnings as a simple mechanism to add interactivity to Web pages and develop simple communication schemes are a distant memory. Today Java boasts a graphical user interface (GUI) library that rivals features of the best operating systems; a Web development solution that surpasses any other offering; a distributed enterprise platform that leads the market; and a rich set of libraries for data input and output, multithreading, advanced imaging, XML document manipulation, and more. Almost any feature you could be searching for in a programming language you will find in Java.
Secure
Remember that Java';s inception was designed around the communication between smart devices. This legacy added a set of very strict rules governing what it can and cannot do. Various components of the Java programming language operate in different secure environments. For example, applets running in a Web browser cannot access a Web client';s underlying file system or any other Web site other than that from which it originated; a distributed component must be granted access to communicate with other hosts; and all Java programs run in a virtual machine that protects the underlying operating system from harm.
Architecture Neutral
Because Java runs inside of a Virtual Machine (a program written in operative system specific code that provides a common front-end to all operating systems) it in no way depends on the underlying operating system or hardware. Again this was another of the basic tenets of Java';s existence: to be able to run on any device.
Portable
Applications developed in Java are compiled into byte-code, which consists of instructions that a Virtual Machine will translate to operating system–specific instructions. Because of this, any Java code that you write and compile into byte-code will run on any operating system for which there exists a compatible Virtual Machine. Hence, the phrase: write once, run anywhere. The joke in the industry used to be write once, debug everywhere, but that is becoming less of a concern, especially in the server-side arenas.
Interpreted
Java is interpreted, which means that it is not compiled into machine-specific code until it is executed. Interpreted code tends to run much slower than fully compiled code, but Java gains some performance because it is partially compiled into byte-code. The partial compilation further benefits Java in that Java applications shipped to customers are not shipped as pure source code that can be easily read, but in a binary form.
Multithreaded
Multithreaded applications have the capability to run multiple things at the same time, for example a multithreaded application can display a graphical user interface to a user while downloading stock quotes from the Internet and computing historical averages. Java';s threading model was designed into the language from the beginning and is eloquently implemented, as you will learn later in the book.
Setting Up a Java Programming Environment
Before you can compile and execute a Java application, you must setup a Java programming environment. There are various Java compilers, but the standard is the one distributed on the Sun Web site. You can download the Java 2 SDK, Standard Edition from http://java.sun.com/j2se/.
On this page you will see three types of downloads for the latest released version and latest prereleased/release candidate (if available) version of Java. These three downloads are
Software Developers Kit (SDK)
Java Runtime Engine (JRE)
Documentation
The SDK is used to compile and execute Java programs; you will need to download this.
The JRE is used to execute Java programs, but does not contain anything for compiling them. People that use your Java applications will have to download and install JRE; the SDK includes the JRE so you don';t need to download it.
The documentation is specifically for users of the SDK. It lists and explains all the public classes in Java. I would highly recommend that you download and install this (it is viewable directly from the Internet). If you are short on disk space, then you can browse through the documentation as you need it.
As of this writing, the latest version of the Java 2, Standard Edition is version 1.4.
There are links to installation instructions presented to you when you download the SDK, but the following sections summarize the installation steps.
Microsoft Windows
The Java SDK for Microsoft Windows is an InstallShield­® file that guides you through the installation using wizard-like screens.
Download the SDK.
Launch the downloaded file.
Follow the prompts.
Linux
There are two versions of installation for Linux: a self-extracting binary file, and a binary file containing RPM packages.
Self-Extracting Binary
Download the SDK.
Copy the file to the directory where you want to install Java.
Grant the file execute privileges:
chmod a+x filename.bin
Execute the file:
./filename.bin
Follow the onscreen instructions.
RPM
RPM files, which are primarily used on Red Hat Linux, contain detailed installation instructions. RPM files are very easy to install and require little user interaction.
Download the SDK.
Grant the file execute privileges:
chmod a+x filename.rpm.bin
Execute the file:
./filename.rpm.bin
The result of this execution is the creation of a .rpm file. Execute the .rpm file as follows:
rpm -iv filename.rpm
Writing Your First Java Program
You can never escape the first chapter of a book without writing the traditional "Hello, World" application. Back in the early 1980s there was a book written by Brian Kernighan and Dennis Ritchie called The C Programming Language that was and is the de facto standard for C programming. In their book they defined the first example that all computer programming books should have: A program that writes the words "Hello, World" on the screen. Therefore, you will find a standard "Hello, World" example in almost every programming book you encounter. So, as not to break tradition, Listing 1.1 is "Hello, World" a la Java.
Listing 1.1 HelloWorld.java
1: public class HelloWorld
2: {
3: public static void main( String[] args )
4: {
5: System.out.println( "Hello, World!" );
6: }
7: }
Compiling Your First Java Program
Create a new file on your computer in a specific folder of your choice. For example, you might create a new file using Windows Notepad in the following folder:
C:\java
Enter the complete text of Listing 1.1 into your editor and save it with the following filename (note that case is important —capital "H" and "W" and all the rest of the letters are lowercase):
HelloWorld.java
If you are using Notepad, be sure to either enclose the filename in quotes ("HelloWorld.java") or check the filename when you are done, in some cases it likes to append a .txt to the end of the filename. If the filename is not correct, please correct it.
Open a command prompt and navigate to the folder where you saved your HelloWorld.java file. Using Windows as an example, open a command prompt, or MS-DOS prompt if you are using Windows 95, and enter the following command:
c:
cd \java
This will ensure that you are on the C: drive and change directory (cd) to the java subdirectory. Note that in this example you must have saved the file in this directory. Now you are ready to compile.
Compilation of Java programs is done at the command prompt using a tool that is packaged with the Java 2 SDK: javac read java see for Java Compiler. You compile a Java program by passing javac the name of the file you want to compile, for example:
javac HelloWorld.java
Upon executing the command you will see one of two possible responses: a new command prompt or a set of one or more errors. The most common error that my readers and students have when compiling Java programs has to do with an environment variable that Java depends on called CLASSPATH. The Java CLASSPATH is an interesting concept that often confuses not only new Java programmers, but experienced ones as well. The Java CLASSPATH is a list of folders that contain Java classes that you might want to include in your program, these define where your dependencies are located. If there is no CLASSPATH environment variable defined, the default value is the current folder. If there is one defined, the value must explicitly have the current folder in it if you want to compile from the current folder. To check the value of the CLASSPATH environment variable on your computer do the following:
Windows:
echo %CLASSPATH%
Unix:
echo $CLASSPATH
If the result is blank, then any errors you are receiving are not related to your CLASSPATH. If there is a value associated with the CLASSPATH environment variable, you must ensure that it includes the current folder. The CLASSPATH is simply a list of folders delimited by semicolons (;) on Windows and colons (:) on Unix. The current folder is specified by a period (.), which must appear in the CLASSPATH. To add the current folder to the CLASSPATH, enter the following:
Windows:
Add the current folder to the CLASSPATH
set CLASSPATH=.;%CLASSPATH%
Or to erase the CLASSPATH';s value
set CLASSPATH=
Unix:
CLASSPATH=.:$CLASSPATH; export CLASSPATH
At this point your CLASSPATH related errors should go away.
If you have other errors, here is a list of things to check:
Ensure that your Java code matches Listing 1.1: The case of all words must match identically, for example, class must be lowercase and "HelloWorld" must have a capital "H" and "W" and all remaining characters must be lowercase. Note that the formatting of the document does not affect the compilation, for example, if you want to write the entire program on one line or add 20 spaces between each line it would have no affect on the compiler.
Ensure that the name of your file is HelloWorld.java, again check the case of each letter, and if in Windows make sure Notepad did not add a .txt to the end of the filename. That can be accomplished by getting a directory of the folder your file is in by issuing a dir command (or ls in Unix):
dir
Ensure that you have the Java 2 SDK installed, and that the version you downloaded is the current version. To do so, execute the following command in the PATH:
java -version
Running Your First Java Program
After the HelloWorld.java file is successfully compiled, a new HelloWorld.class file is created. This is the file that contains the byte-code that contains instructions for the Java virtual machine to process. Java applications are run using the command-line tool java. To run HelloWorld, type the following from a command prompt in the folder that holds HelloWorld.class:
java HelloWorld
The result should be the following displayed to the screen:
Hello, World
If you receive an error, look at your CLASSPATH environment variable (see the discussion in the previous section for details).
Understanding Your First Java Program
It only took 7 lines to print "Hello, World" to the screen, and most of them have only one character each! Let';s look at this program line-by-line and see what is happening.
1: public class HelloWorld
In Java programs, .java files are compiled into byte-code with a .class extension. .class files can be thought of as the program itself. In this first line, a new class called HelloWorld is being defined. You can create new classes by using the keyword class followed by a name for the class.
Lines 2 and 7, the brace pair { and }, define the body of the HelloWorld class. Everything that is included between Lines 2 and 7 is part of the HelloWorld class.
3: public static void main( String[] arguments )
Line 3 defines a method, or function if you would prefer, that is a member of the HelloWorld class called main. main is a very special function in Java, specifically for applications. main is the entry point that the Java Runtime Engine (JRE), or java.exe, processes when it starts. When you launch the application later by typing
java HelloWorld
you are telling the Java Runtime Engine to open the class file HelloWorld.class and process the main function. Let';s break down this function prototype further:
public
The keyword public is known as an access modifier; an access modifier defines who can and cannot see this function (or variable.) There are three possible values for access modifiers:
public, protected, and private, each having their own restrictions, which we will cover later in the book. In this case, it is saying that this function, main, is publicly available to anyone who wants to call it. This is essential for the main function; otherwise the Java Runtime Engine would not be able to access the function, and hence could not launch our application.
static
The static keyword tells the compiler that there is one and only one method (or variable) to be used for all instances of the class. For example, if you have 100 different copies of the HelloWorld class running, there will be only one main function. This functionality will be explained more later when you get a little more Java under your belt, but for now remember that main functions have to be static in a class.
void
The term void refers to the return type. Functions can return values; for example, integers, floating-point values, characters, strings, and more. If a function does not return any value, it is said to return void. In this declaration it is saying that the main function does not return a value.
main
The word main is the name of the function. As previously mentioned, main is a special function that must be defined when writing a Java application. It is the entry-point into your class that the Java Runtime Engine processes when it starts; it will control the flow of your program.
( String[] arguments )
Enclosed in parentheses next to the function name is the parameter list passed to the function. When you write a function, you can pass any type of data for that function to work with. In this case, the main function accepts an array (a collection or set of items) of String objects (text) that represent the command-line arguments the user entered when he launched the application.
java HelloWorld one two three four
The command line then would have four items sent to it: one, two, three, and four. The variable arguments would contain an array of these four strings. Here is how that would be listed:
arguments[0] = "one"
arguments[1] = "two"
arguments[2] = "three"
arguments[3] = "four"
Note that the indexes (0, 1, 2, and 3) start at zero and climb up to one, minus the total number of elements. This zero indexing is common to many programming languages such as C and C++ and programmers refer to the first element in an array as the "0-th element." This book will address arrays in detail a bit later.
Command-line arguments are beneficial because they can give a program additional infor-mation about what tasks to perform. For example, if you wanted to create an application that added two numbers and printed the result, you could take the two numbers to add from the command line, for example:
java AddApp 5 10
In the main function you would read in the numbers 5 and 10, and then print their sum to the screen.
Lines 4 and 6, the brace pair, denote the body of the main function; everything that is written between these braces is part of the main function.
5: System.out.println( "Hello, World" );
Now this statement looks a little scary, but don';t fret, it is not nearly as intimidating as it looks. Let';s break apart this statement a bit:
System
System is actually a class that the Java language provides for you. This class is the focal point that you will use to access the standard input (keyboard), standard output (monitor), and standard error (usually a monitor unless you have a separate error output defined).
Note
Whenever you have questions about a class, you can always refer to the Java SDK documentation. Here is what the Java 2 SDK documentation has to say about the System class:
"The System class contains several useful class fields and methods. It cannot be instantiated."
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined "properties;" a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
The System class has a collection of public attributes, or data members, and a collection of public methods, or functions, that you can access in your program. You access these properties and methods by placing a period (.) after the class name System, and then appending to it the method or property name. The "." denotes a hierarchical movement through the object; the object to the left of the dot is the parent of the object to the right. In this example, we are going to access the System class';s out property.
out
The System class';s out property is defined as follows:
public static final PrintStream out
As with the main function, it is both public, meaning that everyone can access it, and static, meaning that there is only one copy of it for all instances of the System class. The final keyword says that this variable cannot change in value.
As I already mentioned, the out variable represents the standard output device, typically the monitor. Note that the out variable is of type PrintStream.
The PrintSteam class contains a collection of print, println, and write functions that know how to print different types of variables: Booleans, ints, floats, and so on. This is how println can print out so many different types of values.
Note
Here is what the Java 2 SDK documentation has to say about the out member variable:
"The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user."
Summary
This chapter discussed the fundamental concepts that empower Java as a powerful and productive programming language. It discussed the installation procedures and location of the Java 2 SDK Standard Edition, and then finished with writing your first Java program. Most of the discussion of your first Java program is probably still fuzzy, but now that you have a starting point, we will go through the entire Java programming language step-by-step so that this example will become trivial.
The next few chapters help you build a solid foundation into the Java programming language, starting with Chapter 2, "Keywords, Data Types, and Variables."
println
Okay, finally we are down to the function that actually does all the work for us! println has multiple definitions, one for each of the native data types (int, Boolean, float, double, String, and so on). The one that we are concerned with is declared as follows:
public void println(String x)
This version of the println function prints a String called x, which is what you send it, to an output stream.
Note
Here is what the Java 2 SDK documentation has to say about the println member variable:
"Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println()."
You might have noticed that the PrintSteam class has both print and println member functions. The only difference here has to do with the line termination. print simply prints text to the screen, whereas println prints text to the screen followed by a new line.
"Hello, World"
Finally, you have the text String that you are telling println to print to the standard output device. The text string is enclosed in parentheses and delimited by double quotes ("").
Note that a semicolon terminates the very end of the statement. This is very important in the Java programming language. A semicolon terminates all statements; this is how the Java compiler knows where one statement ends and the next begins.
|