A. Introduction to Java Applications


Objectives

In this appendix you’ll learn:

Image To write simple Java applications.

Image To use input and output statements.

Image Java’s primitive types.

Image Basic memory concepts.

Image To use arithmetic operators.

Image The precedence of arithmetic operators.

Image To write decision-making statements.

Image To use relational and equality operators.


A.1 Introduction

This appendix introduces Java application programming. You’ll use tools from the JDK to compile and run programs. At www.deitel.com/books/AndroidHTP3/, we’ve posted videos to help you get started with several popular integrated development environments (IDEs). The Android part of this book uses the Android Studio IDE, which is based on IntelliJ® IDEA.

A.2 Your First Program in Java: Printing a Line of Text

A Java application is a computer program that executes when you use the java command to launch the Java Virtual Machine (JVM).First we consider a simple application that displays a line of text. Figure A.1 shows the program followed by a box that displays its output.


 1  // Fig. A.1: Welcome1.java
 2  // Text-printing program.
 3
 4  public class Welcome1
 5  {
 6     // main method begins execution of Java application
 7     public static void main( String[] args )
 8     {
 9        System.out.println( "Welcome to Java Programming!" );
10     } // end method main
11  } // end class Welcome1


Welcome to Java Programming!


Fig. A.1 | Text-printing program.

Commenting Your Programs

We insert comments to document programs and improve their readability. The Java compiler ignores comments, so they do not cause the computer to perform any action when the program is run.

The comment in line 1

// Fig. A. 1: Welcome1.java

begins with //, indicating that it is an end-of-line comment—it terminates at the end of the line on which the // appears. Line 2 is a comment that describes the purpose of the program.

Java also has traditional comments, which can be spread over several lines as in

/* This is a traditional comment. It
   can be split over multiple lines */

These begin and end with delimiters, /* and */. The compiler ignores all text between the delimiters.


Image Common Programming Error A.1

A syntax error occurs when the compiler encounters code that violates Java’s language rules (i.e., its syntax). Syntax errors are also called compilation errors, because the compiler detects them during the compilation phase. The compiler responds by issuing an error message and preventing your program from compiling.


Using Blank Lines

Line 3 is a blank line. Blank lines, space characters and tabs make programs easier to read. Together, they’re known as white space (or whitespace). The compiler ignores white space.

Declaring a Class

Line 4 begins a class declaration for class Welcome1. Every Java program consists of at least one class that you (the programmer) define. The class keyword introduces a class declaration and is immediately followed by the class name (Welcome1). Keywords are reserved for use by Java and are always spelled with all lowercase letters. The complete list of keywords can be viewed at:

Class Names and Identifiers

By convention, class names begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). A class name is an identifier—a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces. The name 7button is not a valid identifier because it begins with a digit, and the name input field is not a valid identifier because it contains a space. Java is case sensitive—uppercase and lowercase letters are distinct—so value and Value are different identifiers.

In Appendices AE, every class we define begins with the keyword public. For our application, the file name is Welcome1.java.


Image Common Programming Error A.2

A public class must be placed in a file that has the same name as the class (in terms of both spelling and capitalization) plus the .java extension; otherwise, a compilation error occurs. For example, public class Welcome must be placed in a file named Welcome.java.


A left brace (as in line 5), {, begins the body of every class declaration. A corresponding right brace, }, must end each class declaration.


Image Good Programming Practice A.1

Indent the entire body of each class declaration one “level” between the left brace and the right brace that delimit the body of the class. We recommend using three spaces to form a level of indent. This format emphasizes the class declaration’s structure and makes it easier to read.


Declaring a Method

Line 6 is an end-of-line comment indicating the purpose of lines 7–10 of the program. Line 7 is the starting point of every Java application. The parentheses after the identifier main indicate that it’s a program building block called a method. For a Java application, one of the methods must be called main and must be defined as shown in line 7. Methods perform tasks and can return information when they complete their tasks. Keyword void indicates that this method will not return any information. In line 7, the String[] args in parentheses is a required part of the method main’s declaration—we discuss this in Appendix E.

The left brace in line 8 begins the body of the method declaration. A corresponding right brace must end it (line 10).

Performing Output with System.out.println

Line 9 instructs the computer to perform an action—namely, to print the string of characters contained between the double quotation marks (but not the quotation marks themselves). A string is sometimes called a character string or a string literal. White-space characters in strings are not ignored by the compiler. Strings cannot span multiple lines of code.

The System.out object is known as the standard output object. It allows a Java applications to display information in the command window from which it executes. In recent versions of Microsoft Windows, the command window is the Command Prompt. In UNIX/Linux/Mac OS X, the command window is called a terminal window or a shell. Many programmers call it simply the command line.

Method System.out.println displays (or prints) a line of text in the command window. The string in the parentheses in line 9 is the argument to the method. When System.out.println completes its task, it positions the cursor (the location where the next character will be displayed) at the beginning of the next line in the command window.

