full file at ://fratstock.eu/sample/solutions-manual-java...• discover how to input data into...

22
Full file at https://fratstock.eu Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor’s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional Resources ey Terms K

Upload: others

Post on 27-Jul-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-1

Chapter 2 Basic Elements of Java At a Glance Instructor’s Manual Table of Contents • Overview

• Objectives • Teaching Tips Quick Quizzes •

Class Discussion Topics •

• Additional Projects

Additional Resources

• ey Terms

K

Page 2: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-2

Lecture Notes

verviewO

d e basic structure of a Java

program, including the import statement and commenting.

In this chapter, students will learn the basics of programming in Java. Fundamental topics include data types, arithmetic operations, precedence rules, type casting, input anoutput, and assignment operators. The chapter also covers th

hapter ObjectivesC

• omponents of a Java program, including methods, rs

xpressions ssions are evaluated

t operators

essary

• ow to properly structure a program, including using comments to document a program

Become familiar with the basic cspecial symbols, and identifie

• Explore primitive data types • Discover how to use arithmetic operators • Examine how a program evaluates arithmetic e• Explore how mixed expre• Learn about type casting • Become familiar with the String type • Learn what an assignment statement is and what it does • Discover how to input data into memory by using input statements • Become familiar with the use of increment and decremen• Examine ways to output results using output statements • Learn how to import packages and why they are nec• Discover how to create a Java application program

Explore h

eaching TipsT

1. lish a task, and that programming is a process of planning and

creating a program.

2. ,

ograms on the computer to make sure that each program does what it is supposed to do.

1. , and special words, and explain the difference between the syntax and the semantics.

Explain that a computer program, or a program, is a sequence of statements whose objective is to accomp

Explain that learning a programming language requires direct interaction with the toolsand emphasize that you must have a fundamental knowledge of the language, and you must test your pr

he Basics of a Java Program T

Explain that a programming language is a set of rules, symbols

Page 3: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-3

2. Explain that the smallest individual unit of a program written in any programming language is called a token. Java’s tokens are divided into special symbols, reserved words, and identifiers.

Special Symbols

1. Explain the special symbols presented on page 33, and note that a blank, which is not shown, is also a special symbol.

Teaching Tip

Emphasize that symbols comprised of two characters (such as <= and ==) are considered a single symbol, and a blank may not appear between the two characters.

Reserved Words (Keywords)

1. Explain that reserved words are called keywords and are always lowercase.

2. Emphasize that reserved words may not be used for any other purpose, or be redefined within any program.

Teaching Tip

Take time to give examples of reserved words, and explain that they are considered single symbols. Note that a complete list of reserved words in Java is in Appendix A.

Identifiers

1. Explain that identifiers are names of things, such as variables, constants, and methods, that appear in programs, and they may or may not be predefined.

2. Explain that a Java identifier consists of letters, digits, the underscore character ( _), and

the dollar sign ($), and must begin with a letter, underscore, or the dollar sign.

Teaching Tip

Stress the fact that Java is case sensitive, and walk through Example 2-2 to show examples of good and bad identifiers.

Data Types

1. Explain that a data type is a set of values together with a set of operations, and only certain operations can be performed on a particular type of data.

Page 4: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-4

Primitive Data Types

1. Explain that there are three primitive data types: integral, floating-point, and Boolean, and refer to Figure 2-1.

2. Refer to Figure 2-2 to explain that integral data types fall into five categories.

3. Explain that each data type has a different set of values associated with it, and walk

through Table 2-2, explaining the range of values associated with each integral data type. int Data Type

1. Explain that in Java, positive integers do not have to have a + sign in front of them, and no commas are used within an integer.

char Data Type

1. Explain that the char data type is used to represent single characters such as letters, digits, and special symbols, and it can represent any key on your keyboard.

2. Explain that each character represented is enclosed within single quotation marks, and

only one symbol can be placed between the single quotation marks.

3. Explain that Java uses the Unicode character set, which contains 65536 values numbered 0 to 65535, and each of the 65536 values of the Unicode character set represents a different character.

4. Explain that each character has a predefined ordering, which is called a collating

sequence, in the set, and it is used when comparing characters.

