Review Exercises - Class 2

  1. What gets printed by the following Java statements? Try and figure this out by hand first and then check you answers by running them in DrJava.
          int x;
          x = 4/2;
          StdOut.println(x);
          x = 7/2;
          StdOut.println(x);      
          x = 1/2;
          StdOut.println(x);
          
  2. Recall how you did division in grade school using remainders. The remainder of 7 ÷ 2 is 1. Two goes into seven three times with one left over. The remainder is 31 ÷ 4 is 3. Assuming that x and y are integer variables, write a Java code segment that uses Java's basic arithmetic operators of +, -, *, / and computes and prints the remainder of x ÷ y.
  3. What gets printed by the following Java code segment. Again, do this as a mental exercise and then check your answers in DrJava.
          double pi;
          int x;      
          pi = 3.14159;
          x = (int) pi * 2;
          StdOut.println(x);
       
  4. What gets printed by the Java code segment below. Check your answer in DrJava.
          double x;
          double y;
          x = 2.4;
          y = Math.rint(x);
          StdOut.println(y);
          y = Math.rint(x*x);
          StdOut.println(y);
          
  5. Write a Java code segment that calculates the average of three integers x, y, and z.
  6. Write a Java code segment that calculates the average of three integers x, y, and z and prints the average rounded to one decimal place. For example the average of 7, 8, and 10 is 3.3. The average of 7, 8, and 11 is 8.7.
  7. What does DrJava tell you when you forget to declare a variable?
  8. The number 2147483647 is special in Computer Science (believe it or not). Assign this value to an integer variable and then add one to it like in the code below:
             int x;    
             x = 2147483647;
             StdOut.println(x + 1);
            
  9. Examine the following code. Mathematically x and y should be equal. What value should they be equal to? What happens when you execute the code? Can you explain what is going on?
          double x,y;
          x = 1 - (1/3.0 + 1/3.0 + 1/3.0);
          y = 1 - 1/3.0 - 1/3.0 - 1/3.0;
          StdOut.println(x);
          StdOut.println(y);
         
  10. In Physics Newton's law of gravitation says that two bodies are attracted to each other and is related to the product of their masses but inversely proportional as a square of their distance. F = Gm1m2/r2 , where G is Newton's gravitational constant. A Java programmer gets the wrong answer with the formula
                F = G * mass1 * mass2 / r * r;
             
    What is the error?