Documentation

The Java™ Tutorials
Hide TOC
Questions and Exercises问题和练习
Trail: Learning the Java Language
Lesson: Language Basics

Questions and Exercises: Operators问题和练习:运算符

Questions问题

  1. Consider the following code snippet.考虑下面的代码片段。
    arrayOfInts[j] > arrayOfInts[j+1]
    Which operators does the code contain?代码包含哪些运算符?>+
  2. Consider the following code snippet.考虑下面的代码片段。
    int i = 10;
    int n = i++%5;
    1. What are the values of i and n after the code is executed?代码执行后in的值是多少?110
    2. What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?如果不使用后缀增量运算符(i++),而是使用前缀版本(++i)),in的最终值是多少?111
  3. To invert the value of a boolean, which operator would you use?要反转boolean,您将使用哪个运算符?
  4. Which operator is used to compare two values, = or == ?哪个运算符用于比较两个值,=====
  5. Explain the following code sample:解释以下代码示例:result = someCondition ? value1 : value2;

Exercises练习

  1. Change the following program to use compound assignments:将以下程序更改为使用复合指定:
    class ArithmeticDemo {
    
         public static void main (String[] args){
              
              int result = 1 + 2; // result is now 3
              System.out.println(result);
    
              result = result - 1; // result is now 2
              System.out.println(result);
    
              result = result * 2; // result is now 4
              System.out.println(result);
    
              result = result / 2; // result is now 2
              System.out.println(result);
    
              result = result + 8; // result is now 10
              result = result % 7; // result is now 3
              System.out.println(result);
         }
    }
  2. In the following program, explain why the value "6" is printed twice in a row:在以下程序中,解释为何值“6”连续打印两次:
    class PrePostDemo {
        public static void main(String[] args){
            int i = 3;
            i++;
            System.out.println(i);    // "4"
            ++i;                     
            System.out.println(i);    // "5"
            System.out.println(++i);  // "6"
            System.out.println(i++);  // "6"
            System.out.println(i);    // "7"
        }
    }

Check your answers检查你的答案


Previous page: Summary of Operators
Next page: Expressions, Statements, and Blocks