Every programming language before Java was designed to create stand-alone programs.
Java, however, has two categories of programs. Apart from the traditional stand-alone pro-grams, Java introduced applets. Applets are small applications intended to run on a web browser. In this book, application programs are introduced fi rst. All the Java language fundamentals, good programming skills, and soft ware engineering principles are taught through application programs. Java applets are discussed in Chapter 8.
Apago PDF Enhancer
A Java program is a collection of one or more classes. So a very simple application program must have at least one class. Th e basic syntax of class can be shown using a syntax template as follows:
[accessModifiers] class className [classModifiers]
{
[members]
}
An item inside a pair of square brackets in a syntax template is optional. In the syntax tem-plate, className is a name you would like to give to the class. Th e optional members consist of attributes and operations of the class. Th e optional accessModifiers deter-mines, among other things, the accessibility of the class to other classes and Java virtual machine (JVM). For example, the access modifi er public makes a class accessible to JVM.
Because JVM needs access to your program, every application must have one class with public or package access. We will have more to say about this topic later. Both public and class are reserved words or keywords. A reserved word is a word with special mean-ing. For example, the reserved word class indicates the beginning of a class defi nition.
In a syntax template, all reserved words are shown in bold. Th e optional classModi-fiers are not used in the fi rst six chapters of this book and it will be explained in Chapter 7. Following the reserved word class, you must supply a name for the class. Note that the name identifi es a class. Similarly, you need to provide a name to attributes and operations of a class. All such names are collectively known as identifi ers.
Self-Check
5. In a syntax template, how is an optional item shown?
6. In a syntax template is shown in bold.
Identifi er
A Java identifi er can be of any length. However, it must obey the following three rules:
1. Every character in an identifi er is a letter (A to Z, a to z), or a digit (0 to 9), or the underscore character (_), or the dollar sign ($).
2. Th e fi rst character of an identifi er must be a letter or the underscore character or the dollar sign.
3. An identifi er cannot be a reserved word.
Common Programming Error 2.1
Using a space or blank character as part of an identifi er is an error.
Common Programming Error 2.2 Using a hyphen as part of an identifi er is an error.
Apago PDF Enhancer
Note 2.1 Java is a case-sensitive language. In other words, uppercase letter A is not the same as lowercase letter a. Th us, Welcome, welcome, WelCome, and WELCOME are four diff erent identifi ers.
Good Programming Practice 2.1
Create meaningful identifi ers. An identifi er must be self-explanatory.
Good Programming Practice 2.2
Java system has many predefi ned identifi ers. Most frequently encountered identi-fi ers are System, print, println, main, and next. Even though predeidenti-fi ned identifi ers can be redefi ned, it is wise to refrain from it.
Example 2.4
Th e following identifi ers are legal:
Carrot Tiger
bonusSalary
number_of_lines_per_page
_0 //legal but bad choice
$1 //legal but bad choice
Even though identifi ers _0 and $1 are legal, they do not convey the purpose or the meaning of the identifi er and as such should be avoided.
Example 2.5 Table 2.1 provides a list of fi ve illegal identifi ers.
It is a well-accepted convention to keep an identifi er used to name a class in all letters and the fi rst letter of each word in uppercase. Th us HiThere, FirstJavaProgram, and DigitalClock obey the convention followed by class names.
TABLE 2.1 Illegal Identifi ers
Identifi er Explanation
Yearly bonus Th e space character cannot appear in an identifi er British#Sterling Th e pound sign cannot appear in an identifi er Jim&Mary Th e symbol & cannot be used in an identifi er 9thValue A digit cannot be the fi rst character of an identifi er public Reserved word cannot be used as an identifi er
Apago PDF Enhancer
Note that a class need not have any members. Th erefore, you can create a class named HiThere as follows:
public class HiThere {
}
Note 2.2 You must always keep the opening and closing pair of braces ({ and }) in the class defi nition.
Note 2.3 As a matter of style, we always align a pair of braces vertically and any Java statements appearing inside a pair of braces will be indented.
Once you have created this class, you must save it in a fi le HiThere.java. If you compile this class, Java will create a new fi le HiThere.class without any error messages. However, if you try to execute HiThere.class, Java will give you an error message similar to the following one:
Exception in thread "main" java.lang.NoSuchMethodError: main In other words, to execute an application, there needs to be a method named main.
Th e term method stands for Java code that implements an operation of the class.
Th e basic syntax of the method main is
public static void main(String[] args) {
[statements]
}
You need not be concerned about the details of the syntax at this point. Instead, note that statements are optional. Th e simplest method main one could write is public static void main(String[] args)
{ }
We have the following simple application program:
public class HiThere {
public static void main(String[] args) {
} }
Apago PDF Enhancer
You may compile and execute this program without any error. However, this program produces no output at all. All application programs in this chapter will be created out of the above template.
So far you have encountered identifi ers, reserved words, methods, classes, and a pair of opening and closing braces. You have also mastered the rules for forming identifi ers. Let us now have a closer look at reserved words.
Self-Check
7. List four distinct identifi ers that spell the word “fi ne.”
8. Why using the identifi er abc123 a bad choice?
Reserved Word
You have already seen the reserved words public, static, void,andclass. In Java, all reserved words are made up of lowercase letters. Each reserved word is treated as a single symbol and must be typed exactly as shown. For example, there are two reserved words throwandthrows. Both have diff erent intended usage and the reserved word throw is not the plural of the reserved word throws. A complete list of reserved words can be found in Appendix C. Recall, from the rules of identifi ers, that you cannot create an identifi er that matches a reserved word. Reserved words are also known as keywords.
Note 2.4 In this book, all reserved words appearing in the code are highlighted in bold.
Many Java program editor soft ware display the keywords in a diff erent color. Th is feature is known as syntax coloring.
Self-Check 9. Is Class a reserved word in Java?
10. True or false: In Java, all reserved words are made up of lowercase letters.
Comment Lines
One of the most important qualities of a good program is its readability. Program-mers are notorious for creating programs that are very diffi cult to understand not only by others, but also by themselves aft er a short period of time. Since soft ware main-tenance is quite costly, importance of documentation in soft ware creation cannot be overemphasized.
As a programmer, you can place comment lines in your programs to fully explain the purpose as well as the logic of each of the important steps. Java provides two types of comment lines: single line format and multiple lines format. A Single line comment starts with // and can begin at any place in a line. Th e compiler ignores everything that appears aft er two consecutive / characters. A Multiple line comment starts with /* and ends with */. Everything that appears between /* and */ is ignored by the compiler.
Apago PDF Enhancer
Example 2.6
In this example, we illustrate both single line and multiple line comments:
// This is a single line comment and is equivalent to the following:
/* This is a single line comment */
Similarly, six lines of comment
// This is a comment. Next five lines are also comments // Line 1
// Line 2 // Line 3 // Line 4 // Line 5
is equivalent to the following:
/* This is a comment. Next five lines are also comments Line 1
Line 2 Line 3 Line 4
Line 5
*/
Note 2.5 Every Java program is a collection of one or more classes and every class has one or more methods. Since you have not seen many classes or methods, the material covered in this note may not be completely clear. From a pedagogi-cal perspective, it is better to develop the habit of including comments in every program. In Java, there is a standard for documenting classes and methods. If you follow these guidelines, you can use a Java utility called javadoc to generate docu-mentation in HTML format from the comments in the source code. Th e documen-tation comment is placed before the class or method defi nition and it starts with /** and ends with */. Th e javadoc utility copies the fi rst line of each comment into a table. Th erefore, compose your fi rst lines in each comment with some care. Here is a sample comment you may place before a class:
/**
A student class tracks gpa, major and advisor
*/
Th e additional conventions you need to follow in the case of methods will be dis-cussed in Chapter 3. Comments in this book will follow conventions consistent with javadoc.
Apago PDF Enhancer
Self-Check
11. True or false: In Java, every comment starts with /*.
12. True or false: Including comments in a program is optional.