|
|
Getting Started With Java By Herbert Schildt
Java is the preeminent programming language of the Internet. Originally conceived in 1991 by James Gosling at Sun Microsystems, Inc., the language was initially called Oak, but was renamed Java prior to its 1995 release. In very short order, Java transformed the Web into a highly interactive environment, setting a new standard in computer language design in the process. Its innovations changed the course of programming and its influence continues to be felt. If Web development is in your future, then Java is the right language to learn. The purpose of this article is to help you take your first steps toward becoming a Java programmer. Here you will learn how to
Keep in mind that Java is a full-featured, professional programming language. The information presented here is only a starting point.
Obtain the Java Development Kit Before you can compile and run a Java program, you must have a Java development system installed on your computer. The one used by this article is the standard JDK (Java Development Kit), which is available from Sun Microsystems. The JDK can be downloaded free of charge from java.sun.com. Just go to the download page and follow the instructions for the type of computer that you have. After you have installed the JDK, you will be ready to compile and run programs. Note: Beginning with the release of Java 2 Platform Standard Edition 5 (J2SE 5), the term JDK technically stands for J2SE Development Kit. However, most programmers still refer to it as the Java Development Kit. The JDK supplies two primary programs. The first is javac, which is the Java compiler. The second is java, which is called the application launcher. It starts the Java interpreter, which executes your program. One other point: the JDK runs in the command prompt environment. It is not a windowed, GUI-based application.
Create, Compile, and Run Your First Java Program The first step to learning to program in Java is to understand how to create, compile, and run a Java program. The one we will begin with is shown here. /* Here is the sequence you will follow.
Enter the Program When you write a program, you create a file that contains the program's source code. Source code is the human-readable form of a program. Thus, you must begin by creating a file that holds the source code to the program just shown. To enter the program, you must use a text editor, not a word processor. Word processors typically store format information along with text. This format information will confuse the Java compiler. If you are using Windows you can use WordPad to enter the program. Just be sure to save it as a text file. For most computer languages, the name of the file that holds the source code to a program is arbitrary. However, this is not the case with Java. Instead, the name you give to a source file can be very important. For this example, the name of the source file should be Example.java. Here's why. In the program, notice this line: class Example { This line begins the definition of a class called Example. A class defines a basic unit of program functionality. In Java, all program activity occurs in a class, and all programs must define at least one class. As a general rule, the name of a source file should match the name of the class that it holds. Because Java is case sensitive, you must also make sure that the capitalization of the filename matches the class name. The Java compiler requires that a source file use the .java extension. At this point, the convention that filenames correspond to class names may seem arbitrary. However, following this rule makes it easier to maintain and organize your programs. Furthermore, in some cases, the name of the file must match the name of the class that it holds.
Compile the Program Before you can run the program, you must compile it. Compilation translates the source code into a form that can be executed. In the case of Java, the output of the compiler is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is commonly called the Java Virtual Machine (JVM). Thus, the output of the Java compiler is not code that can be directly executed by the CPU of your computer. To compile the Example program, execute the Java compiler, javac, specifying the name of the source file on the command line, as shown here: javac Example.java This causes javac to create a file called Example.class that contains the bytecode version of the program. Here is an important point: The bytecode file is called Example.class not because the source file name is Example.java, but because Example is the name of the class that was compiled. In general, when a Java source file is compiled, the bytecode for the class contained in the file is put into an output file named after the class and having the .class extension. This is why it is a good idea to give a file the same name as the class it contains—the name of the source file will match the name of the .class file.
Run the Program To actually run the program, you must use java, the Java application launcher. To do so, pass the class name Example as a command-line argument, as shown here: java Example This causes the class Example to be run. Notice that you do not specify the .class extension. When the program executes, the following output is displayed: Java drives the Web. To review: The output of javac is bytecode. Bytecode is not directly executable by the CPU of your computer. Rather, it is interpreted by the JVM, which is started via java. To execute a program, pass its class name to java.
The First Sample Program Line by Line Although Example.java is quite short, it includes several key features that are common to all Java programs. Let's closely examine each part of the program. The program begins with the following lines: /* This is a comment. Like most other programming languages, Java lets you enter a remark into a program's source file. The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. In this case, the comment describes the program and reminds you that the source file should be called Example.java. Of course, in real applications, comments generally explain how some part of the program works or what a specific feature does. Java supports three styles of comments. Two types are used in the program: multiline and single-line. (The third type is the documentation comment, but it is beyond the scope of this article.) The one shown at the top of the program is a multiline comment. This type of comment must begin with /* and end with */. Anything between these two comment symbols is ignored by the compiler. As the name suggests, a multiline comment may be several lines long. The next line of code in the program is class Example { This line uses the keyword class to declare that a new class is being defined. As mentioned earlier, the class is the basic building block of Java, and the place in which all program activity occurs. Example is the name of the class. The class definition begins with the opening curly brace { and ends with the closing curly brace }. The elements between the two braces are members of the class. The next line in the program is the single-line comment, shown here: // A Java program begins with a call to main(). This is the second type of comment supported by Java. A single-line comment begins with a double slash (//) and ends at the end of the line. As a general rule, programmers use multiline comments for longer remarks and single-line comments for brief, line-by-line descriptions. The next line of code is public static void main(String args[]) { This line begins the main( ) method. In Java, a subroutine is called a method. As the comment preceding it suggests, this is the line at which the program will begin executing. All simple Java programs begin execution by calling main( ). A complete description of this line cannot be given here because it requires a detailed understanding of several other Java features. However, because of its importance, a brief overview is warranted. The public keyword is an access specifier. An access specifier determines how one part of a program can be accessed by other parts of the program. When a class member, such as main( ), is preceded by public, then that member can be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.) In this case, main( ) must be declared as public because it is called by code outside of its class when the program is started. The keyword static allows main( ) to be called before an object of its class has been created. This is necessary since main( ) is called by the Java interpreter to begin program execution. The keyword void simply tells the compiler that main( ) does not return a value. The name of the method is main. Inside the parentheses that follow main is declared a parameter called args. This is an array of objects of type String. (Arrays are collections of similar objects.) Objects of type String store sequences of characters. In this case, args receives any command-line arguments present when the program is executed. This program does not make use of command-line arguments. However, the args parameter must be present in the declaration of main( ) whether it is used or not. The last character on the line is the {. This signals the start of main( )'s body. All of the code included in a method will occur between the method's opening curly brace and its closing curly brace. The next line of code is shown here. Notice that it occurs inside main( ). System.out.println("Java drives the Web."); This line outputs the string "Java drives the Web." followed by a new line on the screen. Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the string that is passed to it. As you will see, println( ) can be used to display other types of information, too. The line begins with System.out. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. Thus, System.out is an object that handles console output. The first } in the program ends main( ), and the last } ends the Example class definition. Remember: Java is case sensitive. Forgetting this can cause you problems. For example, if you accidentally type Main instead of main, or PrintLn instead of println, the preceding program will be incorrect. Furthermore, if you misspell main, the compiler will still compile your program. However, the Java interpreter will report an error because it won't be able to find the main( ) method when it tries to execute the program.
Using a Variable Perhaps no other construct is as important to a programming language as the assignment of a value to a variable. A variable is a named memory location that can be assigned a value. Further, the value of a variable can be changed during the execution of a program. That is, the content of a variable is changeable, not fixed. The following program uses two variables called x and y. /* When you run this program, you will see the following output: x contains 10 This program introduces several new concepts. First, the statement int x; // this declares a variable called x declares a variable called x of type integer. In Java, all variables must be declared before they are used. Further, the kind of values that the variable can hold must also be specified. This is called the type of the variable. In this case, x can hold integer values. These are whole number values. In Java, to declare a variable to be of type integer, precede its name with the keyword int. Thus, the preceding statement declares a variable called x of type int. The next line declares a second variable called y. int y; // this declares a variable called y Notice that it uses the same format as the first except that the name of the variable is different. In general, to declare a variable you will use a statement like this:
Here, type specifies the type of variable being declared, and var-name is the name of the variable. In addition to int, Java supports several other data types, such as double, float, long, short, and char. In Java, variable names (and other programmer-defined names) are called identifiers. Identifiers may start with any letter of the alphabet, an underscore, or a dollar sign. Next may be either a letter, a digit, a dollar sign, or an underscore. The underscore can be used to enhance the readability of a variable name, as in line_count. The dollar sign is intended for machine-generated names and not for general use. Uppercase and lowercase are different; that is, to Java, myvar and MyVar are separate names. Here are some examples of acceptable identifiers:
Remember, you can't start an identifier with a digit. Thus, 12x is invalid, for example. The next line in the program, shown here, assigns x the value 10. x = 10; // this assigns 10 to x In Java, the assignment operator is the single equal sign. It copies the value on its right side into the variable on its left. The next line of code outputs the value of x preceded by the string "x contains ". System.out.println("x contains " + x); In this statement, the plus sign causes the value of x to be displayed after the string that precedes it. This approach can be generalized. Using the + operator, you can chain together as many items as you want within a single println( ) statement. The next line of code assigns y the value of x plus 2. y = x + 2; After the line executes, y will contain the value 12. The value of x is unchanged and is still 10. Like most other computer languages, Java supports a full range of arithmetic operators, including those shown here.
Here is the last line in the program: System.out.println("y contains: " + y); It displays the string "y contains: " followed by the value of y, which is 12.
Two Control Statements Inside a method, execution proceeds sequentially from one statement to the next, top to bottom. However, it is possible to alter this flow through the use of various program control statements. Java provides a rich set of such statements. We will examine two here: the if and the for.
The if Statement You can selectively execute part of a program through the use of Java's conditional statement: the if. The Java if statement works much like the IF statement in any other language. Its simplest form is shown here:
Here, condition is an expression that evaluates to either true or false. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed. Here is an example: if(10 < 11) System.out.println("10 is less than 11"); In this case, since 10 is less than 11, the conditional expression is true, and println( ) will execute. However, consider the following. if(10 < 9) System.out.println("This won't be displayed."); In this case, 10 is not less than 9 and the condition is false. Thus, the call to println( ) will not take place. Java defines a full complement of relational operators that can be used in a conditional expression. They are shown here.
Notice that the test for equality is the double equal sign. Here is a program that demonstrates the if statement. /* The output is shown here. a is not equal to b
The for Loop You can repeatedly execute a sequence of code by creating a loop. Java supplies a powerful assortment of loop constructs. The one we will look at here is the for loop. The simplest form of the for loop is shown here:
The initialization portion of the loop sets a loop control variable to an initial value. The condition is an expression that tests the loop control variable. If the outcome of that test is true, statement is executed and the for loop continues to iterate. If it is false, the loop terminates. The itr-expr expression determines how the loop control variable is changed each time the loop iterates. Here is a program that demonstrates the for loop. It counts from 0 to 4. /* The output generated by the program is shown here: This is x: 0 In this example, x is the loop control variable. It is set to zero in the initialization portion of the for. At the start of each iteration (including the first one), the conditional test x < 5 is performed. If the outcome of this test is true, the println( ) statement is executed, and then x is increased by one. This process continues until the conditional test is false, at which point execution picks up at the bottom of the loop. As a point of interest, in professionally written Java programs you will almost never see the iteration expression of the loop written as shown in the preceding program. That is, you will seldom see statements like this: x = x + 1; The reason is that Java includes a special increment operator that performs this operation more efficiently. The increment operator is ++ (that is, two plus signs back to back). The increment operator increases its operand by one. By use of the increment operator, the preceding statement can be written like this: x++; Thus, the for in the preceding program will usually be written like this: for(x = 0; x < 5; x++) You might want to try this. As you will see, the loop still runs exactly the same as it did before. Java also provides a decrement operator, which is specified as – –. This operator decreases its operand by one.
Create a Code Block Another key element of Java is the code block. A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for Java's if and for statements. Consider this if statement: if(w < h) { Here, if w is less than h, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The important point here is that whenever you need to logically link two or more statements, you do so by creating a block.
Putting It All Together Although you only know a little about Java at this point, you can still use it to write a useful program. The following program creates a table of conversions from gallons to liters, beginning with 1 gallon and ending at 99 gallons. This is accomplished through the use of a for loop. After every 10 conversions, it outputs a blank line. This is handled by an if statement that examines the value of a variable called count. After each conversion is displayed, the value of count is incremented. If it equals 10, a blank line is output and count is reset. Notice that the targets of the for loop and the if statement are blocks of code. /* Here is a portion of the output. 1 gallons is 3.7854 liters.
A Short Word About Object-Oriented Programming As explained earlier, the class is Java's basic unit of program functionality. However, it is more than that. It is also Java's foundation for object-oriented programming (OOP). Although Java's object-oriented features are beyond the scope of this article, they are an important part of Java programming because Java is an object-oriented programming language. OOP is based on three key principles: encapsulation, inheritance, and polymorphism. Encapsulation binds together code and data, inheritance is the mechanism by which one class can inherit the functionality of another, and polymorphism lets you define one interface that describes a general set of actions. These attributes work together in a powerful way that enables the construction of reliable, reusable, and extensible programs. As you advance in your study of Java, you will see how the object-oriented features play an integral role in the way that Java code is written.
Continuing Your Study of Java This short introduction to Java has shown you some of the key elements of the language, including the general form of a Java program, variables, two control statements, and code blocks. Of course, we have only scratched the surface of this rich language. To continue your study of Java, consider Java: A Beginner's Guide. |
|