Wednesday, June 27, 2007

Chapter 2 - Language Fundamentals

Go to Home Page



Chapter 2:

Language Fundamentals

As you read through this chapter, you should concentrate on the following key items:
. How to identify a Java package . How to import classes and interfaces from other packages . How to create a program's main() method . How to access command-line arguments . How to create valid identifiers . How field variables and arrays are initialized . What the range of each primitive type is . How to create literal values of each primitive type . How to create String literal values

Chapter Introduction

This chapter covers the fundamentals of the Java programming language. If you've written Java programs, you should be familiar with most of the material in this chapter. However, odds are there are a few things that you might not be sure of. The questions on the certification exam will exploit this uncertainty—so pay careful attention to the material that's presented. Make sure that you read through each section, even if you think that you know it cold. The review questions and exam questions will let you know how well you know this material and will give you an idea of how well you will do in exam-related questions.

The Structure of Java Programs

Java programs are composed of declarations of classes and interfaces. Classes define variables, which provide named access to data, methods, which perform actions consisting of operations on the data, and constructors, which create instances of classes, referred to as objects. Data items consist of primitive data values—such as byte, char, and int values—and objects—such as arrays, I/O streams, and GUI elements. Interfaces define collections of methods that are implemented by classes. They are also used to define constants, which are data values that cannot be changed. Java programs are written using one or more compilation units, which are Java source code files. Every source code file consists of the name of a class or interface followed by the .java extension. Since Java identifiers are case-sensitive, source code filenames are also case-sensitive. Each source code file may contain at most one public class or interface. If a class or interface is declared as public, the source code filename must be the name of the class or interface (followed by the .java extension). If a source code file does not contain a public class or interface, it may take on a name that is different from its classes and interfaces.

Identifying Packages

Java classes and interfaces are organized into packages. Packages provide a naming context for classes and interfaces. In other words, packages enable different programmers (or even the same programmer) to create classes and interfaces with the same name. For example, if you and I both create a class named Cool and then use the two different versions of Cool in the same program, the compiler and runtime system won't know which version to use. But, if I put my Cool class in the Mypackage, and you put your
Cool class in the You package, the compiler and runtime system will have no problem, as long as we refer to Cool using its package name. Packages are identified by the package statement. It must appear as the first statement in a source code file
package packageName;
Note Use of Packages In addition to being used as a naming context, packages are
used to organize related classes and interfaces into a single API unit to which
access may be controlled. If a package statement is omitted, the classes and interfaces declared within the package are put into the default no name package. In the Java 2 Platform Software Development Kit (SDK), the package name and the CLASSPATH environment variable are used to find a class or interface that is located in another package.

Importing Classes and Interfaces from Other Packages

The import statement is used to reference classes and interfaces that are declared in other packages (without having to specify their names each time they are referenced). There are three forms of the import statement:
import packageName.className;
import packageName.interfaceName;
import packageName.*;
The first and second forms enable the identified classes and interfaces to be referenced without specifying the name of their package. The third form allows all classes and interfaces in the specified package to be referenced without specifying the name of their package.
The main() Method
The main() method is used as the entry point for a Java application program. All programs must have a main() method or they cannot be run. The main() method is a method of the class that is executed to run the program.

Note Importing java.lang The java.lang package is always imported by default
and does not need to be imported by an import statement. For example, if your program's name is MyProgram, then the MyProgram class must be defined in a file named MyProgram.java. The MyProgram class must have a correctly defined main() method. A correctly defined main() method has the following form:
public static void main(String[] args) {
// Statements go here
} The main() method must be declared as public, static, and void. The void keyword must appear immediately before main(). The public and static keywords may be interchanged. The main() method has one argument—an array of String arguments. This argument may be defined as String[] args or String []args or String args[]. The args argument may use any valid identifier. For example, you can use arg, myArgs, or parms. However, args is standard, and you should probably stick with it. As a convention, when I refer to args, I'm referring to the argument to a program's main() method. The args array is used to access a program's command-line arguments. These arguments are passed to a program when it is invoked. They are passed as part of the command that is used to invoke the program.
Note Applets Applets are not required to have a main() method.
For example, to run the MyProgram program, you would enter
java MyProgram Suppose that you wanted to pass the arguments 2 and 3 to MyProgram.