The entire line 9, including System.out.println, the argument "Welcome to Java Programming!" in the parentheses and the semicolon (;), is called a statement. Most statements end with a semicolon. When the statement in line 9 executes, it displays Welcome to Java Programming! in the command window.

Using End-of-Line Comments on Right Braces for Readability

We include an end-of-line comment after a closing brace that ends a method declaration and after a closing brace that ends a class declaration. For example, line 10 indicates the closing brace of method main, and line 11 indicates the closing brace of class Welcome1.

Compiling and Executing Your First Java Application

We assume you’re using the Java Development Kit’s command-line tools, not an IDE. As we mentioned previously, we’ve posted videos at www.deitel.com/books/AndroidHTP3/ to help you get started with several popular IDEs.

To prepare to compile the program, open a command window and change to the directory where the program is stored. Many operating systems use the command cd to change directories. On Windows, for example,

cd c:examplesappAfigA_01

changes to the figA_01 directory. On UNIX/Linux/Max OS X, the command

cd ~/examples/appA/figA_01

changes to the figA_01 directory.

To compile the program, type

javac Welcome1.java

If the program contains no syntax errors, this command creates a new file called Welcome1.class (known as the class file for Welcome1) containing the platform-independent Java bytecodes that represent our application. When we use the java command to execute the application on a given platform, the JVM will translate these bytecodes into instructions that are understood by the underlying operating system and hardware.


Image Error-Prevention Tip A.1

When attempting to compile a program, if you receive a message such as "bad command or filename," "javac: command not found" or "'javac' is not recognized as an internal or external command, operable program or batch file," then your Java software installation was not completed properly. If you’re using the JDK, this indicates that the system’s PATH environment variable was not set properly. Please carefully review the installation instructions in the Before You Begin section of this book. On some systems, after correcting the PATH, you may need to reboot your computer or open a new command window for these settings to take effect.


Figure A.2 shows the program of Fig. A.1 executing in a Microsoft® Windows® 7 Command Prompt window. To execute the program, type java Welcome1. This command launches the JVM, which loads the .class file for class Welcome1. The command omits the .class file-name extension; otherwise, the JVM will not execute the program. The JVM calls method main. Next, the statement at line 9 of main displays "Welcome to Java Programming!"

Image

Fig. A.2 | Executing Welcome1 from the Command Prompt.


Image Error-Prevention Tip A.2

When attempting to run a Java program, if you receive a message such as “Exception in thread "main" java.lang.NoClassDefFoundError: Welcome1," your CLASSPATH environment variable has not been set properly. Please carefully review the installation instructions in the Before You Begin section of this book. On some systems, you may need to reboot your computer or open a new command window after configuring the CLASSPATH.


A.3 Modifying Your First Java Program

Welcome to Java Programming! can be displayed several ways. Class Welcome2, shown in Fig. A.3, uses two statements (lines 9–10) to produce the output shown in Fig. A.1.


 1  // Fig. A.3: Welcome2.java
 2  // Printing a line of text with multiple statements.
 3
 4  public class Welcome2
 5  {
 6     // main method begins execution of Java application
 7     public static void main( String[] args )
 8     {
 9        System.out.print( "Welcome to " );        
10        System.out.println( "Java Programming!" );
11     } // end method main
12  } // end class Welcome2


Welcome to Java Programming!


Fig. A.3 | Printing a line of text with multiple statements.

The program is similar to Fig. A.1, so we discuss only the changes here. Line 2 is a comment stating the purpose of the program. Line 4 begins the Welcome2 class declaration. Lines 9–10 of method main display one line of text. The first statement uses System.out’s method print to display a string. Each print or println statement resumes displaying characters from where the last print or println statement stopped displaying characters. Unlike println, after displaying its argument, print does not position the output cursor at the beginning of the next line in the command window—the next character the program displays will appear immediately after the last character that print displays. Thus, line 10 positions the first character in its argument (the letter “J”) immediately after the last character that line 9 displays (the space character before the string’s closing double-quote character).

Displaying Multiple Lines of Text with a Single Statement

A single statement can display multiple lines by using newline characters, which indicate to System.out’s print and println methods when to position the output cursor at the beginning of the next line in the command window. Like blank lines, space characters and tab characters, newline characters are white-space characters. The program in Fig. A.4 outputs four lines of text, using newline characters to determine when to begin each new line.


 1  // Fig. A.4: Welcome3.java
 2  // Printing multiple lines of text with a single statement.
 3
 4  public class Welcome3
 5  {
 6     // main method begins execution of Java application
 7     public static void main( String[] args )
 8     {
 9        System.out.println( "Welcome to Java Programming!" );
10     } // end method main
11  } // end class Welcome3


Welcome
to
Java
Programming!


Fig. A.4 | Printing multiple lines of text with a single statement.