5. Explain that the newline character is represented as ‘\n’, the tab character is ‘\t’, and the null character is ‘\0’, and note that Appendix C has a list of characters.

boolean Data Type

1. Explain that the data type boolean has only two values: true and false, which are called the logical (Boolean) values. The central purpose of this data type is to manipulate logical (Boolean) expressions.

2. Explain that in Java, boolean, true, and false are reserved words, and the memory

allocated for the boolean data type is one bit. Floating-Point Data Types

1. Explain that the floating-point data types deal with decimal numbers, and to represent real numbers, Java uses a form of scientific notation called floating-point notation.

Page 5: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-5

2. Walk through Table 2-3 to show how decimal numbers are represented in floating-point notation, and point out that the E stands for the exponent.

3. Explain that as shown in Figure 2-3, the float and double types are used to represent

decimal numbers.

4. Explain that floats represent any real number between –3.4E+38 and 3.4E+38, and the memory allocated for the float data type is 4 bytes.

5. Explain that doubles are used to represent any real number between –1.7E+308 and

1.7E+308, and the memory allocated for the double data type is 8 bytes.

6. Explain that the maximum number of significant digits in float values is 6 or 7, while the maximum number of significant digits in double values is 15.

Teaching Tip

Emphasize that the default type of floating-point numbers is double. Therefore, using the data type float might produce an error, such as “truncation from double to float.” For students new to programming, it may not be obvious why using a float might cause a loss of data. Take time to explain truncation as it relates to the number of significant digits represented by each data type.

Teaching Tip

Take time to explain what a literal, or constant, is.

Arithmetic Operators and Operator Precedence 1. Walk through the five arithmetic operators, and point out that they can be used with both

integral and floating-point types. 2. Explain that integral division truncates any fractional part because there is no rounding. 3. Explain that an arithmetic expression is constructed by using arithmetic operators and

numbers, and the numbers in the expression are called operands. 4. Explain that the numbers used to evaluate an operator are called the operands for that

operator, and operators that have only one operand are called unary operators, and operators that have two operands are called binary operators.

Teaching Tip

Students new to programming may be unfamiliar with the concept of a unary operator. Take time to give examples of unary operators.

Page 6: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-6

5. Explain integer division, emphasizing that the division operator represents the quotient in ordinary division when used with integral types, and walk through Example 2-3.

Teaching Tip

Take time to work a few examples of integer division to make sure the concept is understood.

Teaching Tip

Students new to programming may be unfamiliar with the mod operator. Take time to work examples, and to explain some of the subtleties of using the mod operator with negative numbers.

Order of Precedence

1. Explain that Java uses operator precedence rules to determine the order in which operations are performed to evaluate the expression, and explain the precedence of the operators.

2. Explain that when arithmetic operators have the same precedence, they are evaluated

from left to right, but that parentheses can be used to group arithmetic expressions.

3. Walk through Example 2-5 to illustrate operator precedence and the use of parentheses.

4. Explain that because arithmetic operators are evaluated from left to right, unless parentheses are present, the associativity of arithmetic operators is said to be from left to right.

5. Explain that since the char data type is also an integral data type, Java allows you to

perform arithmetic operations on char data.

Teaching Tip

Emphasize the difference between the character ‘8’ and the integer 8, and work through several examples of using arithmetic operators on characters.

Expressions

1. Explain that if all operands in an expression are integers, the expression is called an integral expression, and if all operands in an expression are floating-point numbers, the expression is called a floating-point or decimal expression.

2. Use Example 2-6 and Example 2-7 to illustrate integral and floating-point expressions.

Page 7: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-7

Mixed Expressions

1. Explain that an expression that has operands of different data types is called a mixed expression.

2. Explain that if the operator has the same types of operands (that is, both are integers or

both are floating-point numbers), the operator is evaluated according to the type of the operand.

3. Explain that if the operator has both types of operands (that is, one is an integer and the

other is a floating-point number), during calculation the integer is changed to a floating-point number with the decimal part of zero, and then the operator is evaluated, and the result is a floating-point number.

4. Explain that the entire expression is evaluated according to the precedence rules, and use

Example 2-8 to show how to evaluate mixed expressions.

Teaching Tip

