Methods - Passing Values QuizS2C Home « Methods - Passing Values Quiz

Java Objects & Classes Quiz 6

The quiz below tests your knowledge of the material learnt in Objects & Classes - Lesson 6 - Methods - Passing Values.

Question 1 : We pass objects to methods as arguments?
- We DO NOT pass objects to methods as arguments, we actually pass a copy of the reference variable associated with that object.
Question 2 : What will be output from this code snippet?

package com.server2client;
public class Dog {
    String name;
    void dogLooks(String name) {
        name = "zzz";
    }
}

package com.server2client;
public class TestDog {
    public static void main (String[] args) {
        Dog doggy = new Dog();
        String name = "rover";
        doggy.dogLooks(name);
        System.out.println("Our dog is called: " + name);
    }
}
- The output will be <code>Our dog is called: rover</code> as we are passing a copy of the name parameter, the original remains unchanged and is printed on return.
Question 3 : Where are objects stored?
- Objects are stored on the <code>heap</code>.
Question 4 : We pass primitives to methods as arguments?
- We DO NOT pass primitives to methods as arguments, we actually pass a copy of the value associated with that primitive.
Question 5 : What will be output from this code snippet?

package com.server2client;
public class Dog {
    String name;
    void dogLooks(Dog dog) {
        dog.name = "zzz";
    }
}

package com.server2client;
public class TestDog {
    public static void main (String[] args) {
        Dog doggy = new Dog();
        doggy.name = "rover";
        doggy.dogLooks(doggy);
        System.out.println("Our dog is called: " + name);
    }
}
- The output will be <code>Our dog is called: zzz</code>; although we are passing a copy of the reference variable we are still updating the actual <code>Dog</code> object on the heap, so the original is changed and is printed on return.
Question 6 : When we pass an argument to a method what are we are actually passing?
- When we pass an argument to a method we are actually passing a copy of the argument and this is known as <i>pass-by-value</i>
Quiz Progress Bar Please select an answer


What's Next?

The in our final quiz on Java methods we test your knowledge of overloading and variable arguments.