Line 2 is a comment stating the program’s purpose. Line 4 begins the Welcome3 class declaration. Line 9 displays four separate lines of text in the command window. Normally, the characters in a string are displayed exactly as they appear in the double quotes. Note, however, that the paired characters and n (repeated three times in the statement) do not appear on the screen. The backslash () is an escape character. which has special meaning to System.out’s print and println methods. When a backslash appears in a string, Java combines it with the next character to form an escape sequence. The escape sequence represents the newline character. When a newline character appears in a string being output with System.out, the newline character causes the screen’s output cursor to move to the beginning of the next line in the command window.

Figure A.5 lists several common escape sequences and describes how they affect the display of characters in the command window.

Image

Fig. A.5 | Some common escape sequences.

A.4 Displaying Text with printf

The System.out.printf method displays formatted data. Figure A.6 uses this method to output the strings "Welcome to" and "Java Programming!". Lines 9–10 call method System.out.printf to display the program’s output. The method call specifies three arguments—they’re placed in a comma-separated list.


 1  // Fig. A.6: Welcome4.java
 2  // Displaying multiple lines with method System.out.printf.
 3
 4  public class Welcome4
 5  {
 6     // main method begins execution of Java application
 7     public static void main( String[] args )
 8     {
 9        System.out.printf( "%s %s ",         
10           "Welcome to", "Java Programming!" );
11     } // end method main
12  } // end class Welcome4


Welcome to
Java Programming!


Fig. A.6 | Displaying multiple lines with method System.out.printf.

Lines 9–10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it’s a continuation of line 9.

Method printf’s first argument is a format string that may consist of fixed text and format specifiers. Fixed text is output by printf just as it would be by print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. Format specifiers also may include optional formatting information.

Format specifiers begin with a percent sign (%) followed by a character that represents the data type. For example, the format specifier %s is a placeholder for a string. The format string in line 9 specifies that printf should output two strings, each followed by a newline character. At the first format specifier’s position, printf substitutes the value of the first argument after the format string. At each subsequent format specifier’s position, printf substitutes the value of the next argument. So this example substitutes "Welcome to" for the first %s and "Java Programming!" for the second %s. The output shows that two lines of text are displayed.

A.5 Another Application: Adding Integers

Our next application reads (or inputs) two integers (whole numbers, such as —22, 7, 0 and 1024) typed by a user at the keyboard, computes their sum and displays it. Programs remember numbers and other data in the computer’s memory and access that data through program elements called variables. The program of Fig. A.7 demonstrates these concepts. In the sample output, we use bold text to identify the user’s input (i.e., 45 and 72).


 1  // Fig. A.7: Addition.java
 2  // Addition program that displays the sum of two numbers.
 3  import java.util.Scanner; // program uses class Scanner
 4
 5  public class Addition
 6  {
 7     // main method begins execution of Java application
 8     public static void main( String[] args )
 9     {
10        // create a Scanner to obtain input from the command window
11        Scanner input = new Scanner( System.in );                  
12
13        int number1; // first number to add   
14        int number2; // second number to add  
15        int sum; // sum of number1 and number2
16
17        System.out.print( "Enter first integer: " ); // prompt
18        number1 = input.nextInt(); // read first number from user
19
20        System.out.print( "Enter second integer: " ); // prompt
21        number2 = input.nextInt(); // read second number from user
22
23        sum = number1 + number2; // add numbers, then store total in sum
24
25        System.out.printf( "Sum is %d ", sum ); // display sum
26     } // end method main
27  } // end class Addition


Enter first integer: 45
Enter second integer: 72
Sum is 117


Fig. A.7 | Addition program that displays the sum of two numbers.

Import Declarations

Lines 1–2 state the figure number, file name and purpose of the program. A great strength of Java is its rich set of predefined classes that you can reuse rather than “reinventing the wheel.” These classes are grouped into packages—named groups of related classes—and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API). Line 3 is an import declaration that helps the compiler locate a class that’s used in this program. It indicates that this example uses Java’s predefined Scanner class (discussed shortly) from package java.util.

Declaring Class Addition

Line 5 begins the declaration of class Addition. The file name for this public class must be Addition.java. Remember that the body of each class declaration starts with an opening left brace (line 6) and ends with a closing right brace (line 27).

The application begins execution with the main method (lines 8–26). The left brace (line 9) marks the beginning of method main’s body, and the corresponding right brace (line 26) marks its end. Method main is indented one level in the body of class Addition, and the code in the body of main is indented another level for readability.

Declaring and Creating a Scanner to Obtain User Input from the Keyboard

A variable is a location in the computer’s memory where a value can be stored for use later in a program. All Java variables must be declared with a name and a type before they can be used. A variable’s name enables the program to access the value of the variable in memory. A variable’s name can be any valid identifier. A variable’s type specifies what kind of information is stored at that location in memory. Like other statements, declaration statements end with a semicolon (;).

Line 11 is a variable declaration statement that specifies the name (input) and type (Scanner) of a variable that’s used in this program. A Scanner enables a program to read data (e.g., numbers and strings) for use in a program. The data can come from many sources, such as the user at the keyboard or a file on disk. Before using a Scanner, you must create it and specify the source of the data.

