Section 1.4. Java Language Elements


[Page 33 (continued)]

1.4. Java Language Elements

In this section we will introduce some of the key elements of the Java language by describing the details of a small program. We will look at how a program is organized and what the various parts do. Our intent is to introduce important language elements, many of which will be explained in greater detail in later sections.

The program we will study is a Java version of the traditional HelloWorld program"traditional" because practically every introductory programming text begins with it. When it is run, the HelloWorld program (Fig. 1.5) displays the greeting "Hello World!" on the console.

Figure 1.5. The HelloWorld application program.
(This item is displayed on page 34 in the print version)

 /*   * File: HelloWorld.java   * Author: Java Java Java   * Description: Prints Hello World greeting.   */ public class HelloWorld extends Object         // Class header {                                              // Start class body   private String greeting = "Hello World!";   public void greet()                          // Method definition   {                                            // Start method body       System.out.println(greeting);            // Output statement   } // greet()                                 // End method body  public static void main(String args[])        // Method header  {    HelloWorld helloworld;                      // declare    helloworld = new HelloWorld();              // create    helloworld.greet();                         // Method call   } // main() } // HelloWorld class                          // End class body 

Grace Hopper and the First Computer Bug

Rear Admiral Grace Murray Hopper (19061992) was a pioneer computer programmer and one of the original developers of the COBOL programming language, which stands for COmmon Business-Oriented Language. Among her many achievements and distinctions, Admiral Hopper also had a role in coining the term computer bug.

Photograph courtesy of Naval Visual News Service

In August 1945, she and a group of other programmers were working on the Mark I, an electro-mechanical computer developed at Harvard that was one of the ancestors of today's electronic computers. After several hours of trying to figure out why the machine was malfunctioning, someone located and removed a two-inch moth from one of the computer's circuits. From then on whenever anything went wrong with a computer, Admiral Hopper and others would say "it had bugs in it." The first bug itself is still taped to Admiral Hopper's 1945 log book, which is now in the collection of the Naval Surface Weapons Center.

In 1991, Admiral Hopper was awarded the National Medal of Technology by President George H.W. Bush. To commemorate and honor Admiral Hopper's many contributions, the U.S. Navy recently named a warship after her. For more information on Admiral Hopper, see the Web site at

http://www.chips.navy.mil



[Page 34]

1.4.1. Comments

The first thing to notice about the HelloWorld program is the use of comments. A comment is a nonexecutable portion of a program that is used to document the program. Because comments are not executable instructions, they are ignored by the compiler. Their sole purpose is to make the program easier for the programmer to read and understand.

