Chapter One Part II
Chapter One Part II
Java basics
System.out.println("welcome to java");
}
}
1. Anatomy of a Java Program
The application program in Listing 1.1 has the following components:
Comments
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
To build a program, you need to understand these basic elements. They are explained in the
sections that follow.
Comments
Comment tells what the program is and how the program is constructed. Comments help
programmers to communicate and understand the program. Comments are not programming
statements and thus are ignored by the compiler. In Java, comments are preceded by two slashes
(//) on a line, called a line comment, or enclosed between /* and */ on one or several lines, called
a paragraph comment. When the compiler sees //, it ignores all text after // on the same line.
When it sees /*, it scans for the next */ and ignores any text between /* and */.
Here are examples of the two types of comments:
// This application program prints Welcome to Java!
/* This application program prints Welcome to Java! */
/* This application program
prints Welcome to Java! */
Reserved Words
Reserved words, or keywords, are words that have a specific meaning to the compiler and cannot
be used for other purposes in the program. For example, when the compiler sees the word class,
it understands that the word after class is the name for the class. Other reserved words in Listing
1.1 are public, static, and void. Their use will be introduced later in next chapter.
Tip Because Java is case-sensitive, public is a reserved word, but Public is not.
Nonetheless, for clarity and readability, it would be best to avoid using
reserved words in other forms.
Modifiers
Java uses certain reserved words called modifiers that specify the properties of the data, methods,
and classes and how they can be used. Examples of modifiers are public and static. Other
modifiers are private, final, abstract, and protected. A public datum, method, or class can be
accessed by other classes. A private datum or method cannot be accessed by other classes.
Statements
A statement represents an action or a sequence of actions. The statement
System.out.println("Welcome to Java!"); in the program in Listing 1.1 is a statement to display
the greeting "Welcome to Java!". Every statement in Java ends with a semicolon (;).
Blocks
The braces in the program form a block that groups the components of the program. In Java, each
block begins with an opening brace ({) and ends with a closing brace (}). Every class has a class
block that groups the data and methods of the class. Every method has a method block that
groups the statements in the method. Blocks can be nested, meaning that one block can be placed
within another.
Classes
The class is the essential Java construct. To program in Java, you must understand classes and be
able to write and use them. The mystery of classes will be unveiled throughout the course. For
now, though, it is enough to know that a program is defined by using one or more classes.
Declaring a class
Every java program consists of at least one class that you (the programmer) define. “class”
keyword followed by the class name (identifier). Just as every entity in the real world has a
name, so you need to choose names for the things you will refer to in your programs.
Programming languages use special symbols called identifiers to name such programming
entities as variables, constants, methods, classes, and packages. Here are the rules for naming
identifiers:
An identifier is a sequence of characters that consists of letters, digits, underscores (_),
and dollar signs ($).
An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start
with a digit.
An identifier cannot be a reserved word. ("Java Keywords,")
An identifier cannot be true, false, or null.
An identifier can be of any length.
For example, $2, ComputeArea, area, radius, and showMessageDialog are legal identifiers,
whereas 2A and d+4 are illegal identifiers because they do not follow the rules. The Java
compiler detects illegal identifiers and reports syntax errors.
Note The print method is identical to the println method except that println moves
the cursor to the next line after displaying the string, but print does not
advance the cursor to the next line when completed.
Listing 1.2 gives an example that reads various types of data from the console using the Scanner
class.
Listing 1.2 TestScanner.java
1 import java.util.Scanner; // Scanner is in java.util
2
3 public class TestScanner {
4 public static void main(String args[]) {
5 // Create a Scanner
6 Scanner scanner = new Scanner(System.in);
7
8 // Prompt the user to enter an integer
9 System.out.print("Enter an integer: ");
10 int intValue = scanner.nextInt();
11 System.out.println("You entered the integer " + intValue);
12
13 // Prompt the user to enter a double value
14 System.out.print("Enter a double value: ");
15 double doubleValue = scanner.nextDouble();
16 System.out.println("You entered the double value "
17 + doubleValue);
18
19 // Prompt the user to enter a string
20 System.out.print("Enter a string without space: ");
21 String string = scanner.next();
22 System.out.println("You entered the string " + string);
23 }
24 }
(i.e., -9223372036854775808 to
9223372036854775807)
Note To assign a variable of the int type to a variable of the short or byte type,
explicit casting must be used. For example, the following statements have a
syntax error:
int i = 1;
byte b = i; // Error because explicit casting is required
Listing 1.4 gives a program that displays the sales tax with two digits after the decimal point.
Listing 1.4. SalesTax.java
1 public class SalesTax {
2 public static void main(String[] args) {
3 double purchaseAmount = 197.55;
4 double tax = purchaseAmount * 0.06;
5 System.out.println((int)(tax * 100) / 100.0);
6 }
7}
Variable purchaseAmount is 197.55 (line 3). The sales tax is 6% of the purchase, so the tax is
evaluated as 11.853 (line 4). The statement in line 5 displays the tax 11.85 with two digits after
the decimal point. Note that (int)(tax * 100) is 1185, so (int)(tax * 100) / 100.0 is 11.85.
6. The String Type
The char type only represents one character. To represent a string of characters, use the data
type called String. For example, the following code declares the message to be a string that has
an initial value of "Welcome to Java".
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like the System class and
JOptionPane class. The String type is not a primitive type. It is known as a reference type. Any
Java class can be used as a reference type for a variable. As first shown in Listing 2.1, two
strings can be concatenated. The plus sign (+) is the concatenation operator if one of the
operands is a string. If one of the operands is a non-string (e.g., a number), the non-string value
is converted into a string and concatenated with the other string. Here are some examples:
// Three strings are concatenated
String message = "Welcome" + "to" + "Java";