Provide many examples of mixed expressions, as many students fail to realize the importance of this aspect of programming. A good illustrative example is the calculation of an average using all integer division versus using mixed division.

Quick Quiz 1

1. The __________ rules of a language determine which instructions are valid. Answer: syntax 2. True or False: Hello! is an example of a legal identifier. Answer: False 3. True or False: The Boolean data type has two possible values – true and false. Answer: True 4. What is the value of the following expression? 3 + 4 * 5 Answer: 23

Type Conversion (Casting)

1. Explain that implicit type coercion occurs when a value of one data type is automatically changed to another data type.

2. Explain that to avoid implicit type coercion, Java provides for explicit type conversion

through the use of a cast operator.

Page 8: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-8

3. Explain that the cast operator, also called the type conversion or type casting, takes the form (dataTypeName) expression.

4. Explain that in type casting, the expression is evaluated first and its value is then

converted to a value of the type specified by dataTypeName.

5. Explain that when using the cast operator to convert a floating-point (decimal) number to an integer, you simply drop the decimal part of the floating-point number.

6. Work through Example 2-9 to demonstrate type conversion. 7. Explain that you can also use cast operators to explicitly convert char data values into int

data values, and int data values into char data values by using a collating sequence. class String

1. Explain that a string is a sequence of zero or more characters, and strings in Java are enclosed in double quotation marks.

2. Present the class String, which contains various operations to manipulate a string, and

note that it is presented in more detail in Chapter 3.

3. Explain that a string that contains no characters is called a null or empty string, and that strings such as “hello” are sometimes called character strings, string literals, or string constants.

4. Explain that the position of the first character is 0, the position of the second character is

1, and so on, and that the length of a string is the number of characters in it. Use Example 2-10 to illustrate these concepts.

Teaching Tip

Emphasize that spaces must be counted when computing the length of a string.

Input

1. Remind students that the main objective of Java programs is to perform calculations and manipulations on data, and the data must be loaded into main memory before it can be manipulated.

Allocating Memory with Named Constants and Variables

1. Explain that a named constant is a memory location whose content is not allowed to change during program execution, and explain the syntax to declare a named constant.

Page 9: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-9

2. Explain that the words static and final are reserved, and the word final specifies that the value stored in the identifier is fixed and cannot be changed.

Teaching Tip

Explain that Java programmers typically use uppercase letters to name a named constant.

Teaching Tip

Remind students that double is the default type for floating-point numbers, and explain the syntax for declaring a float.

3. Present the reasons for using named constants.

4. Explain that memory cells whose contents can be modified during program execution are called variables, and explain the syntax for declaring one variable or multiple variables.

Teaching Tip

Explain that Java programmers typically use lowercase letters to declare variables. If a variable name is a combination of more than one word, then the first letter of each word, except the first word, is uppercase.

Teaching Tip Emphasize that variables must be declared before they can be used.

Putting Data into Variables

1. Introduce this section by mentioning that the two common ways to place data into a variable are to use an assignment statement and to use an input, or read, statement.

Assignment Statement

1. Explain the syntax for variable assignment, and emphasize that the value of the expression should match the data type of the variable.

2. Define the term initialization and explain that the equals sign is the assignment operator.

3. Walk through Example 2-13 to illustrate variable assignment, and use the code fragment

to show the effect of the statements in the example.

Page 10: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-10

Teaching Tip

Explain that the Java language is strongly typed, which means that you cannot assign a value to a variable that is not compatible with its data type.

4. Explain that a statement such as x = y = z; is legal, and the associativity of the

assignment operator is said to be from right to left.

Saving and Using the Value of an Expression

1. Explain that to save the value of an expression and use it in a later expression, first declare a variable of the appropriate data type, and then use the assignment statement to assign the value of the expression to the variable that was declared.

2. Use Example 2-14 to illustrate saving the value of an expression to use it in a future

expression. Declaring and Initializing Variables

1. Remind students that using a variable without initializing it will likely generate a compiler error.

2. Explain that variables can be initialized when they are declared, and explain the syntax

for initializing variables at the time of declaration. Input (Read) Statement

1. Point out that in most cases, the standard input device is the keyboard, and that when the computer gets the data from the keyboard, the user is said to be acting interactively.

Teaching Tip

