Java Reference
In-Depth Information
Chapter Summary
An if statement lets you write code that will execute only
if a certain condition is met. An if/else statement lets
you execute one piece of code if a condition is met, and
another if the condition is not met. Conditions are Boolean
expressions and can be written using relational operators
such as < , >= , and != . You can test multiple conditions
using the && and || operators.
incrementally adds to that variable's value inside the
loop.
Since the double type does not store all values exactly,
small roundoff errors can occur when the computer per-
forms calculations on real numbers. Avoid these errors by
providing a small amount of tolerance in your code for
values near the values that you expect.
You can nest if/else statements to test a series of condi-
tions and execute the appropriate block of code on the
basis of whichever condition is true.
The char type represents individual characters of text.
Each letter of a String is stored internally as a char
value, and you can use the String 's charAt method to
access these characters with an index.
The == operator that tests primitive data for equality
doesn't behave the way we would expect with objects, so
we test objects for equality by calling their equals
method instead.
The System.out.printf method prints formatted text.
You can specify complex format strings to control the width,
alignment, and precision by which values are printed.
Common code that appears in every branch of an
if/else statement should be factored out so that it is not
replicated multiple times in the code.
You can “throw” (generate) exceptions in your own code.
This technique can be useful if your code ever reaches an
unrecoverable error condition, such as the passing of an
invalid argument value to a method.
Cumulative algorithms compute values incrementally.
A cumulative sum loop declares a sum variable and
Self-Check Problems
Section 4.1: if/else Statements
1. Translate each of the following English statements into logical tests that could be used in an if/else statement. Write
the appropriate if statement with your logical test. Assume that three int variables, x , y , and z , have been declared.
a. z is odd.
b. z is not greater than y 's square root.
c. y is positive.
d. Either x or y is even, and the other is odd.
e. y is a multiple of z .
f. z is not zero.
g. y is greater in magnitude than z .
h. x and z are of opposite signs.
i. y is a nonnegative one-digit number.
 
 
Search WWH ::




Custom Search