Copyright ©1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290 or at support@mcp .com.

Notice: This material is excerpted from Special Edition Using Java, ISBN: 0-7897-0604-0. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.

Chapter 7 - The Parts of the Language

by Jay Cross

Now that you have installed Java, and learned about its security features, the next step is to learn the Java language. If you are an experienced C or C++ programmer, most parts of this language will seem very familiar. C programmers will need to adjust to the object paradigm, but Java uses it about as simply as has ever been expressed. Otherwise, it will still be fairly simple; Java has few extraneous features.

In this chapter, an overview of the parts of the language is presented. In subsequent chapters more detailed views of these parts is presented. These parts are given in seven categories: Tokens, Types, Expressions, Statements, Classes, Interfaces, and Packages,. From these parts ideas can be expressed in Java as applications or applets.

In this chapter, you will learn:

Looking from the largest to the smallest, Java applets and applications import prepackaged utilities from Packages such as Graphics, or widgets. (Java's equivilent to libraries or class libraries). Packages are made up of classes and interfaces (the self-contained units which may be imported) The java awt package has class definitions for Graphics, Color, Font, and many more. A class is defined by a declaration and a block of statements, as seen in the ubiquitous HelloWorld examples.Most statements contain expressions. Expressions describe what is done with types of data (such as "2 * Radius * Pi" ) ; and tokens are the characters and groups of characters which the compiler recognizes for building up expressions and statements.

Fig 7.1
(a.) Java applications and applets are classes, which may uses classes and interfaces imported from packages. (b.) Java classes are defined using a block of statements. (c.) Java statements can contain expressions of compatible types. (d.) Java statements and expressions are built using tokens.

These parts are described from the most basic to the highest level.

Tokens

For a compiler to convert a human readable file to machine instructions, it must first determine what tokens or symbols are expressed in the code. This is true for any computer language. By analogy, the same idea can be applied to human language and philosophy.

When Java code is fed to the Java Compiler (javac), it parses it into individual tokens. In Java, as with most computer languages, there are five types of tokens: identifiers, keywords, literals, operands, and separators. Java code may also contain comments and white space (spaces, tabs, and line feeds), which are a great aid to human readability, but do not affect the interpretation of the application or applet. See table 7.1.

javac,is described in Chapter 5.
Table 7.1 The types of tokens in the Java Language.
Options Description Examples
Keyword words that are an essential part of the language definition. public, class, static, void, String, else, if, synchronized, this, while
Identifier names for classes, objects, variables, constants, labels, methods, etc. Composed of unicode alpha-numerics, with the first character being a non-numeric. HelloWorld, main, args, System, out, println, j, n32e20
Literal used for entering explicit values for variables or constants. These may be numeric, boolean, character, or strings. "Hello World", 6, 257L, 7Ex,6.0225e+23d, true
Separator symbols used to indicate where groups of code are divided and arranged. ( ) { } [ ] ; , .
Operator characters and combinations of characters which identify an operation to be done on one or more variables or constants. +, -, *, /, <<, >>,
White Space non-meaningful characters which may be placed between any of the above in any order of quantity. Used to add clarity to the appearance of the source code [space], [tab], [end-of-line],[formfeed]
Comment further aid an abet the conveying of meaning of the source code to human readers. // Comment until the next end-of-line /* Embedded comment */

Java code uses the 16-bit Unicode character set (Not 8-bit ASCII). This allows the use of alphabets other than the Latin/English one. The compiler expects Unicode. All literals are in Unicode. When however, when javac is done, the result is in the form of machine-independent Java bytecode.

More details about the individual token types, plus comments and white space, will be given in Chapter 9.

Types

Type for a computer language refers to how a primitive object (i.e. a variable) is represented in the computers storage facilities. It also usually has ramifications pertaining to what operations can be one with it, and to it. For example many computer languages forbid direct arithmetic operations on a character string, unless there is an implied instruction to first attempt to convert the string to a number.

Java has eight primitive types, including six numeric types plus one Boolean, and one character type. Java also allows arrays of any of these types which are described briefly in table 7.2 below.

Table 7.2 Primitive data types in the Java language
Type Description
byte 8 bit two's-compliment integer with values between -27 and 27-1 (-128 and 127)
short 16 bit two's-compliment integer with values between -215 and 215-1 (-32,768 and 32,767)
int 32 bit two's-compliment integer with values between -231 and 231-1 (-2,147,483,648 and 2,147,483,647)
long 64 bit two's-compliment integer with values between -263 and 263-1 (+/- 9.2 x 1018 , roughly the number of stars in 10 million large galaxies, or the number of bits in 3 million uncompressed HDTV feature length movies)
float 32 bit single precision floating point numbers using the IEEE 754-1985 standard (+/- about 1039)
double 64 bit double precision floating point numbers using the IEEE 754-1985 standard. (+/- about 10317)
char 16 bit Unicode characters. For alpha-numerics, these are the same as ASCII with the high byte set to 0.
boolean These have values of either true or false.

None of the numeric types are unsigned. This is one way in which Java is different from C or C++. This helps to simplify the usage of the language, and eliminates a subtle variety of errors that has plagued C programmers for decades. Of the six numeric types, there are four integer types: byte (8-bit signed), short (16-bit signed), int (32-bit signed) , and long (64-bit signed), and two floating point types: float (32-bit) and double (64-bit). Note that literal floating point expressions (such as 3.14159) are interpreted by default to be of type double.

Boolean variables are type boolean, and have values of true or false. These types cannot have integer operations done to them, or have values other than true or false. C or C++ programmers may have seen booleans as a typedef in their local programming environment. Java has no typedef statement.

As stated above in the overview of tokens, characters in Java store 16-bit Unicode values, not the 8-bit ASCII that C and C++ programmers are familiar with. For the most part this should not result in much of an adjustment; it means that strings take up twice as much space, and that internationalization is easier.

Types are examined in more detail in Chapter 10.

Expressions

Expressions in Java are very similar to expressions in C or C++. They express a value either directly, or by being a means of computing the value; or they can be control-flow expressions, which express the sequence of program execution. These expressions can include constants, variables, keywords, operators and other expressions. Some valid Java expressions are:

7
3.141592654
2^32 -1
3*i
(14-i) * (3+j)
(i>64) && (i<73)
j++
k<<7
(k>128) ? true : false

Java does not support the creation of compound statements using the comma operator, except within the initialization and continuation clauses of loop statements.

Thus:

k=25, j=36;

is not by itself a valid statement, but it may be included in the initialization (or continuation) clause of a loop:

for (k=25, j=36; j+k < 65; j++, k++) {
// statements in the loopà
}

The lists of keywords and operators are presented in Chapter 9.

Statements

Statements in Java are similar to statements in C or C++, and to a lesser degree like many other computer languages such as Pascal, Ada, Basic, Fortran, and Cobol. Statements are executed in sequence (except as described by control-flow statements, or exception statements). They are executed for their effect, and do not of themselves have any value.

Java has several different types of statements as described below in table 7.3, namely:

Table 7.3 Types of statements in the Java language.
Empty Statement These do nothing, and may be useful during program development as a place holder. This is the same as in C and C++.
Labeled Statement Any statement may begin with a label. Such labels must not be a keyword, an already declared local variable, or a previously used label in this module. Except for their use with Jump statements, labels are identical to their C and C++ counterparts. Labels in Java may be used as the arguments of Jump statements listed below.
Expression Statement Most statements are expression statements. The Java language specification lists seven types of Expression statements: Assignment, Pre-Increment, Pre-Decrement, Post-Increment, Post-Decrement, Method Call, Allocation Expression.
Selection Statement These choose one of several control flows. Like C and C++, there are three types of selection statements in Java: if, if-else, switch-case-default.
Iteration Statement These specify how and when looping will take place. There are three types of Iteration statements, which, except for jumps and labels are identical to their C and C++ counterparts: while, do, for.
Jump Statement Jump Statements pass control to the beginning, or end of the current block, or to a labeled statement. Note that there is no goto statement in Java. The optional label argument on the break and continue statements are not part of C or C++. Such labels must be in the same block, and continue labels must be on an iteration statement. These statements have implications for synchronization statements in the block as well. The four types of Jump statement are: break, continue, return, throw. Throw statements are an important part of the exception mechanism.
Synchronization Statement These are used used for handling issues with multi-threading. The synchronized and threadsafe keywords are used to mark variables which may or may not require locks against simultaneous use.
Guarding Statement Guarding statements are used for safe handling of code which may cause exceptions (such as divide by zero). These statements use the try, catch, and finally keywords.
Unreachable Statement These generate an error at compile time.
The details and nature of these statements are presented in Chapter 14.

Classes

In the context of computer languages, classes are a piece of the object paradigm. If you are familiar with the world of Object Oriented programming, you will find Java refreshingly simple. If you are not, you will need to learn the object paradigm if you are going to use Java. Java is purely Object Oriented. You cannot write a procedural program in Java.

It is beyond the scope of this book to teach object oriented programming. However, here are a few notes that should be enough to get you started.

Take a look at the Hello World example; the whole program is the definition of a trivial object:

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

The hello world example does so little that it shows very little about how a class is defined. It does show that a class that does something can be created with five lines of code (two of which are closing curly braces).When compiled with javac, it creates a file called HelloWorld.class which has the class expressed as machine independent byte-codes which Java can execute on any machine on which it resides. Later class examples will show instance variables, static members, inheritance, and methods including creators and destructors.Classes are to objects as types are to variables. A variable is an instance of a type (for example a place in memory which the compiler is told contains a byte, has the value 0000 0110 in it. This instance of a byte has the value 6.) An object is a instance of a class. The hello world example creates a definition of a class, which when run, creates an object, which writes the text, "Hello World" to the screen.

Classes are different from types in many ways. They can be composed of a mixed assortment of types and other classes. They can inherit properties from parent classes. They can have operations (called Methods in the object paradigm) as part of their definition. Perhaps most importantly, it is the definition of these classes which is the job of the programmer.

C programmers often consider classes to be like structure definitions, in which the structure may contain procedures that pertain to the data in the structure. People experienced with relational databases can consider a class to be like a table, with the tables columns being like the classes instance variables and the tables triggers being like the classes methods. In neither case is the correlation perfect, but it is a good place to start.

Traditionally, teachers of the object paradigm like to describe a class as a template, from which objects are created. Also, from such a template, a more specific class may be defined. For instance, we might imagine a class which is describes a room. This class might have features for dimensions, and for methods for placement of windows, doors, sockets, lights, etc. This class might work well for describing offices and bedrooms, but you may want to extend the class definition for describing a kitchen or bathroom with methods for placement of other fixtures. See figure 7.2.

Fig. 7.2
In this figure we see a room of a hypothetical class 'Room' on the left. It has the simple features of a room. On the right we see a room from a child class of 'Room'. In this case the child class is 'BathRoom'. It has the extra features of a bathtub, and other fixtures.
Classes are discussed in much more detail in Chapter 11 and in the Language Grammar appendix

Classes are discussed in much more detail in a chapter 11.

Interfaces

There is no multiple inheritance in Java. Object oriented programming relies on the creation of subclasses from broad parent classes. For example you could imagine that Class TwoDoorSedan could be a subclass of Class Car. It inherits properties from Class Car, and has some properties of its own that Car does not have. In C++ and some other Object Oriented Languages, an allowance was made for inheriting properties from two distinct parent Classes. For example Class AmphibiousCar might inherit from Class Car, and from Class MotorBoat. This is called multiple inheritance. Readers familiar with C++ are well aware that multiple inheritance makes Object Oriented programming more complex.

Java's creators knew about the value of multiple inheritance, but found a simpler way to fill the same needs, while introducing much less ambiguity and general doubt about usage. It is known as an interface. An interface is a collection of methods declarations and constants that one or more Classes of Objects will use. Interfaces cannot contain variables or code to specifically implement any method.

With a bit of a change in how you define it, Interfaces allow making the Class AmphibiousCar inherit from both Class MotorBoat and Class Car, because (you may imagine) there may need to be both motorboat-like and car-like variables in the class (e.g. TireSize (from Car) and GunwaleLength (from MotorBoat)). Real programming examples that can't be done just as easily with the interface construct are proving very rare.

Commonly seen examples of interfaces tend to be lists of methods for printing or acquiring data, for specifying how forms will look on the screen, and for defining how classes might deal with some contained feature such as images, or bodies of text.

Getting back to the AmphibiousCar: in Java, an inexperienced programmer might let the Class AmphibiousCar inherit from either Car or MotorBoat, and the other features (MotorBoat-like or Car-like) would need to be built in to the subclass and maintained there to imitate the features of non-inherited class. This would result in maintenance trouble. Clever programmers, anticipating this rare object duality could create the parent classes using interfaces to specify the common methods for each. Then, the AmphibiousCar class would have a list of methods that need to be implemented, and javac would point out when some feature had not been fleshed out.

Listing 7.1 An example to demonstrate using interfaces for multiple inheritance.
Interface WheeledVehicle {
        String GetTireSize();
        int GetNumberOfTires();
}
Interface FloatingVehicle {
        int GetGunwaleLength();
        int GetTransomStrength();
}
Class Car Implements WheeledVehicle {
        protected String TireSize;
        protected int NumberOfTires;
        // note many necessary methods not included, see chaps 11 & 12.
        public String GetTireSize() {
                return TireSize;
        }
        public int GetNumberOfTires() {
                return NumberOfTires;
        }
}
Class AmphibiousCar extends Car Implements FloatingVehicle {
        protected int GunwaleLength;
        protected int TransomStrength;
        // note many necessary methods not included, see chaps 11 & 12.
        public int GetGunwaleLength() {
                return GunwaleLength;
        }
        public int GetTransomStrength() {
                return TransomStrength;
        }
}

In the above example, the keyword "implements" is used to identify a list (in these cases a one element list) of interfaces used by the class.

Interfaces are a simple but important part of the Java language, and are discussed less fancifully, and in much more detail in chapter 12.

Packages

Packages in Java are groups of Classes. These are like libraries in many computer languages. A package of Java classes typically will contain related classes. From the above fanciful examples we can imagine a package called Transportation, which would have numerous Classes defined in it such as Car, Boat, Airplane, Train, Rocket, AmphibiousCar, SeaPlane, etc. Applications that deal with items of this sort might benefit from importing our imaginary Transportation Package. This is done by a line which must come before the definition of any class in the file, as follows:

// FILE: TravelAgencyApp.java
import Transportation.*;
// à the import statement having been demonstrated, 
//   the rest of the Application is omitted.
// End of File

While a package may contain many classes (related or not), each file that goes into creating a Package may contain at most one public Class definition. The package statement at the beginning of the file tells Java that this class is part of a package, as follows:

// FILE: Car.java
package Transportation;
// à definition of the Car Class
// End of File
// FILE: Boat.java
package Transportation;
// à definition of the Boat Class
// End of File

Note that you do not need to import a package to use classes in a package, but doing so affords a short-hand way to refer to classes defined in the package. Specifically, in the above example, if the Package was not imported, to create an object of Class Car, you would need to write:

new Transportation.Car()

Whereas if the Transportation package was imported you could write:

new Car()

Packages are more than just a shortcut. They are a way of keeping things organized.

Java comes with a built-in set of packages:

Table 7.4 Standard Java packages.
Package Description
java.applet contains classes needed to create Java applets that will run under Netscape 2.0 (or greater), HotJava, or other Java-compatible browsers.
java.awt contains classes helpful in writing platform-independent Graphic User Interface (GUI) applications. This comes with several subpackages including java.awt.peer, and java.awt.image.
java.io contains classes for doing I/O (input & output). This is where the data stream classes are kept.
java.lang contains the essential Java classes. It is implicitly imported, so you don't need to.
java.net contains the classes used for making network connections. These are used in tandem with java.io for reading and writing data from the network.
java.util contains the leftovers, such as encoding, decoding, vectors, stacks, etc.

Additional packages are doubtlessly available commercially.

QUE Home Page

For technical support for our books and software contact support@mcp.com

Copyright ©1996, Que Corporation