Play Computer in Java Exercises

Do by hand first! Then you can run the code and check. Make sure you understand if the two are different!

  1. Instance Code Following Exercise

    What is printed by this program? That is the final answer, though you are recommended to write down the intermediate "playing computer" steps separately. Be sure to follow this code one step at a time! All needed code is in this one class X.

    public class X
    {
       private String s;
       private String t;
    
       public static void main(String[] args)
       {
          X a = new X("the");              //1
          X b = new X("an");               //2
          b.change("oh");                  //3
          System.out.println(a));          //4
          System.out.println(b));          //5
       }
    
       public X(String str)                //6
       {
          s = str;                         //7
          t = "";                          //8
       }
    
       public void change(String z)        //9
       {
          s = s.toUpper() + z;            //10
          t = z + s;                      //11
       }
    
       public String toString()           //12
       {
          return "s:" + s + " t:" + t;    //13
       }
    }
    
  2. String Format Exercise

    What is printed by this code fragment?

    double x = 9/4, y = 41, z = y/4;
    System.out.println("01234567890123456789"));
    System.out.format("x:%4.1f y:%.1f z:%3.1f%n", x, y, z);
    System.out.format("All");
    System.out.println("done");
    
  3. What is printed by this program? Be able to explain!

    public class Ex3 {
    
        public static void main(String[] args)
        {
            System.out.println(f(2));
            System.out.println(f(2.5));
        }
    
        public static String f(double x)
        {
            return x +"!!";
        }
    
        public static String f(int x)
        {
            return 2*x +"??";
        }
    }