Exercises 1

Many of the exercises are borrowed from Rich Pattis from Carnegie Mellon University. Many thanks to Rich for letting me use these.

  1.  Classify each of the following as a legal or illegal identifier. If it is illegal, propose a legal identifier that can take its place (a homophone or homoglyph)

    packAge x12 2Lips
    xOrY sum of squares %Raise
    termInAte u235 $Bill
    x_1


  2. Classify each of the following numeric literals as int, or double, or illegal (neither); write the equivalent value of each double without using E notation; for each illegal literal, write a legal one with the "same" value.

    5. 3.1415 17
    17.0 1E3 1.E3
    .5E-3 5.4x103 50E-1
    1,024

     

     

    0.087

     

     

    .087

     

     

  3. What is the difference between 5, 5., five, '5', and "5"? What is the difference between true and "true"?

  4. Choose an appropriate type to represent each of the following pieces of information

     
  5. Show a few different ways to declare A and B as int variables initially storing 0 and 1 respectively. Do it with one declaration statement; with two declaration statements; write slightly different variants of these that still accomplish the job.

     

  6. What are the results of each of the the following operators?
        7/10   7./10   7/10.   7./10.
        7/10   57/10   157/10   2157/10
        7%10   57%10   157%10   2157%10

     

  7. Show the result produced by each of the following operators/methods (or indicate that some syntax error is present). If the state of some variable is changed, show that too (and indicate any implicit conversions). Assume int x = 0; String s = "ABC"; before each call.
      false == false          'a' < 'Z'          'a'-'A'
      true  != true           true && false      true || false
      x++                     ++x                1 = x
      x = 1                   x == 1             x = 'A'
      Math.abs(-3.5)          Math.abs(3.5)      Math.max(3.5, 8)
      Math.sqrt(-1.)          Math.pow(-3.,2.)   Math.pow(-3.,.5)
    
      s = System.out.println("Hi");
    
  8. Translate each of the following mathematical formulas (7 on the top line, 3 on the middle and bottom lines) into Java expressions. Assume that all variables (some have subscripts) are declared to be of type double. Writing |x| means the absolute value of x. Analyze each expression by writing its oval diagram.

     

     

  9. Suppose that we declare int attendance = 3000, capacity=10000; the number of fans attending an event at a stadium and the maximum number of fans possible at that stadium respectively. Which of the following Java expressions evaluates to 30, the percentage of fans in the stadium? What do the "incorrect" expressions evaluate to?
            attendance/capacity
            100*attendance/capacity
            100*(attendance/capacity)
            attendance/capacity*100