The = in line 11 indicates that Scanner variable input should be initialized (i.e., prepared for use in the program) in its declaration with the result of the expression to the right of the equals sign—new Scanner(System.in). This expression uses the new keyword to create a Scanner object that reads characters typed by the user at the keyboard. The standard input object, System.in, enables applications to read bytes of information typed by the user. The Scanner translates these bytes into types (like ints) that can be used in a program.

Declaring Variables to Store Integers

The variable declaration statements in lines 13–15 declare that variables number1, number2 and sum hold data of type int—that is, integer values (whole numbers such as 72, —1127 and 0). These variables are not yet initialized. The range of values for an int is —2,147,483,648 to +2,147,483,647. [Note: Actual int values may not contain commas.]

Other data types include float and double, for holding real numbers (such as 3.4, 0.0 and —11.19), and char, for holding character data. Variables of type char represent individual characters, such as an uppercase letter (e.g., A), a digit (e.g., 7), a special character (e.g., * or %) or an escape sequence (e.g., the newline character, ). The types int, float, double and char are called primitive types. Primitive-type names are keywords and must appear in all lowercase letters. Appendix L summarizes the characteristics of the eight primitive types (boolean, byte, char, short, int, long, float and double).


Image Good Programming Practice A.2

By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter.


Prompting the User for Input

Line 17 uses System.out.print to display the message "Enter first integer: ". This message is called a prompt because it directs the user to take a specific action. We use method print here rather than println so that the user’s input appears on the same line as the prompt. Recall from Section A.2 that identifiers starting with capital letters typically represent class names. So, System is a class. Class System is part of package java.lang. Class System is not imported with an import declaration at the beginning of the program.


Image Software Engineering Observation A.1

By default, package java.lang is imported in every Java program; thus, classes in java.lang are the only ones in the Java API that do not require an import declaration.


Obtaining an int as Input from the User

Line 18 uses Scanner object input’s nextInt method to obtain an integer from the user at the keyboard. At this point the program waits for the user to type the number and press the Enter key to submit the number to the program.

Our program assumes that the user enters a valid integer value. If not, a runtime logic error will occur and the program will terminate. Appendix H discusses how to make your programs more robust by enabling them to handle such errors—this makes your program more fault tolerant.

In line 18, we place the result of the call to method nextInt (an int value) in variable number1 by using the assignment operator, =. The statement is read as “number1 gets the value of input.nextInt().” Operator = is called a binary operator, because it has two operandsnumber1 and the result of the method call input.nextInt(). This statement is called an assignment statement, because it assigns a value to a variable. Everything to the right of the assignment operator, =, is always evaluated before the assignment is performed.


Image Good Programming Practice A.3

Placing spaces on either side of a binary operator makes the program more readable.


Prompting for and Inputting a Second int

Line 20 prompts the user to input the second integer. Line 21 reads the second integer and assigns it to variable number2.

Using Variables in a Calculation

Line 23 is an assignment statement that calculates the sum of the variables number1 and number2 then assigns the result to variable sum by using the assignment operator, =. The statement is read as “sum gets the value of number1 + number2.” In general, calculations are performed in assignment statements. When the program encounters the addition operation, it performs the calculation using the values stored in the variables number1 and number2. In the preceding statement, the addition operator is a binary operator—its two operands are the variables number1 and number2. Portions of statements that contain calculations are called expressions. In fact, an expression is any portion of a statement that has a value associated with it. For example, the value of the expression number1 + number2 is the sum of the numbers. Similarly, the value of the expression input.nextInt() is the integer typed by the user.

Displaying the Result of the Calculation

After the calculation has been performed, line 25 uses method System.out.printf to display the sum. The format specifier %d is a placeholder for an int value (in this case the value of sum)—the letter d stands for “decimal integer.” The remaining characters in the format string are all fixed text. So, method printf displays "Sum is", followed by the value of sum (in the position of the %d format specifier) and a newline.

Calculations can also be performed inside printf statements. We could have combined the statements at lines 23 and 25 into the statement

System.out.printf( "Sum is %d ", ( number1 + number2 ) );

The parentheses around the expression number1 + number2 are not required—they’re included to emphasize that the value of the entire expression is output in the position of the %d format specifier.

Java API Documentation

For each new Java API class we use, we indicate the package in which it’s located. This information helps you locate descriptions of each package and class in the Java API documentation. A web-based version of this documentation can be found at

A.6 Memory Concepts

Variable names such as number1, number2 and sum actually correspond to locations in the computer’s memory. Every variable has a name, a type, a size (in bytes) and a value.

In the addition program of Fig. A.7, when the following statement (line 18) executes:

number1 = input.nextInt(); // read first number from user

the number typed by the user is placed into a memory location corresponding to the name number1. Suppose that the user enters 45. The computer places that integer value into number1 (Fig. A.8), replacing the previous value (if any) in that location. The previous value is lost.

Image

Fig. A.8 | Memory location showing the name and value of variable number1.

When the statement (line 21)

number2 = input.nextInt(); // read second number from user

executes, suppose that the user enters 72. The computer places that integer value into location number2. The memory now appears as shown in Fig. A.9.