You would invoke it as follows:
java MyProgram 2 3 The String object "2" would be accessed as args[0], and the String object "3" would be accessed as args[1]. If you are a C or C++ programmer—pay attention. Java accesses command-line arguments using different indices than do C and C++ programs. The ArgsTest program of Listing 2.1 shows how command-line arguments are accessed using the args array. When you run the program using the following command line

java ArgsTest this is a test
it displays the following results args[0] = this args[1] = is args[2] = a
args[3] = test Listing 2.1: The Argstest Program class ArgsTest {
public static void main(String[] args) {
for(int i=0;i System.out.println("args["+i+"] = "+args[i]);
}
}
}

Comments

Java provides three styles of comments: /* This is a multiline comment. */
// This is a single-line comment.
/** This is a multiline javadoc comment */ The first comment style supports traditional C-language comments. All text appearing between /* and */ is treated as a comment. Comments of this style can span multiple lines. The second comment style supports single line C++ comments. All text following the // until the end of the line is treated as a comment. The third comment style is used by the javadoc documentation generation tool. All text between the /** and */ is treated as a javadoc comment. javadoc comments may span multiple lines. You don't need to know about javadoc on the certification exam. However, if you are interested, it is described in the tools section of the Java 2 platform documentation.
Comments cannot be nested. If comments appear within a String or character literal, they are treated as part of the String or literal.

Identifiers and Keywords

Identifiers are used to name Java language entities. They begin with a Unicode letter, underscore character (_), or dollar sign ($). Subsequent characters consist of these characters and the digits 0–9. Identifiers are case sensitive and cannot be the same as a reserved word or the boolean values True or False or the null value. Avoid using the dollar sign character; it is intended for use by compiler-generated identifiers.

The following are examples of valid Java identifiers:
. myIdentifier. $my_identifier. $123 The following are invalid Java identifiers:
. 1badIdentifier . bad-too . %badID The following words are reserved by the Java language and cannot be used as identifiers:

abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements importinstanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient try void volatile while
Although you don't necessarily need to memorize the above list, it's a good idea to familiarize yourself with it because you are very likely to see at least one exam-related question that requires knowledge of the preceding keywords.

Primitive Types and Literal Values

Java defines eight primitive types. Variables that are declared as a primitive type are not references to objects. They are only place-holders to store primitive values. The eight primitive types are byte, short, int, long, float, double, char, and boolean. The byte, short, int, and long types represent 8-, 16-, 32-, and 64-bit signed integer values. The char type represents an unsigned 16-bit value. The float and double types represent 32- and 64-bit floating point values. The ranges of the primitive types are shown in Table 2.1.

Table 2.1: Ranges of Numeric Types
Type boolean byte char short int long float Range true and false -(27) to 27 - 1 0 to 216 - 1 -(215) to 215 - 1 -(231) to 231 - 1 -(263) to 263 - 1 Float.MIN_VALUE to Float.MAX_VALUE, Float.NaN,
- 19
Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITYdoubleDouble.MIN_VALUE to Double.MAX_VALUE, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY
The literal values of these integer types are written using positive or negative decimal, hexadecimal, or octal integers. Hexadecimal values are preceded by 0x or 0X and use the letters a through f (uppercase or lowercase) to represent the digits 10 through 15. Octal numbers are preceded by 0. Long decimal values have an l or L appended to the end of the number. Examples of conversions between decimal, hexadecimal, and octal values are shown in Table 2.2.
Table 2.2: Decimal, Hexadecimal, and Octal Values
Decimal Value 14 123 4567 Hexadecimal Value 0x0E 0x7B 0x11D7 Octal Value 020 0173 010727

