Week 3 Answers


  1. In the following code:
        String a;
        String b;
        String c;
        String d;
    
        a = "hello";
        b = a;
        c = a;
        d = b;   // 1
        a = d;   // 2
    
    
    • How many references to "hello" are there after we've executed line "1"?

      4

    • What effect does line "2" have?

      None at all. The compiler might well optimize it out

    • How could you make a,b,c,d *all* contain a reference to the string "goodbye"?

      You have to assign the reference to each of a, b, c and d. e.g.

            a = "goodbye";
            b = a;
            c = a;
            d = a;
      
            // OR
            a = b = c = d = "goodbye"; // legal but horrible
      
  2. Write a program which has a function like this:
    
        void changeArgs(String name, int val) 
        {
             name = "a silly name";
             val = -1;
             System.out.println("I changed the args to : " + name + ", " + val);
        }
    
    
      and call the function using, e.g.
    
        String myName = "nick";
        int myAge = 21;
    
        System.out.println("I am " + myName + ", my age is " + myAge); // 1
        changeArgs(myName, myAge);
        System.out.println("I am " + myName + ", my age is " + myAge); // 2
    
    
    
    • Explain why "myName" and "myAge" are unchanged by the time you get to line "2"

      the changeArgs() method only alters the its own local references, it doesn't touch the variables that the caller passed

    • Can you alter the "changeArgs" function to make line "2" show myAge is -1?

      I can't think of how to do it

    • Can you alter the "changeArgs" function to make line "2" show myName is "a silly name?"

      I can't think of how to do it

    • What difference does it make it you make "name" be "final"?

      Means you can't assign any new value to it inside the function

    • What practical use is there to making "name" "final"?

      Maybe it is useful if you want to make sure you will not accidentally modify "name" to refer to something other than the caller's String

  3. For the following code, how much memory will be used by the object "myThing"?
       class Thing {
             int x;
             int y;
             char c;
             String s;
             java.util.Date d;
             public Thing(String a) { s = a; d = new java.util.Date(); }
       }
    
       ...
    
       Thing myThing = new Thing("hello");  // How much memory does myThing use
                                            // up?
    

    There's no way to do this. The JVM takes care of memory allocation and doesn't provide any standard way for you to interrogate it or work out how much it uses.


Back to index page