Image

Fig. A.9 | Memory locations after storing values for number1 and number2.

After the program of Fig. A.7 obtains values for number1 and number2, it adds the values and places the total into variable sum. The statement (line 23)

sum = number1 + number2; // add numbers, then store total in sum

performs the addition, then replaces any previous value in sum. After sum has been calculated, memory appears as in Fig. A.10. number1 and number2 contain the values that were used in the calculation of sum. These values were used, but not destroyed, as the calculation was performed. When a value is read from a memory location, the process is nondestructive.

Image

Fig. A.10 | Memory locations after storing the sum of number1 and number2.

A.7 Arithmetic

Most programs perform arithmetic calculations. The arithmetic operators are summarized in Fig. A.11. Note the use of various special symbols not used in algebra. The asterisk (*) indicates multiplication, and the percent sign (%) is the remainder operator, which we’ll discuss shortly. The arithmetic operators in Fig. A.11 are binary operators, because each operates on two operands. For example, the expression f + 7 contains the binary operator + and the two operands f and 7.

Image

Fig. A.11 | Arithmetic operators.

Integer division yields an integer quotient. For example, the expression 7 / 4 evaluates to 1, and the expression 17 / 5 evaluates to 3. Any fractional part in integer division is simply discarded (i.e., truncated)—no rounding occurs. Java provides the remainder operator, %, which yields the remainder after division. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3, and 17 % 5 yields 2. This operator is most commonly used with integer operands but can also be used with other arithmetic types.

Arithmetic Expressions in Straight-Line Form

Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer. Thus, expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line. The following algebraic notation is generally not acceptable to compilers:

Image

Parentheses for Grouping Subexpressions

Parentheses are used to group terms in Java expressions in the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write

a * ( b + c )

If an expression contains nested parentheses, such as

( ( a + b ) * c )

the expression in the innermost set of parentheses (a + b in this case) is evaluated first.

Rules of Operator Precedence

Java applies the operators in arithmetic expressions in a precise sequence determined by the rules of operator precedence, which are generally the same as those followed in algebra:

1. Multiplication, division and remainder operations are applied first. If an expression contains several such operations, they’re applied from left to right. Multiplication, division and remainder operators have the same level of precedence.

2. Addition and subtraction operations are applied next. If an expression contains several such operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence.

These rules enable Java to apply operators in the correct order.1 When we say that operators are applied from left to right, we’re referring to their associativity. Some operators associate from right to left. Figure A.12 summarizes these rules of operator precedence. A complete precedence chart is included in Appendix K.