The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers. Floatnumbers have the f or F suffix. Double numbers have d or D. If no suffix is provided, the default double type is assumed. Floating-point numbers may be written using any of the following forms:
digits . optionalDigits optionalExponentPart suffix
. digits optionalExponentPart suffix
digits optionalExponentPart suffix

The suffix is optional. It consists of f, F, d, or D, as described previously. The exponent part is optional. It consists of an e or E followed by a signed integer. It is used to identify the exponent of 10 of the number written in scientific notation. For example, 1000000.0 could be represented as 1.0E6. If a floating-point literal does not contain a decimal point, then it needs to have either the exponent part or the suffix to be recognized as a floating-point literal (as opposed to an integer literal). The Float and Double classes define three special float and double constants. The special value NaN is used to represent the value for "not a number" that occurs as the result of undefined mathematical operations. The values, POSITIVE_INFINITY and NEGATIVE_INFINITY, represent infinite values in the positive and negative directions. The char type represents 16-bit Unicode characters. Unicode is a 16-bit superset of the ASCII character set that provides many foreign-language characters. A single character is specified by putting the character within single quotes ('). There are three exceptions: single quote ('), double quote ("), and backslash (\). The backslash character (\) is used as an escape code to represent special character values. For example, a single quote would be represented by '\''. The character escape codes are shown in Table 2.3.

Table 2.3: Character Escape Codes

Escape Code \b \t \n \f \r \" \' \\ Character backspace tab linefeed form feed carriage return double quote single quote backslash

The backslash can also be followed by an 8-bit octal value (\000 through \377) or by a u or U followed by a four-digit, hexadecimal value (\u0000 through \uffff). The four-digit value can be used to specify the full range of Unicode characters. The boolean type represents the logical values true and false. String literals are also supported by Java. String literals are not primitive values. They are a shorthand notation for representing String objects. Strings consist of characters enclosed by double quotes ("). The character escape codes may be used within String literals to represent special characters within the string. The literal value null is used to identify the fact that an object is not assigned to a variable. It may be used with any variable that is not of a primitive data type. Class literals were introduced with Java 1.1. A class literal is formed by appending .class to the name of a primitive or reference type. It evaluates to the class descriptor of the reference type or class descriptor of the primitive type's wrapper class. The expression void.class evaluates to the class descriptor of the Void class. For example, suppose Test is a class that you've declared.
The following statement displays the output class Test:

System.out.println(Test.class);
Automatic Initialization
Field variables and the elements of arrays are automatically initialized to default values. Local variables are not automatically initialized. Failure to initialize a local variable results in a compilation error. Table
2.4 identifies the default values of each primitive type.

Table 2.4: Default Values for Primitive Types
boolean
false
Type
Default Value
byte
0
char
\u0000
short
0
int
0
long
0l
float
0.0f
double
0.0d

Note Field Variables and Local Variables Field variables are variables that are declared as members of classes. Local variables, also referred to as automatic variables, are declared relative to (or local to) a method or constructor.
Field variables of object types and the elements of arrays of object types are automatically initialized to the null value. The Initialization program (Listing 2.2) illustrates the use of the automatic initialization of field variables and arrays. It displays the following output:
boolean: false byte: 0 char: short: 0 int: 0 long: 0 float: 0.0 double: 0.0 Object: null int[2]: 0 0

Object[2]: null null Note Declaring Arrays and Objects The declaration and use of arrays and objects are covered in Chapter 4, "Declarations and Access Control."

Listing 2.2: The Initialization Program

class Initialization { boolean bo; byte by; char c; short s; int i; long l; float f; double d; Object o; public static void main(String[] args) {
Initialization app = new Initialization();
app.run(); } void run() {
int[] intArray = new int[2]; Object[] objectArray = new Object[2]; System.out.println("boolean: "+bo); System.out.println("byte: "+by); System.out.println("char: "+c); System.out.println("short: "+s); System.out.println("int: "+i); System.out.println("long: "+l); System.out.println("float: "+f); System.out.println("double: "+d); System.out.println("Object: "+o); System.out.println("int[2]: "+intArray[0]+" "+intArray[1]); System.out.println("Object[2]: "+objectArray[0]+" "+objectArray[1]);

} }

Chapter Summary

This chapter reviewed the basics of Java programming. You learned how to create packages, import classes and interfaces from other packages, and create a program's main() method. You also learned how command-line variables are accessed, identifiers are formed, and which keywords are reserved by the Java language. You were introduced to each primitive type, learned its range of values, and learned how to create literal values of each type (and also the String type). You should now be prepared to test your knowledge of these subjects. The following review questions and exam questions will let you know how well you understand this material and will give you an idea of how you'll do in related exam questions. They'll also indicate which material you need to study further.

Key Terms

. Interface . Class . Field Variable . Local Variable . Automatic Variable . Constant . Object . Method . Constructor . Compilation Unit . Source Code File . Package . Naming Context . Import . Command-Line Argument . Comment . Keyword . Primitive Type

Review Questions

1. What is a Java package and how is it used?
2. What is a compilation unit?
3. How are Java source code files named?
4. What restrictions are placed on the location of a package statement within a source code file? 5. Which package is always imported by default?
6. What is the return type of a program's main() method?
7. What is the argument type of a program's main() method?
8. Which non-Unicode letter characters may be used as the first character of an identifier? - 23
9. Which characters may be used as the second character of an identifier, but not as the first character of an identifier?

10. Are true and false keywords?
11. Is null a keyword?
12. Is sizeof a keyword?
13. Name the eight primitive Java types.
14. What is the range of the short type?
15. What is the range of the char type?
16. Is "abc" a primitive value?
17. To what value is a variable of the boolean type automatically initialized?
18. To what value is a variable of the String type automatically initialized?

Exam Questions
1. In order for the public class MyClass to successfully compile, which of the following are true? A. MyClass must have a correctly formed main() method.

B. MyClass must be defined in the file MyClass.java.
C. MyClass must be defined in the MyClass package.
D. MyClass must be imported.

2. In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
A. It must import java.lang.
B. It must declare a public class named Test.
C. It must be named Test.java.
D. It must have a package statement.

3. In order for the MyProgram program to be compiled and run, which of the following must be true?
A. The MyProgram class must be defined in MyProgram.java.
B. MyProgram must be declared public.
C. MyProgram must have a correctly formed main() method.
D. MyProgram must import java.lang.

4. Which of the following are true?
A. If a package statement is included in a source code file, it must appear as the first non-blank line.
B. If an import statement is included in a source code file, it must appear as the first non-blank line.
C. If a main() method is included in a source code file, it must appear as the first non-blank line. D. If a public interface is declared in a source code file, it must have the same name as the source code file.

5. Which of the following are valid main() methods?
A. public static void main() { }
B. public static void main(String[] argc) { }
C. void main(String[] args) { }
D. public static void main(String []args) { }

6. What is the output of the following program when it is invoked using the command line java Test this is a test?
7. class Test {
8. public static void main(String[] args) {
9. System.out.println(args[1]);
10. } }
A. this B. is C. a D. test - 24


11. Which of the following are valid Java comments?
A. \\ This is a comment.
B. /* This is a comment. */
C. /** This is a comment. */
D. \* This is a comment *\

12. Which of the following are valid Java identifiers?
A. %id
B. $id
C. _id
D. #id

13. Which of the following are valid Java identifiers?
A. my-id
B. my_id
C. 101ids
D. id101

14. Which of the following are Java keywords?
A. interface B. sizeof C. superD. volatile

15. Which of the following are Java keywords?
A. NULL B. null C. extends D. main

16. Which of the following are primitive types?
A. byteB. StringC. integerD. Float

17. What is the range of the short type?
A. 0 to 216 B. -(216) to 216 C. -(215) to 215 D. -(215) to 215- 1

18. What is the range of the char type?
A. 0 to 216 B. 0 to 216 - 1 C. 0 to 215 D. 0 to 215- 1

19. What is the octal equivalent of the decimal value 123?
A. 0173 B. 123 C. 0x123 D. 0x173

20. What is the hexadecimal equivalent of decimal 123?
A. 0x173 B. 0x123 C. 0x7B D. 173

21. What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment."); ?
A. // Looks like a comment.
B. / Looks like a comment.
C. No output is displayed.
D. The statement results in a compilation error.

22. Which of the following are valid double literals?
A. 1D B. 1E-5D C. e2d D. 1ed

23. What is the output of the following program?
24. public class Question {
25. public static void main(String args[]){
26. boolean[] b = new boolean[2];
27. double[] d = new double[2];
28. System.out.print(b[0]);
29. System.out.println(d[1]);
30. } }
A. true0.0 B. true0 C. false0.0 D. false0

31. What is the output of the following program?
32. public class Question {
33. public static void main(String args[]){
34. Object[] o = new Object[2];
35. byte[] b = new byte[2];
36. System.out.print(o[0]);
37. System.out.println(b[1]);
38. } }
A. 0 B. o0 C. A NullPointerException is thrown D. null0


Answers to Review Questions
1. A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes a
nd interfaces.

2. A compilation unit is a Java source code file.

3. A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

4. A package statement must appear as the first line in a source code file (excluding blank lines and comments).

5. The java.lang package is always imported by default.

6. A program's main() method has a void return type.

7. A program's main() method takes an argument of the String[] type.

8. The non-Unicode letter characters $ and _ may appear as the first character of an identifier.

9. The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

10. The values true and false are not keywords.

11. The null value is not a keyword.

12. The sizeof operator is not a keyword.

12. The eight primitive types are byte, char, short, int, long, float, double, and boolean.

13. The range of the short type is -(215) to 215 - 1.

14. The range of the char type is 0 to 216 - 1.

15. The String literal "abc" is not a primitive value.

16. The default value of the boolean type is false.

17. The default value of an String type is null.

Answers to Exam Questions

1. B. A class does not need a main() method to compile. Nor does it need to be defined in a package or imported. However, a public class needs to be defined in a source code file of the same name.
2. C. A source code file must take the same name as any public class or interface that it declares. 3. C. For a class to be compiled and run, it must have a correctly formed main() method. It does not need to be declared public.
4. A and D. Package statements must appear as the first non-blank line of a source code file (if they appear at all). If a public class or interface is declared in a source code file, then the source code file must take the name of the public class or interface.
5. B and D. The main() method of answer A is missing an argument. The main()method of answer C is missing the public and static modifiers.
6. B. The String "is" is assigned to args[1].
7. B and C. Comments use slashes and not backslashes.
8. B and C. The only special characters that may appear in an identifier are _ and $.
9. B and D. The only special characters that may appear in an identifier are _ and $. Digits may not be used as the first character of an identifier.
10. A, C, and D. The sizeof operator is not a Java keyword.
11. C. NULL, null, and main are not Java keywords.
12. A. Neither String, integer, nor Float are primitive types.
13. D. The range of the short type is -(215) to 215- 1.
14. B. The range of the char type is 0 to 216 - 1.
15. A. The octal value 0173 is equivalent to the decimal value 123.
16. C. The hexadecimal value 0x7B is equivalent to the decimal value 123.
17. A. Comments may not appear in a String literal.
18. A and B. Since the value e2d begins with a letter, it is treated as an identifier. Since there is no signed integer value after the e in 1ed, it is an invalid double literal.
19. C. The default value of a boolean is false and the default value of a double is 0.0.
20. D. The default value of an Object is null and the default value of a byte is 0.

Go to Home Page

No comments: