CS 1401 Homework #9

Date Assigned: Tuesday, April 12, 2005
Due Date: Thursday, April 14, 2005, before the beginning of class.

Name (please type legibly, ideally in block letters): __________________________________________
UTEP ID # (if you do not remember it, it is OK): __________________________________________ 

Topics: Operators and switch statements

Question 1.  The increment (++) and decrement (--) operators in Java have two forms, the prefix form and the postfix form, as shown below using a variable j :

prefix form:              ++j;
postfix form:             j++;
When written by themselves as shown above, it usually doesn't matter whether the prefix or postfix form of the operators is used in your code.  When used inside larger expressions, however, there are side effects that you should keep in mind.

Recall that ++j may be translated as follows: "first, increment j by 1, and then use the new value of j."  On the other hand,  j++ means "first use the current value of  j and then increment j by 1."  

  a)  What are the values of the variables j and k after the following two statements are executed?

int j = 7 ;
int k = ++j ;


  b)  What are the values of the variables j and k after the following two statements are executed?

int j = 7 ;
int k = j++ ;


Question 2.  The Java increment and decrement operators are unary (single operand) operators.  Java also has a ternary (three operand) operator called the ?: or conditional operator.  (Refer to p. 456 in your textbook for more information.)

The ?: operator has the following logical format:

boolean expression  ?     action if true   :    action if false

This is just a shorter way of expressing the logic shown in the pseudocode shown below:

if  (boolean expression)   {
       take some action if true;
else   {
       take some other action if false;

 For example, if we want to obtain the larger of two numbers a and b, we could use the following expression:

(a > b?  :  b


The following code is an incomplete method designed to return the smaller of two integers a and bWrite the missing statements to complete the method.  Use the ?: operator in one of the statements.  Return the value of the smaller integer.  

  public int returnSmaller(int a, int b) {   


Question 3.  Read the following code fragment and answer the questions that follow.

int number = 20;
int sum = 0;
int j = 6;
int k = 10;
switch (Math.abs(j - k))
    case 4:
    case 3:  number += 7;
    case 2:  sum = ++number;   
    case 1:  sum = number--; 
    default: sum = number; 

a)  What are the values of the variables number and sum after this code executes?   


b)  In the space below (or on the back), convert the switch statement portion of the code above into an equivalent if statement.  Replace all ++, --, and += with statements using only +, -, and =.