Exercises
Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from www.BruceEckel.com.
There are two expressions in the section labeled “precedence” early in this chapter. Put these expressions into a program and demonstrate that they produce different results.
Put the methods ternary( ) and alternative( ) into a working program.
From the sections labeled “if-else” and “return,” modify the two test( ) methods so that testval is tested to see if it is within the range between (and including) the arguments begin and end.
Write a program that prints values from 1 to 100.
Modify Exercise 4 so that the program exits by using the break keyword at value 47. Try using return instead.
Write a method that takes two String arguments and uses all the boolean comparisons to compare the two Strings and print the results. For the == and !=, also perform the equals( ) test. In main( ), call your method with some different String objects.
Write a program that generates 25 random int values. For each value, use an if-else statement to classify it as greater than, less than, or equal to a second randomly-generated value.
Modify Exercise 7 so that your code is surrounded by an “infinite” while loop. It will then run until you interrupt it from the keyboard (typically by pressing Control-C).
Write a program that uses two nested for loops and the modulus operator (%) to detect and print prime numbers (integral numbers that are not evenly divisible by any other numbers except for themselves and 1).
Create a switch statement that prints a message for each case, and put the switch inside a for loop that tries each case. Put a break after each case and test it, then remove the breaks and see what happens.