The rest of this subsection presents the methods of the Scanner class. For students new to programming, it may be helpful to briefly explain the syntax of the examples, including the creation of an instance of the Scanner class, the dot operator, and the method calls. Note that this will be covered in more detail later in the book.

2. Explain that to put data into variables, we create an input stream object and associate it

with the standard input device. Walk through the statement that accomplishes this.

3. Note that Scanner is a predefined Java class, and if the next statement can be interpreted as an integer, then the nextInt() method retrieves the integer.

4. Explain that if the next input token can be interpreted as a floating-point number, the

nextDouble() method retrieves the floating-point number.

Page 11: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-11

5. Explain that the method next() retrieves the next input token as a string, and the method nextLine() retrieves the next input as a string until the end of a line.

6. Emphasize that the expressions console.nextInt(),

console.nextDouble(), and console.next() skip whitespace characters.

7. Explain that System.in is called a standard input stream object and is designed to input data from the standard input device. However, the object System.in extracts data in the form of bytes from the input stream.

8. Explain that to use System.in, we first create a Scanner object so that the data can

be extracted in a desired form.

Teaching Tip

Note that the class Scanner is added to the Java library in Java version 5.0. Therefore, this class is not available in Java versions lower than 5.0.

9. Walk through Examples 2-15 through 2-17 to demonstrate how to read data of various

types from a standard input device.

10. Explain what a comment is, and emphasize that comments are ignored by the compiler. Variable Initialization

1. Explain that a variable can be initialized by an assignment statement, or by using an input statement.

2. Stress that a read statement is much more versatile than an assignment statement.

Reading a Single Character

1. Explain the syntax for reading a character using the next() method of the Scanner class and storing it in a char variable.

Teaching Tip

In the example in the book, the first character is read from the input using the charAt() method. Take time to explain the charAt() method, and to walk through Example 2-18 to explain reading input in and storing it in variables.

Increment and Decrement Operators

1. Explain that the increment operator, ++, increases the value of a variable by 1, and the decrement operator, --, decreases the value of a variable by 1.

Page 12: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-12

2. Explain that the increment and decrement operators each have two forms, pre and post, and explain the syntax of the increment and decrement operators.

3. Explain the difference between pre- and post-increment and pre- and post-decrement

operators, and walk through Example 2-19.

Teaching Tip

It may be helpful to work through several examples to illustrate the difference between pre- and post- increment and decrement operations.

Teaching Tip

Point out that pre-increment operators and post-increment operators are also referred to as prefix operators and postfix operators, respectively. These operators have the highest level of precedence.

Teaching Tip

Note that the result of the unary expression must be a variable of a numeric type, or a compile-time error occurs.

Strings and the Operator +

1. Explain that string concatenation allows a string to be appended to the end of another string, using the operator +.

2. Illustrate string concatenation using Example 2-20, pointing out that the operator + can

be used to concatenate two strings, as well as a string and a numeric value or a character. Quick Quiz 2

1. If an operator has an integer and a floating-point operand, the result of the operation is

a(n) __________ number. Answer: floating-point

2. The expression (int)9.2 evaluates to __________.

Answer: 9 3. True or False: The value of a variable can change during execution.

Answer: True 4. Suppose a and b are int variables. What is the value of b?

a = 3; b = 4 + (++a) Answer: 8

Page 13: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-13

Output

1. Note that the standard output device is usually the monitor. 2. Explain that in Java, output on the standard output device is accomplished by using the

standard output object System.out.

3. Explain that the object System.out has access to two methods, print and println, to output a string on the standard output device.

4. Explain the syntax of the print and println methods and the difference between

them.

5. Explain that the statement System.out.println(); prints a blank line, and point out that the empty parentheses are necessary.

6. Explain that when an output statement outputs char values, it outputs the character

without the single quotation marks. Similarly, the value of a string does not include the double quotation marks, unless they are explicitly included as part of the string.

7. Walk through Examples 2-21 through 2-24 to illustrate output statements.

8. Walk through Table 2-4, explaining each of the escape characters, and use Example 2-25

for illustration. Method flush

1. Explain that the output generated by the methods print and println first goes into an area in the computer called a buffer.

2. Explain that when the buffer is full, the output is sent to the output device, and you can