1. We use simple examples to explain the order of evaluation of expressions. Subtle issues occur in the more complex expressions you’ll encounter. For more information on order of evaluation, see Chapter 15 of The Java Language Specification (https://docs.oracle.com/javase/specs/jls/se7/jls7.pdf).

Image

Fig. A.12 | Precedence of arithmetic operators.

Sample Algebraic and Java Expressions

Now let’s consider several expressions in light of the rules of operator precedence. Each example lists an algebraic expression and its Java equivalent. The following is an example of an arithmetic mean (average) of five terms:

Image

The parentheses are required because division has higher precedence than addition. The entire quantity (a + b + c + d + e) is to be divided by 5. If the parentheses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates as

Image

Here’s an example of the equation of a straight line:

Image

No parentheses are required. The multiplication operator is applied first because multiplication has a higher precedence than addition. The assignment occurs last because it has a lower precedence than multiplication or addition.

The following example contains remainder (%), multiplication, division, addition and subtraction operations:

Image

The circled numbers under the statement indicate the order in which Java applies the operators. The *, % and / operations are evaluated first in left-to-right order (i.e., they associate from left to right), because they have higher precedence than + and -. The + and - operations are evaluated next. These operations are also applied from left to right. The assignment (=) operation is evaluated last.

Evaluation of a Second-Degree Polynomial

To develop a better understanding of the rules of operator precedence, consider the evaluation of an assignment expression that includes a second-degree polynomial ax2 + bx + c:

Image

The multiplication operations are evaluated first in left-to-right order (i.e., they associate from left to right), because they have higher precedence than addition. (Java has no arithmetic operator for exponentiation in Java, so x2 is represented as x * x. Section C.16 shows an alternative for performing exponentiation.) The addition operations are evaluated next from left to right. Suppose that a, b, c and x are initialized (given values) as follows: a = 2, b = 3, c = 7 and x = 5. Figure A.13 illustrates the order in which the operators are applied.

Image

Fig. A.13 | Order in which a second-degree polynomial is evaluated.

A.8 Decision Making: Equality and Relational Operators

A condition is an expression that can be true or false. This section introduces Java’s if selection statement, which allows a program to make a decision based on a condition’s value. For example, the condition “grade is greater than or equal to 60” determines whether a student passed a test. If the condition in an if statement is true, the body of the if statement executes. If the condition is false, the body does not execute. We’ll see an example shortly.

Conditions in if statements can be formed by using the equality operators (== and !=) and relational operators (>, <, >= and <=) summarized in Fig. A.14. Both equality operators have the same level of precedence, which is lower than that of the relational operators. The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right.

Image

Fig. A.14 | Equality and relational operators.

Figure A.15 uses six if statements to compare two integers input by the user. If the condition in any of these if statements is true, the statement associated with that if statement executes; otherwise, the statement is skipped. We use a Scanner to input the integers from the user and store them in variables number1 and number2. The program compares the numbers and displays the results of the comparisons that are true.


 1  // Fig. A.15: Comparison.java
 2  // Compare integers using if statements, relational operators
 3  // and equality operators.
 4  import java.util.Scanner; // program uses class Scanner
 5
 6  public class Comparison
 7  {
 8     // main method begins execution of Java application
 9     public static void main( String[] args )
10     {
11        // create Scanner to obtain input from command line
12        Scanner input = new Scanner( System.in );
13
14        int number1; // first number to compare
15        int number2; // second number to compare
16
17        System.out.print( "Enter first integer: " ); // prompt
18        number1 = input.nextInt(); // read first number from user
19
20        System.out.print( "Enter second integer: " ); // prompt
21        number2 = input.nextInt(); // read second number from user
22
23        if ( number1 == number2 )                              
24           System.out.printf( "%d == %d ", number1, number2 );
25
26        if ( number1 != number2 )                              
27           System.out.printf( "%d != %d ", number1, number2 );
28
29        if ( number1 < number2 )                              
30           System.out.printf( "%d < %d ", number1, number2 );
31
32        if ( number1 > number2 )                              
33           System.out.printf( "%d > %d ", number1, number2 );
34
35        if ( number1 <= number2 )                              
36           System.out.printf( "%d <= %d ", number1, number2 );
37
38        if ( number1 >= number2 )                              
39           System.out.printf( "%d >= %d ", number1, number2 );
40     } // end method main
41  } // end class Comparison


Enter first integer: 777
Enter second integer: 777
777 == 777
777 <= 777
777 >= 777



Enter first integer: 1000
Enter second integer: 2000
1000 != 2000
1000 < 2000
1000 <= 2000



Enter first integer: 2000
Enter second integer: 1000
2000 != 1000
2000 > 1000
2000 >= 1000


Fig. A.15 | Compare integers using if statements, relational operators and equality operators.

The declaration of class Comparison begins at line 6. The class’s main method (lines 9–40) begins the execution of the program. Line 12 declares Scanner variable input and assigns it a Scanner that inputs data from the standard input (i.e., the keyboard).

Lines 14–15 declare the int variables used to store the values input from the user.

Lines 17–18 prompt the user to enter the first integer and input the value, respectively. The input value is stored in variable number1.

Lines 20–21 prompt the user to enter the second integer and input the value, respectively. The input value is stored in variable number2.

Lines 23–24 compare the values of number1 and number2 to determine whether they’re equal. An if statement always begins with keyword if, followed by a condition in parentheses. An if statement expects one statement in its body, but may contain multiple statements if they’re enclosed in a set of braces ({}). The indentation of the body statement shown here is not required, but it improves the program’s readability by emphasizing that the statement in line 24 is part of the if statement that begins at line 23. Line 24 executes only if the numbers stored in variables number1 and number2 are equal (i.e., the condition is true). The if statements in lines 26–27, 29–30, 32–33, 35–36 and 38–39 compare number1 and number2 using the operators !=, <, >, <= and >=, respectively. If the condition in one or more of the if statements is true, the corresponding body statement executes.


Image Common Programming Error A.3

Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error. The equality operator should be read as “is equal to” and the assignment operator as “gets” or “gets the value of.” To avoid confusion, some people read the equality operator as “double equals” or “equals equals.”


There’s no semicolon (;) at the end of the first line of each if statement. Such a semicolon would result in a logic error at execution time. For example,

if ( number1 == number2 ); // logic error
   System.out.printf( "%d == %d ", number1, number2 );

would actually be interpreted by Java as

if ( number1 == number2 )
   ; // empty statement
System.out.printf( "%d == %d ", number1, number2 );

where the semicolon on the line by itself—called the empty statement—is the statement to execute if the condition in the if statement is true. When the empty statement executes, no task is performed. The program then continues with the output statement, which always executes, regardless of whether the condition is true or false, because the output statement is not part of the if statement.

Note the use of white space in Fig. A.15. Recall that the compiler normally ignores white space. So, statements may be split over several lines and may be spaced according to your preferences without affecting a program’s meaning. It’s incorrect to split identifiers and strings. Ideally, statements should be kept small, but this is not always possible.

Figure A.16 shows the operators discussed so far in decreasing order of precedence. All but the assignment operator, =, associate from left to right. The assignment operator, =, associates from right to left, so an expression like x = y = 0 is evaluated as if it had been written as x = (y = 0), which first assigns the value 0 to variable y, then assigns the result of that assignment, 0, to x.

Image

Fig. A.16 | Precedence and associativity of operators discussed.

A.9 Wrap-Up

In this appendix, you learned many important features of Java, including displaying data on the screen in a Command Prompt, inputting data from the keyboard, performing calculations and making decisions. The applications presented here introduced you to basic programming concepts. As you’ll see in Appendix B, Java applications typically contain just a few lines of code in method main—these statements normally create the objects that perform the work of the application. In Appendix B, you’ll learn how to implement your own classes and use objects of those classes in applications.

Self-Review Exercises

A.1 Fill in the blanks in each of the following statements:

a) A(n) __________ begins the body of every method, and a(n) __________ ends the body of every method.

