The JavaTM Tutorial
Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Language Basics

Answers to Questions and Exercises: Operators

Answers to Questions

  1. Consider the following code snippet:
    arrayOfInts[j] > arrayOfInts[j+1]
    
    Question: What operators does the code contain?
    Answer: [], >, [], +

  2. Consider the following code snippet:
    int i = 10;
    int n = i++%5;
    
    1. Question: What are the values of i and n after the code is executed?
      Answer: i is 11, and n is 0.]

    2. Question: What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?
      Answer: i is 11, and n is 1.

  3. Question: What is the value of i after the following code snippet executes?
    int i = 8;
    i >>=2;
    
    Answer: i is 2.

  4. Question: What is the value of i after the following code snippet executes?
    int i = 17;
    i >>=1;
    
    Answer: i is 8.

Exercises

  1. Exercise: Write a program that tests whether a floating point number is zero. (Hint: You shouldn't generally use the equality operator == with floating point numbers, since floating point numbers by nature are hard to match exactly. Instead, test whether the number is close to zero.)
    Solution: FloatTest (in a .java source file)

  2. Exercise: Write a program that calculates the number of US dollars equivalent to a given number of euros. Assume an exchange rate of 0.781162 euros per dollar. If you want to control the format of the numbers your program displays, you can use the DecimalFormat (in the API reference documentation) class, which is discussed in Formatting Numbers with Custom Formats (in the Learning the Java Language trail)
    Solution: CurrencyExchange (in a .java source file)

  3. Write a program that uses the bits in a single integer to represent the true/false data shown in the following figure:

    Include in the program a variable named status, and have the program print the meaning of status. For example, if status is 1 (only bit 0 is set) the program should print something like this:
    ready to receive requests
    
    1. Exercise: Show your code.
      Solution: Bits (in a .java source file)

    2. Exercise: What is the output when status is 8?
      Solution:
      unrecoverable error occurred
      
    3. Exercise: What is the output when status is 7?
      Solution:
      ready to receive requests
      processing a request
      error recovery in progress
      

Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.