use the method flush associated with System.out to empty the buffer even if it is not full.

Packages, Classes, Methods, and the import Statement

1. Introduce packages by explaining that only a small number of operations are defined in Java. Explain that many of the methods and identifiers needed to run a Java program are provided as a collection of libraries.

2. Explain that a package is a collection of related classes and every package has a name.

3. Explain that the term class is broadly used. It is used to create Java programs—either

application or applet, it is used to group a set of related operations, and it is used to allow users to create their own data types.

Page 14: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-14

4. Explain that each of these operations is implemented using the Java mechanism of methods.

5. Explain that a method is a set of instructions designed to accomplish a specific task.

6. Explain that to make use of the existing classes, methods, and identifiers, you must

specify the packages that contain the appropriate information using the reserved word import.

7. Explain the syntax of the import statement, emphasizing that import statements are

placed at the top of the program.

Teaching Tip

Point out to students that if you use the wildcard character (*) in the import statement, the compiler determines the relevant class(es) used in the program.

Teaching Tip

Explain that the primitive data types are directly part of the Java language, and do not require that any package be imported into the program. Also, the class String is contained in the package java.lang. Emphasize that it is not necessary to import classes from the package java.lang because the system automatically does it for you. Note that mathematical functions are in the class Math in the package java.util, which must be imported.

Creating a Java Application Program

1. Explain that the basic unit of a Java program is called a class, and a Java application program is a collection of one or more classes.

2. Remind students that a method is a set of instructions designed to accomplish a specific

task, and some predefined or standard methods such as nextInt, print, and println are already written and are provided as part of the system.

3. Explain that to accomplish most tasks, programmers must write their own methods.

Teaching Tip

Emphasize that although it is often necessary to write a new method, whenever possible it is desirable to use a previously written method. Discuss reasons why.

4. Explain that one of the classes in a Java application program must have the method

called main, and there can be only one method main in a Java program. 5. Emphasize that if a Java application program has only one class, it must contain the

method main.

Page 15: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-15

6. Explain that statements to declare memory spaces (named constants and variables), statements to create input stream objects, statements to manipulate data (such as assignments), and statements to input and output data will be placed within the class.

7. Explain that statements to declare named constants and input stream objects are usually

placed outside the method main, and statements to declare variables are usually placed within the method main.

8. Explain that statements to manipulate data and input and output statements are placed

within the method main.

9. Explain the syntax of a class to create a Java application program, and explain the general syntax of the method main.

10. Explain that the import statements and the program statements constitute the Java source

code, which must be saved in a file called a source file that has the name extension .java.

11. Emphasize that the name of the class and the name of the file containing the Java program must be the same.

12. Explain that public static void main(String[] args) is called the heading

of the method main.

13. Explain that the statements enclosed between curly braces ({ and }) form the body of the method main.

14. Explain that the body of the method main contains two types of statements: declaration

statements and executable statements.

15. Explain that declaration statements are used to declare things such as variables.

16. Explain that executable statements perform calculations, manipulate data, create output, accept input, and so on.

17. Explain that variables or identifiers can be declared anywhere in the program, but must

be declared before they can be used.

18. Walk through Examples 2-26 through 2-28 to illustrate the concepts in this section.

Page 16: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-16

Teaching Tip

The reserved word static may be a source of confusion to students. Point out that the heading of the method main contains the reserved word static. The statements to declare the named constants and the input stream objects are placed outside the definition of the method main. Therefore, Java requires that you declare the named constants and the input stream objects with the reserved word static. Note that static variables and classes will be discussed in more detail later in the book.

Programming Style and Form

1. Introduce this section by emphasizing that a program must be understandable to other programmers, and also observe the correct syntax.

Syntax

1. Remind students that the syntax rules of a language tell what is legal and what is illegal. Errors in syntax are detected during compilation.

Teaching Tip

Emphasize that when the first syntax error is removed and the program is recompiled, subsequent syntax errors caused by the first syntax error may disappear. Therefore, you should correct syntax errors in the order in which the compiler lists them.

Use of Blanks

1. Remind students that in Java, you use one or more blanks to separate numbers when data is input, and blanks are also used to separate reserved words and identifiers from each other and from other symbols.