b) The __________ statement is used to make decisions.

c) __________ begins an end-of-line comment.

d) __________, __________ and __________ are called white space.

e) __________ are reserved for use by Java.

f) Java applications begin execution at method __________.

g) Methods __________, __________ and __________ display information in a command window.

A.2 State whether each of the following is true or false. If false, explain why.

a) Comments cause the computer to print the text after the // on the screen when the program executes.

b) All variables must be given a type when they’re declared.

c) Java considers the variables number and NuMbEr to be identical.

d) The remainder operator (%) can be used only with integer operands.

e) The arithmetic operators *, /, %, + and - all have the same level of precedence.

A.3 Write statements to accomplish each of the following tasks:

a) Declare variables c, thisIsAVariable, q76354 and number to be of type int.

b) Prompt the user to enter an integer.

c) Input an integer and assign the result to int variable value. Assume Scanner variable input can be used to read a value from the keyboard.

d) Print "This is a Java program" on one line in the command window. Use method System.out.println.

e) Print "This is a Java program" on two lines in the command window. The first line should end with Java. Use method System.out.println.

f) Print "This is a Java program" on two lines in the command window. The first line should end with Java. Use method System.out.printf and two %s format specifiers.

g) If the variable number is not equal to 7, display "The variable number is not equal to 7".

A.4 Identify and correct the errors in each of the following statements:

a)

if ( c < 7 );
    System.out.println( "c is less than 7" );

b)

if ( c => 7 )
    System.out.println( "c is equal to or greater than 7" );

A.5 Write declarations, statements or comments that accomplish each of the following tasks:

a) State that a program will calculate the product of three integers.

b) Create a Scanner called input that reads values from the standard input.

c) Declare the variables x, y, z and result to be of type int.

d) Prompt the user to enter the first integer.

e) Read the first integer from the user and store it in the variable x.

f) Prompt the user to enter the second integer.

g) Read the second integer from the user and store it in the variable y.

h) Prompt the user to enter the third integer.

i) Read the third integer from the user and store it in the variable z.

j) Compute the product of the three integers contained in variables x, y and z, and assign the result to the variable result.

k) Display the message "Product is" followed by the value of the variable result.

A.6 Using the statements you wrote in Exercise A.5, write a complete program that calculates and prints the product of three integers.

Answers to Self-Review Exercises

A.1

a) left brace ({), right brace (}).

b) if.

c) //.

d) Space characters, newlines and tabs.

e) Keywords.

f) main.

g) System.out.print, System.out.println and System.out.printf.

A.2

a) False. Comments do not cause any action to be performed when the program executes. They’re used to document programs and improve their readability.

b) True.

c) False. Java is case sensitive, so these variables are distinct.

d) False. The remainder operator can also be used with noninteger operands in Java.

e) False. The operators *, / and % are higher precedence than operators + and -.

A.3

a)

int c, thisIsAVariable, q76354, number;

or

int c;
int thisIsAVariable;
int q76354;
int number;

b) System.out.print( "Enter an integer: " );

c) value = input.nextInt();

d) System.out.println( "This is a Java program" );

e) System.out.println( "This is a Java program" );

f) System.out.printf( "%s %s ", "This is a Java", "program" );

g)

if ( number != 7 )
   System.out.println( "The variable number is not equal to 7" );

A.4

a) Error: Semicolon after the right parenthesis of the condition ( c < 7 ) in the if. Correction: Remove the semicolon after the right parenthesis. [Note: As a result, the output statement will execute regardless of whether the condition in the if is true.]

b) Error: The relational operator => is incorrect. Correction: Change => to >=.

A.5

a) // Calculate the product of three integers

b) Scanner input = new Scanner( System.in );

c)

int x, y, z, result;

or

int x;
int y;
int z;
int result;

d) System.out.print( "Enter first integer: " );

e) x = input.nextInt();

f) System.out.print( "Enter second integer: " );

g) y = input.nextInt();

h) System.out.print( "Enter third integer: " );

i) z = input.nextInt();

j) result = x * y * z;

k) System.out.printf( "Product is %d ", result );