The HelloWorld program contains examples of two types of Java comments. Any text contained within /* and */ is considered a comment. As you can see in HelloWorld, this kind of comment can extend over several lines and is sometimes called a multiline comment. A second type of comment is any text that follows double slashes (//) on a line. This is known as a single-line comment because it cannot extend beyond a single line.

When the compiler encounters the beginning marker (/*) of a multiline comment, it skips over everything until it finds a matching end marker (*/). One implication of this is that it is not possible to put one multiline comment inside of another. That is, one comment cannot be nested, or contained, within another comment. The following code segment illustrates the rules that govern the use of /* and */:

/* This first comment begins and ends on the same line. */ /* A second comment starts on this line ...     and goes on ...     and this is the last line of the second comment. */ /* A third comment starts on this line ...      /* This is NOT a fourth comment. It is just         part of the third comment.     And this is the last line of the third comment. */ */  This is an error because it is an unmatched end marker. 



[Page 35]

As you can see from this example, it is impossible to begin a new comment inside an already-started comment because all the text inside the first comment, including /*, is ignored by the compiler.

Java Language Rule: Comments

Any text contained within /* and */, which may span several lines, is considered a comment and is ignored by the compiler. Inserting double slashes (//) into a line turns the rest of the line into a comment.


Multiline comments are often used to create a comment block that provides useful documentation for the program. In HelloWorld, the program begins with a comment block that identifies the name of the file that contains the program and its author, and provides a brief description of what the program does.

For single-line comments, double slashes (//) can be inserted anywhere on a line of code. As a result, the rest of the line is ignored by the compiler. We use single-line comments throughout the HelloWorld program to provide a running commentary of its language elements.

Single-line comment


Java Programming Tip: Use of Comments

A well-written program should begin with a comment block that provides the name of the program, its author, and a description of what the program does.


1.4.2. Program Layout

Another thing to notice about the program is how neatly it is arranged on the page. This is done deliberately so that the program will be easy to read and understand. In Java, program expressions and statements may be arranged any way the programmer likes. They may occur one per line, several per line, or one per several lines. But the fact that the rules governing the layout of the program are so lax makes it all the more important that we adopt a good programming style, one that will help make programs easy to read.

So look at how things are presented in HelloWorld. Note how beginning and ending braces, { and }, are aligned, and note how we use single-line comments to annotate ending braces. Braces are used to mark the beginning and end of different blocks of code in a Java program. It can sometimes be difficult to know which beginning and end braces are matched up. Proper indentation and the use of single-line comments make it easier to determine how the braces are matched up.

Similarly, indentation is used to show when one element of the program is contained within another element. Thus, the elements of the HelloWorld class are indented inside the braces that mark the beginning and end of the class. And the statements in the main() method are indented to indicate that they belong to that method. Use of indentation in this way, to identify the program's structure, makes the program easier to read and understand.

Java Programming Tip: Use of Indentation

Indent the code within a block, and align the block's opening and closing braces. Use a comment to mark the end of a block of code.



[Page 36]

1.4.3. Keywords and Identifiers

The Java language contains 50 predefined keywords (Table 1.1). These are words that have special meaning in the language and whose use is reserved for special purposes. For example, the keywords used in the HelloWorld program (Fig. 1.5) are: class, extends, private, public, static, and void.

Table 1.1. Java keywords.

abstract

continue

for

new

switch

assert

default

goto

package

synchronized

boolean

do

if

private

this

break

double

implements

protected

throw

byte

else

import

public

throws

case

enum

instanceof

return

transient

catch

extend

int

short

TRy

char

final

interface

static

void

class

finally

long

strictfp

volatile

const

float

native

super

while


Because their use is restricted, keywords cannot be used as the names of methods, variables, or classes. However, the programmer can make up names for the classes, methods, and variables that occur in a program, provided that certain rules and conventions are followed.

The names for classes, methods, and variables are called identifiers, and they follow certain syntax rules:

Java Language Rule: Identifier

An identifier must begin with a capital or lower-case letter and may be followed by any number of letters, digits, underscores (_), or dollar signs ($). An identifier may not be identical to a Java keyword.


Identifier syntax


Names in Java are case sensitive, which means that two different identifiers may contain the same letters in the same order. For example, thisVar and ThisVar are two different identifiers.

In addition to the syntax rule that governs identifiers, Java programmers follow certain style conventions in making up names for classes, variables, and methods. By convention, class names in Java begin with a capital letter and use capital letters to distinguish the individual words in the namefor example, HelloWorld and TextField. Variable and method names begin with a lowercase letter but also use capital letters to distinguish the words in the namefor example, main(), greeting, greet(), getQuestion(), and getAnswer(). The advantage of this convention is that it is easy to distinguish the different elements in a programclasses, methods, variablesjust by how they are written. (For more on Java style conventions, see Appendix A.).

Identifier style


Java naming conventions


Another important style convention followed by Java programmers is to choose descriptive identifiers when naming classes, variables, and methods. This helps to make the program more readable.

Java Programming Tip: Choice of Identifiers

To make your program more readable, choose names that describe the purpose of the class, variable, or method.



[Page 37]

1.4.4. Data Types and Variables

A computer program wouldn't be very useful if it couldn't manipulate different kinds of data, such as numbers and strings. The operations that one can do on a piece of data depend on the data's type. For example, you can divide and multiply numbers, but you cannot do this with strings. Thus, every piece of data in a Java program is classified according to its data type.

Broadly speaking, there are two categories of data in Java: various types of objects and eight different types of built-in primitive data types. In addition to new types of objects that are created by programmers, Java has many different types of built-in objects. Two types that we will encounter in this chapter are the String and PrintStream objects. Java's primitive types include three integer types, three real-number types, a character type, and a boolean type with values true and false. The names of the primitive types are keywords like int for one integer type, double for one real-number type, and boolean.

Primitive types


As we noted in Chapter 0, a variable is a named storage location that can store a value of a particular type. Practically speaking, you can think of a variable as a special container into which you can place values, but only values of a certain type (Fig. 1.6). For example, an int variable can store values like 5 or -100. A String variable can store values like "Hello." (Actually, this is not the full story, which is a little more complicated, but we will get to that in Chapter 2.)

Figure 1.6. Variables are like typed containers.


In the HelloWorld class, the instance variable greeting (line 8) stores a value of type String. In the main() method, the variable helloworld is assigned a HelloWorld object (line 16).

A literal value is an actual value of some type that occurs in a program. For example, a string enclosed in double quotes, such as "Hello World!," is known as a String literal. A number such as 45.2 would be an example of a literal of type double, and -72 would be an example of a literal of type int. Our HelloWorld program contains just a single literal value, the "Hello World!" String.

1.4.5. Statements

A Java program is a collection of statements. A statement is a segment of code that takes some action in the program. As a program runs, we say that it executes statements, meaning that it carries out the actions specified by these statements. In our HelloWorld program, statements of various types occur on lines 8, 11, 15, 16, and 17. Note that all of these lines end with a semicolon. The rule in Java is that statements must end with a semicolon. Omitting the semicolon would cause a syntax error.

Executing a program


A declaration statement is a statement that declares a variable of a particular type. In Java, a variable must be declared before it can be used in a program. Failure to declare it would cause a syntax error. In its simplest form, a declaration statement begins with the variable's type, which is followed by the variable's name, and ends with a semicolon:


[Page 38]


Type VariableName ;

Declaration statement


A variable's type is either one of the primitive types we mentioned, such as int, double, or boolean, or, for an object, it is the name of the object's class, such as String or HelloWorld. A variable's name may be any legal identifier, as defined earlier, although the convention in Java is to begin variable names with a lowercase letter. In our HelloWorld program, an example a simple declaration statement occurs on line 15:

HelloWorld helloworld; 


This example declares a variable for an object. The variable's name is helloworld, and its type is HelloWorld, the name of the class that is being defined in our example. To take another example, the following statements declare two int variables, named int1 and int2:

int int1; int int2; 


As we noted, an int is one of Java's primitive types and the word int is a Java keyword.

Without going into too much detail at this point, declaring a variable causes the program to set aside enough memory for the type of data that will be stored in that variable. So in this example, Java would reserve enough space to store an int.

An assignment statement is a statement that stores (assigns) a value in a variable. An assignment statement uses the equal sign (=) as an assignment operator. In its simplest form, an assignment statement has a variable on the left-hand side of the equals sign and some type of value on the right-hand side. Like other statements, an assignment statement ends with a semicolon:


VariableName = Value ;

When it executes an assignment statement, Java will first determine what value is given on the right-hand side and then assign (store) that value to (in) the variable on the left-hand side. Here are some simple examples:

greeting = "Hello World"; num1 = 50;        // (a) Assign 50 to num1 num2 = 10 + 15;   // (b) Assign 25 to num2 num1 = num2;      // (c) Copy num2's value (25) into num1 



[Page 39]

In the first case, the value on the right-hand side is the string literal "Hello World!," which gets stored in greeting. Of course, greeting has to be the right type of containerin this case, a String variable. In the next case, the value on the right-hand side is 50. So that is the value that gets stored in num1, assuming that num1 is an int variable. The situation after this assignment is shown in the top drawing in Figure 1.7. In the third case, the value on the right-hand side is 25, which is determined by adding 10 and 15. So the value that gets assigned to num2 is 25. After this assignment we have the situation shown in the middle drawing in the figure. Of course, this assumes that num2 is an int variable. In the last case, the value on the right-hand side is 25, the value that we just stored in the variable num2. So 25 gets stored in num1. This is the bottom drawing in the accompanying figure.

Figure 1.7. This illustrates how the state of the variables num1 and num2 changes over the course of the three assignments, (a), (b), (c), given in the text.


The last of these examples

num1 = num2;   // Copy num2's value into num1 


can be confusing to beginning programmers, so it is worth some additional comment. In this case, there are variables on both the left and right of the assignment operator. But they have very different meaning. The variable on the right is treated as a value. If the variable is storing 25, then that is its value. In fact, whatever occurs on the right-hand side of an assignment operator is treated as a value. The variable on the left-hand side is treated as a memory location. It is where the value 25 will be stored as a result of executing this statement. The effect of this statement is to copy the value stored in num2 into num1, as illustrated in Figure 1.8.

Figure 1.8. In the assignment num1 = num2;, num2's value is copied into num1.



[Page 40]

Java has many other kinds of statements, and we will be learning about them in subsequent examples. The following examples from the HelloWorld program are examples of statements in which a method is called:

System.out.println(greeting); // Call println() method helloworld.greet();           // Call greet() method 


We will discuss these kinds of statements in greater detail as we go along. One final type of statement that should be mentioned at this point is the compound statement (or block), which is a sequence of statements contained within braces {}. We see three examples of this in the HelloWorld program. The body of a class definition extends from lines 7 through 19. The body of the greet() method is a block that extends from line 10 through line 12. The body of the main() method is a block that extends from line 14 to 19.

1.4.6. Expressions and Operators

The manipulation of data in a program is done by using an expression of some kind that specifies the action. An expression is Java code that specifies or produces a value in the program. For example, if you want to add two numbers, you would use an arithmetic expression, such as num1 + num2. If you want to compare two numbers, you would use a relation expression, such as num1 < num2. As you can see, these and many other expressions in Java involve the use of special symbols called operators. Here we see the addition operator (+) and the less-than operator (<). We have already talked about the assignment operator (=).

Java expressions and operators have a type that depends on the type of data that is being manipulated. For example, when adding two int values, such as 5 + 10, the expression itself produces an int result. When comparing two numbers with the less than operator, num1 < num2, the expression itself produces a boolean type, either true or false.

It is important to note that expressions cannot occur on their own. They occur as part of the program's statements. Here are some additional examples of expressions:

num = 7         // An assignment expression of type int num = square(7) // An method call expression of type int num == 7        // An equality expression of type boolean 


The first of these is an assignment expression. It has a value of 7, because it is assigning 7 to num. The second example is also an assignment expression, but this one has a method call, square(7), on its right-hand side. (We can assume that a method named square() has been appropriately defined in the program.) A method call is just another kind of expression. In this case, it has the value 49. Note that an assignment expression can be turned into a standalone assignment statement by placing a semicolon after it.

The third expression is an equality expression, which has the value true, assuming that the variable on its left is storing the value 7. It is important to note the difference between the assignment operator (=) and the equality operator (==).


[Page 41]

Java Language Rule: Equality and Assignment

Be careful not to confuse = and ==. The symbol = is the assignment operator. It assigns the value on its right-hand side to the variable on its left-hand side. The symbol == is the equality operator. It evaluates whether the expressions on its left- and right-hand sides have the same value and returns either TRue or false.


Self-Study Exercises

Exercise 1.1

What is stored in the variable num after the following two statements are executed?

int num = 11; num = 23 - num; 


Exercise 1.2

Write a statement that will declare a variable of type int called num2, and store in it the sum of 711 and 712.

1.4.7. Class Definition

A Java program consists of one or more class definitions. In the HelloWorld example, we are defining the HelloWorld class, but there are also three predefined classes involved in the program. These are the Object, String, and System classes all of which are defined in the Java class library. Predefined classes, such as these, can be used in any program.

As the HelloWorld program's comments indicate, a class definition has two parts: a class header and a class body. In general, a class header takes the following form, some parts of which are optional (opt):


          ClassModifiersopt   class   ClassName   Pedigreeopt

Class header


The class header for the HelloWorld class is:

public class HelloWorld extends Object 


The purpose of the header is to give the class its name (HelloWorld), identify its accessibility (public as opposed to private), and describe where it fits into the Java class hierarchy (as an extension of the Object class). In this case, the header begins with the optional access modifier, public, which declares that this class can be accessed by any other classes. The next part of the declaration identifies the name of the class, HelloWorld. And the last part declares that HelloWorld is a subclass of the Object class. We call this part of the definition the class's pedigree.

As you will recall from Chapter 0, the Object class is the top class of the entire Java hierarchy. By declaring that HelloWorld extends Object, we are saying that HelloWorld is a direct subclass of Object. In fact, it is not necessary to declare explicitly that HelloWorld extends Object because that is Java's default assumption. That is, if you omit the extends clause in the class header, Java will automatically assume that the class is a subclass of Object.

The class's body, which is enclosed within curly brackets {}, contains the declaration and definition of the elements that make up the objects of the class. This is where the object's attributes and actions are defined.

Class body



[Page 42]

1.4.8. Declaring an Instance Variable

There are generally two kinds of elements declared and defined in the class body: variables and methods. As we described in Chapter 0, an instance variable is a variable that belongs to each object, or instance, of the class. That is, each instance of a class has its own copies of the class's instance variables. The HelloWorld class has a single instance variable, (greeting), which is declared as follows:

private String greeting = "Hello World!"; 


In general, an instance variable declaration has the following syntax, some parts of which are optional:


          Modifiersopt  Type  VariableName  InitializerExpressionopt

Thus, a variable declaration begins with optional modifiers. In declaring the greeting variable, we use the access modifier, private, to declare that greeting, which belongs to the HelloWorld class, cannot be directly accessed by other objects. The next part of the declaration is the variable's type. In this case, the greeting variable is a String, which means that it can store a string object. The type is followed by the name of the variable, in this case (greeting). This is the name that is used to refer to this memory location throughout the class. For example, the variable is referred to on line 11, where it is used in a println() statement.

Information hiding


The last part of the declaration is an optional initializer expression. In this example, we use it to assign an initial value, "Hello World!," to the greeting variable.

1.4.9. Defining an Instance Method

Recall that a method is a named section of code that can be called or invoked to carry out an action or operation. In a Java class, the methods correspond to the object's behaviors or actions. The HelloWorld program has two method definitions: the greet() method and the main() method.

A method definition consists of two parts: the method header and the method body. In general, a method header takes the following form, including some parts which are optional:


           Modifiersopt   ReturnType   MethodName   (ParameterListopt)

As with a variable declaration, a method definition begins with optional modifiers. For example, the definition of the greet() method on line 9 uses the access modifier, public, to declare that this method can be accessed or referred to by other classes. The main() method, whose definition begins on line 13, is a special method, and is explained in the next section.

The next part of the method header is the method's return type. This is the type of value, if any, that the method returns. Both of the methods in HelloWorld have a return type of void. This means that they don't return a value of any kind. Void methods just execute the sequence of statements given in their bodies. For an example of a method that does return a value, take a look again at the declaration of the getQuestion() method in the Riddle class, which returns a String (Fig. 1.4).


[Page 43]

The method's name follows the method's return type. This is the name that is used when the method is called. For example, the greet() method is called on line 17.

Following the method's name is the method's parameter list. A parameter is a variable that temporarily stores data values that are being passed to the method when the method is called. Some methods, such as the greet() method, do not have parameters, because they are not passed any information. For an example of a method that does have parameters, see the Riddle() constructor, which contains parameters for the riddle's question and answer (Fig. 1.4).

The last part of method definition is its body, which contains a sequence of executable statements. An executable statement is a Java statement that takes some kind of action when the program is run. For example, the statement in the greet() method,

System.out.println(greeting);   // Output statement 


prints a greeting on the console.

1.4.10. Java Application Programs

The HelloWorld program is an example of a Java application program, or a Java application, for short. An application program is a standalone program"standalone" in the sense that it does not depend on any other program, like a Web browser, for its execution. Every Java application program must contain a main() method, which is where the program begins execution when it is run. For a program that contains several classes, it is up to the programmer to decide which class should contain the main() method. We don't have to worry about that decision for the HelloWorld program because it contains just a single class.

Because of its unique role as the starting point for every Java application program, it is very important that the header for the main method be declared exactly as shown in the HelloWorld class:

public static void main(String args[]) 


It must be declared public so that it can be accessed from outside the class that contains it. The static modifier is used to designate main() as a class method. As you might recall from Chapter 0, a class method is a method associated directly with the class that contains it rather than with the objects of the class. A class method is not part of the class's objects. Unlike instance methods, which are invoked through a class's objects, a class method is called through the class itself. Thus, a class method can be called even before the program has created objects of the class. The special role of main() as the program's starting point requires that it be a class method because it is called by the Java runtime system before the program has created any objects.

Class method


The main() method has a void return type, which means that it does not return any value. Finally, note that main()'s parameter list contains a declaration of a String parameter named args. This is actually an array that can be used to pass string arguments to the program when it is started up. We won't worry about this feature until Chapter 9.


[Page 44]

1.4.11. Creating and Using Objects

The body of the main() method is where the HelloWorld program creates its one and only object. Recall that when it is run, the HelloWorld program just prints the "Hello World!" greeting. As we noted earlier, this action happens in the greet() method. So in order to make this action happen, we need to call the greet() method. However, because the greet() method is an instance method that belongs to a HelloWorld object, we first need to create a HelloWorld instance. This is what happens in the body of the main() method (Fig. 1.5).

The main() method contains three statements:

HelloWorld helloworld;           // Variable declaration helloworld = new HelloWorld();   // Object instantiation helloworld.greet();              // Method invocation 


The first statement declares a variable of type HelloWorld, which is then assigned a HelloWorld object. The second statement creates a HelloWorld object. This is done by invoking the HelloWorld() constructor method. Creating an object is called object instantiation because you are creating an instance of the object. Once a HelloWorld instance is created, we can use one of its instance methods to perform some task or operation. Thus, in the third statement, we call the greet() method, which will print "Hello World!" on the console.

If you look back at the HelloWorld program in Figure 1.5 you won't find a definition of a constructor method. This is not an error because Java will provide a default constructor if a class does not contain a constructor definition. The default constructor is a trivial constructor method"trivial" because its body contains no statements. Here is what the default HelloWorld() constructor would look like:

public HelloWorld() { }  // Default constructor 


Default constructor


For most of the classes we design, we will design our own constructors, just as we did in the Riddle class (Fig. 1.4). We will use constructors to assign initial values to an object's instance variables or to perform other kinds of tasks that are needed when an object is created. Because the HelloWorld object doesn't require any startup tasks, we can make do with the default constructor.

The HelloWorld program illustrates the idea that an object-oriented program is a collection of interacting objects. Although we create just a single HelloWorld object in the main() method, there are two other objects used in the program. One is the greeting, which is a String object consisting of the string "Hello World!" The other is the System.out object, which is a special Java system object used for printing.

Interacting objects


1.4.12. Java Applets

A Java applet is a program that is executed by a Web browser and whose output is embedded within a Web page. Figure 1.9 shows a Java applet named HelloWorldApplet. This program does more or less the same thing as the HelloWorld applicationit displays the "Hello World!" greeting. The difference is that it displays the greeting within a Web page rather than directly on the console.


[Page 45]
Figure 1.9. HelloWorldApplet program.

   /** HelloWorldApplet program */ import java.applet.Applet;                     // Import class names import java.awt.Graphics; public class HelloWorldApplet extends Applet   // Class header {                                              // Start of body      public void paint(Graphics g)             // The paint method      {         g.drawString("Hello World!",10,10);      }                                         // End of paint }                                              // End of HelloWorld 

As in the case of the HelloWorld application program, the HelloWorldApplet consists of a class definition. It contains a single method definition, the paint() method, which contains a single executable statement:

g.drawString("Hello World!",10,10); 


This statement displays the "Hello World!" message directly on a Web page. The drawString() method is one of the many drawing and painting methods defined in the Graphics class. Every Java applet comes with its own Graphics object, which is referred to here simply as g. Thus, we are using that object's drawString() method to draw on the applet window. Don't worry if this seems a bit mysterious now. We'll explain it more fully when we take up graphics examples again.

The HelloWorldApplet also contains some elements, such as the import statements, that we did not find in the HelloWorld application. We will now discuss those features.

1.4.13. Java Library Packages

Recall that the HelloWorld application program used two predefined classes, the String and the System classes. Both of these classes are basic language classes in Java. The HelloWorldApplet program also uses predefined classes, such as Applet and Graphics. However, these two classes are not part of Java's basic language classes. To understand the difference between these classes, it will be necessary to talk briefly about how the Java class library is organized.

A package is a collection of interrelated classes in the Java class library. For example, the java.lang package contains classes, such as Object, String, and System, that are central to the Java language. Just about all Java programs use the classes in this package. The java.awt package provides classes, such as Button, TextField, and Graphics, that are used in graphical user interfaces (GUIs). The java.net package provides classes used for networking tasks, and the java.io package provides classes used for input and output operations.


[Page 46]

All Java classes belong to some package, including those that are programmer defined. To assign a class to a package, you would provide a package statement as the first statement in the file that contains the class definition. For example, the files containing the definitions of the classes in the java.lang package all begin with the following statement:

package java.lang; 


If you omit the package statement, as we do for the programs in this book, Java places such classes into an unnamed default package.

Thus, the full name of any Java class includes the name of the package that contains it. For example, the full name for the System class is java.lang.System, and the full name for the String class is java.lang.String. Similarly, the full name for the Graphics class is java.awt.Graphics. In short, the full name for a Java class takes the following form:


                        package.class

In other words, the full name of any class provides its package name as a prefix.

Of all the packages in the Java library, the java.lang package is the only one whose classes are available by their shorthand names to all Java programs. This means that when a program uses a class from the java.lang package, it can refer to it simply by its class name. For example, in the HelloWorld program we referred directly to the String class rather than to java.lang.String.

1.4.14. The import Statement

The import statement makes Java classes available to programs under their abbreviated names. Any public class in the Java class library is available to a program by its fully qualified name. Thus, if a program was using the Graphics class, it could always refer to it as java.awt.Graphics. However, being able to refer to Graphics by its shorthand name makes the program a bit shorter and more readable.

The import statement doesn't actually load classes into the program. It just makes their abbreviated names available. For example, the import statements in HelloWorldApplet allow us to refer to the Applet and Graphics classes by their abbreviated names (Fig. 1.9).

The import statement takes two possible forms:


                    import package.class

                    import package.*

The first form allows a specific class to be known by its abbreviated name. The second form, which uses the asterisk as a wildcard character ('*'), allows all the classes in the specified package to be known by their short names. The import statements in HelloWorldApplet are examples of the first form. The following example,

import java.lang.*; 


allows all the classes in the java.lang package to be referred to by their class names alone. In fact, this particular import statement is implicit in every Java program.


[Page 47]

1.4.15. Qualified Names in Java

In the preceding subsections we saw several examples of names in Java programs that used dot notation. A qualified name is a name that is separated into parts using Java's dot notation. Examples include package names, such as java.awt, class names, such as java.applet.Applet, and even method names, such as helloworld.greet().

Just as in our natural language, the meaning of a name in a Java program depends on the context. For example, the expression helloworld.greet() refers to the greet() method, which belongs to the HelloWorld class. If we were using this expression from within that class, you wouldn't need to qualify the name in this way. You could just refer to greet() and it would be clear from the context which method you meant.

This is no different than using someone's first name ("Kim") when there's only one Kim around, but using a full name ("Kim Smith") when the first name alone would be too vague or ambiguous.

One thing that complicates the use of qualified names is that they are used to refer to different kinds of things in a Java program. But this is no different, really, than in our natural language, where the same names ("George Washington") can refer to people, bridges, universities, and so on. Here again, just as in our natural language, Java uses the context to understand the meaning of the name. For example, the expression java.lang.System refers to the System class in the java.lang package, whereas the expression System.out.print() refers to a method in the System.out object.

How can you tell these apart? Java can tell them apart because the first one occurs as part of an import statement, so it must be referring to something that belongs to a package. The second expression would only be valid in a context where a method invocation is allowed. You will have to learn a bit more about the Java language before you'll be able to completely understand these names, but the following provide some naming rules to get you started.

Java Language Rule: Library Class Names

By convention, class names in Java begin with an uppercase letter. When referenced as part of a package, the class name is the last part of the name. For example, java.lang.System refers to the System class in the java.lang package.


Java Language Rule: Dot Notation

Names expressed in Java's dot notation depend for their meaning on the context in which they are used. In qualified namesthat is, names of the form X.Y.Zthe last item in the name (Z) is the referentthat is, the element being referred to. The items that precede it (X.Y.) are used to qualify or clarify the referent.


The fact that names are context dependent in this way certainly complicates the task of learning what's what in a Java program. Part of learning to use Java's built-in classes is learning where a particular object or method is defined. It is a syntax error if the Java compiler can't find the object or method that you are referencing.

Debugging Tip: Not Found Error

If Java cannot find the item you are referring to, it will report an "X not found" error, where X is the class, method, variable, or package being referred to.





Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net