Teaching Tip

Emphasize that blanks (and whitespace in general) make the program much more readable.

Use of Semicolons, Braces, and Commas

1. Explain that all Java statements must end with a semicolon, and the semicolon is also called a statement terminator.

2. Explain that braces can be regarded as delimiters, because they enclose the body of a

method and set it off from other parts of the program.

3. Explain that commas are used to separate items in a list.

Page 17: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-17

Semantics

1. Explain that the set of rules that gives meaning to a language is called semantics.

2. Describe the difference between syntax and semantic errors. Naming Identifiers

1. Explain what self-documenting identifiers are, and that self-documenting identifiers can make comments less necessary.

2. Explain that an identifier used to name a named constant is all uppercase, and if the

identifier is a run-together-word, then the words are separated with the underscore character.

3. Explain that an identifier used to name a variable is lowercase, and if the identifier is a

run-together-word, then the first letter of each word, except the first word, is uppercase. 4. Explain that an identifier used to name a class is all lowercase with the first letter of each

word in uppercase. Prompt Lines

1. Explain that part of good documentation is the use of clearly written prompts so that users will know what to do when they interact with a program.

2. Explain that prompt lines are executable statements that inform the user what to do.

3. Explain that in a program, whenever users must provide input, you must include the

necessary prompt lines. Furthermore, these prompt lines should include as much information as possible about what input is acceptable.

Teaching Tip

Take time to emphasize that prompt lines should only be included when they are specifically called for, and point out that many programs (such as those acting on data files) do not require prompts. Emphasize that there are other ways for the user to interact with the program, and these will be discussed later in the book.

Documentation

1. Explain that a well-documented program is easier to understand and modify, even a long time after you originally write it. Explain that comments are used to document programs.

2. Explain that comments should appear in a program to explain the purpose of the

program, identify who wrote it, and explain the purpose of particular statements.

Page 18: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-18

Comments

1. Explain that single line comments begin with // and can be placed anywhere in the line, and explain that everything after the // is ignored by the compiler.

2. Explain that multiple line comments are enclosed between /* and */ and the compiler

ignores anything that appears between /* and */.

Teaching Tip

Emphasize that single line comments can not include a newline, but that multiline comments may.

Form and Style

1. Emphasize that programs should be properly indented and formatted, and to document the variables, programmers typically declare one variable per line, and put a space before and after an operator.

2. Walk through Example 2-29 to show the difference between poor use of white space and

proper use of whitespace. More on Assignment Statements

1. Discuss the compound operators *=, +=, -=, /=, and %=.

2. Explain that the compound assignment statement lets you write simple assignment statements concisely by combining an arithmetic operator with an assignment operator.

3. Walk through Example 2-30, which demonstrates the use of compound statements.

Programming Example: Convert Length

1. Walk through this example, which converts measurements in feet and inches into centimeters using the formula that 1 inch is equal to 2.54 centimeters.

Programming Example: Make Change

1. Walk through this programming example, which computes the number of half-dollars, quarters, dimes, nickels, and pennies to be returned, returning as many half-dollars as possible, then quarters, dimes, nickels, and pennies, in that order.

Quick Quiz 3

1. True or False: Java always initializes the value of a variable.

Answer: False

Page 19: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-19

2. Given the following assignments, what is the value in str? String str; str = “Hello”; str = str + “ World”; Answer: Hello World

3. A(n) __________ is a set of instructions designed to accomplish a specific task.

Answer: method

4. Given the following statements, what is the value of myVar? int myVar = 0; int a = 5, b = 2; myVar = a / b; Answer: 2

Class Discussion Topics

1. What are possible errors and exceptions that might arise in any Java program? 2. Why would it be desirable to use pre-written code whenever possible? 3. Why is it important that code be well-commented and well-formatted? 4. What are ways to debug code?

Additional Projects

1. Write a program that prompts the user for two characters and prints the sum of their Unicode values.

2. Write a program that prompts the user for an amount in dollars and converts it to the

equivalent amount in euros (you can either assume that 1 euro = $1.25, or look up the current exchange rate on the Web).

3. Write a program that prompts the user for a temperature in degrees Fahrenheit and

converts it to Celsius. Additional Resources

1. A complete listing of Java data types: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