A.6 The solution to Self-Review Exercise A.6 is as follows:


 1  // Exercise A.6: Product.java
 2  // Calculate the product of three integers.
 3  import java.util.Scanner; // program uses Scanner
 4
 5  public class Product
 6  {
 7     public static void main( String[] args )
 8     {
 9        // create Scanner to obtain input from command window
10        Scanner input = new Scanner( System.in );
11
12        int x; // first number input by user
13        int y; // second number input by user
14        int z; // third number input by user
15        int result; // product of numbers
16
17        System.out.print( "Enter first integer: " ); // prompt for input
18        x = input.nextInt(); // read first integer
19
20        System.out.print( "Enter second integer: " ); // prompt for input
21        y = input.nextInt(); // read second integer
22
23        System.out.print( "Enter third integer: " ); // prompt for input
24        z = input.nextInt(); // read third integer
25
26        result = x * y * z; // calculate product of numbers
27
28        System.out.printf( "Product is %d ", result );
29     } // end method main
30  } // end class Product


Enter first integer: 10
Enter second integer: 20
Enter third integer: 30
Product is 6000


Exercises

A.7 Fill in the blanks in each of the following statements:

a) __________ are used to document a program and improve its readability.

b) A decision can be made in a Java program with a(n) __________.

c) Calculations are normally performed by __________ statements.

d) The arithmetic operators with the same precedence as multiplication are and __________.

e) When parentheses in an arithmetic expression are nested, the __________ set of parentheses is evaluated first.

f) A location in the computer’s memory that may contain different values at various times throughout the execution of a program is called a(n) __________.

A.8 Write Java statements that accomplish each of the following tasks:

a) Display the message "Enter an integer: ", leaving the cursor on the same line.

b) Assign the product of variables b and c to variable a.

c) Use a comment to state that a program performs a sample payroll calculation.

A.9 State whether each of the following is true or false. If false, explain why.

a) Java operators are evaluated from left to right.

b) The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales$, his_$account_total, a, b$, c, z and z2.

c) A valid Java arithmetic expression with no parentheses is evaluated from left to right.

d) The following are all invalid variable names: 3g, 87, 67h2, h22 and 2h.

A.10 Assuming that x = 2 and y = 3, what does each of the following statements display?

a) System.out.printf( "x = %d ", x );

b) System.out.printf( "Value of %d + %d is %d ", x, x, ( x + x ) );

c) System.out.printf( "x =" );

d) System.out.printf( "%d = %d ", ( x + y ), ( y + x ) );

A.11 (Arithmetic, Smallest and Largest) Write an application that inputs three integers from the user and displays the sum, average, product, smallest and largest of the numbers. Use the techniques shown in Fig. A.15. [Note: The calculation of the average in this exercise should result in an integer representation of the average. So, if the sum of the values is 7, the average should be 2, not 2.3333....]

A.12 What does the following code print?

System.out.printf( "%s %s %s ", "*", "***", "*****" );

A.13 (Largest and Smallest Integers) Write an application that reads five integers and determines and prints the largest and smallest integers in the group. Use only the programming techniques you learned in this appendix.

A.14 (Odd or Even) Write an application that reads an integer and determines and prints whether it’s odd or even. [Hint: Use the remainder operator. An even number is a multiple of 2. Any multiple of 2 leaves a remainder of 0 when divided by 2.]

A.15 (Multiples) Write an application that reads two integers, determines whether the first is a multiple of the second and prints the result. [Hint: Use the remainder operator.]

A.16 (Diameter, Circumference and Area of a Circle) Here’s a peek ahead. In this appendix, you learned about integers and the type int. Java can also represent floating-point numbers that contain decimal points, such as 3.14159. Write an application that inputs from the user the radius of a circle as an integer and prints the circle’s diameter, circumference and area using the floating-point value 3.14159 for π. Use the techniques shown in Fig. A.7. [Note: You may also use the predefined constant Math.PI for the value of π. This constant is more precise than the value 3.14159. Class Math is defined in package java.lang. Classes in that package are imported automatically, so you do not need to import class Math to use it.] Use the following formulas (r is the radius):

diameter = 2r

circumference = 2πr

area = πr2

Do not store the results of each calculation in a variable. Rather, specify each calculation as the value that will be output in a System.out.printf statement. The values produced by the circumference and area calculations are floating-point numbers. Such values can be output with the format specifier %f in a System.out.printf statement. You’ll learn more about floating-point numbers in Appendix B.

A.17 (Separating the Digits in an Integer) Write an application that inputs one number consisting of five digits from the user, separates the number into its individual digits and prints the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the program should print


4  2  3  3  9


Assume that the user enters the correct number of digits. What happens when you execute the program and type a number with more than five digits? What happens when you execute the program and type a number with fewer than five digits? [Hint: It’s possible to do this exercise with the techniques you learned in this appendix. You’ll need to use both division and remainder operations to “pick off” each digit.]

A.18 (Table of Squares and Cubes) Using only the programming techniques you learned in this appendix, write an application that calculates the squares and cubes of the numbers from 0 to 10 and prints the resulting values in table format, as shown below. [Note: This program does not require any input from the user.]


number  square  cube
0       0       0
1       1       1
2       4       8
3       9       27
4       16      64
5       25      125
6       36      216
7       49      343
8       64      512
9       81      729
10      100     1000


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.171.212