2. More information on expressions and a complete listing of operator precedence rules in Java: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html

Page 20: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-20

3. Complete definitions of the predefined Java classes and Java API specifications: http://java.sun.com/reference/api/index.html

4. A description of Java code conventions widely accepted in the Java community:

http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

5. It is common practice to write Java comments that are compatible with the SunMicrosystems’ JavaDoc tool. This tool is capable of creating organized documentation for a Java project simply by parsing the comments in the Java source files. A thorough description of the JavaDoc standard can be found at: http://java.sun.com/j2se/javadoc/writingdoccomments/index.html

Key Terms

arithmetic expression—An expression constructed by using arithmetic operators and numbers.

assignment operator—The (=) the equals sign. Assigns a value to an identifier. associativity—The order in which an operator is evaluated. binary operator—An operator that has two operands. Boolean—A data type that deals with logical values. cast operator—Used for explicit type conversion. character string—see string class—Is used to create Java programs, either application or applet; it is used to group a

set of related operations, and it is used to allow users to create their own data types. collating sequence—A specific non-negative integer value in the Unicode character

set. computer program—A sequence of statements whose objective is to accomplish a

task. data type—A set of values together with a set of operations. decimal expression—See floating-point expression declaration statement—Used to declare things such as variables. decrement operator—(--), which decreases the value of a variable by 1. double precision—Values of type double. executable statements—Perform calculations, manipulate data, create output, accept

input, and so on. floating point expression—An expression in which all operands in the expression are

floating-point numbers. floating-point notation—A form of scientific notation used by Java to represent real

numbers. identifier—Consists of letters, digits, the underscore character ( _), and the dollar sign

($), and must begin with a letter, underscore, or the dollar sign. implicit type coercion—When a value of one data type is automatically changed to

another data type. increment operator—(++), which increases the value of a variable by 1. initialized—A named constant that is declared integral—A data type that deals with integers, or numbers without a decimal part. integral expression—An expression where all operands are integers

Page 21: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-21

keyword—A symbol that can not be redefined within any program. Also called a reserved word.

length—Describes the number of characters in a string. logical (Boolean) expression—An expression that evaluates to true or false. method—A set of instructions designed to accomplish a specific task. mixed expression—An expression that has operands of different data types. multiple line comments—Comments that are enclosed between /* and */. The

compiler ignores anything that appears between /* and */. named constant—A memory location whose content is not allowed to change during

program execution. null (empty)—A string containing no characters. operands—The numbers and alphabetical symbols in the expression. operator precedence rules—Determine the order in which operations are performed to

evaluate an expression. output statements—Any statement that sends data to the output device. Typically the

output statement will print data to the monitor. package—A collection of related classes. precedence—See operator precedence rules precision—The maximum number of significant digits. predefined methods—Methods that are included in the Java class library. programming—A process of planning and creating a program. programming language—A set of rules, symbols, and special words. prompt lines—Executable statements that inform the user what to do. run-together word—When the name of a constant is a combination of more than one

word. self-documenting identifiers—Identifiers in the second set of statements. semantics—The set of rules that gives meaning to a language. semantic rules—Determine the meaning of instructions in a programming language. single line comment—A statement that begins with // and can be placed anywhere in

the line. single precision—Values of type float. source code—The combination of the import statements and the program statements. source file—A file containing the source code, having the file extension .java. standard input stream object—An object that is designed to receive input from the

input device, such as System.in. standard methods—See predefined methods standard output object—An object that is designed to send data to the output device,

such as System.out. statement terminator—The semicolon (;) that terminates a statement. string—A sequence of zero or more characters, which is enclosed in double quotation

marks. string constant—See String string literal—See String syntax rules—Rules of a programming language that determine the validity of

instructions. token—The smallest individual unit of a program written in any programming

language. type casting—See cast operator type conversion—See cast operator

Page 22: Full file at ://fratstock.eu/sample/Solutions-Manual-Java...• Discover how to input data into memory by using input statements ... Stress the fact that Java is case sensitive, and

Full file at https://fratstock.euJava Programming: From Problem Analysis to Program Design, 3rd Edition 2-22

unary operator—An operator that has only one operand. variable —A memory location whose content may change during program execution.