Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz: Objects and References

DZone's Guide to

Java Quiz: Objects and References

An advanced Java quiz on how objects and object references behave.

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

First, let's see how we got the correct answer, F, from last week's quiz:

public void pirnt(){
        for(int i = 0; i < listMySub.size(); i ++ ) {
            if(i == 6) {
                System.out.println("Object6.id=" + listMySub.get(i).id + "    object6.getNumber()=" + listMySub.get(i).getNumber());
            }
            if(i == 8) {
                System.out.println("Object8.id=" + listMySub.get(i).id + "    object8.getNumber()=" + listMySub.get(i).getNumber());
            }
        }
    }
    public static void main(String[] args){
        MyApp ma = new MyApp();
        ma.method();
        ma.pirnt();
    }

Here's the next quiz, intended for advanced Java developers:

Purpose

  1. To demonstrate some behaviors and tricks of objects and object references.

What is written to the standard output as a result of executing the following code?

import java.util.ArrayList;
import java.util.List;

public class MyClass {

    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();

    public List<String> method(List<String> list){
        list.add("a");
        list.add("b");
        return list;
    }
    public static void main(String[] args){
        MyClass mc1 = new MyClass();
        MyClass mc2 = mc1;
        mc2.list1.add("c");
        mc2.list1 = mc2.list2;
        mc2.list1.add("d");
        List<String> list3 = mc2.method(mc2.list1);
        list3.add("e");
        System.out.println(mc1.list2);
    }
}


Let us know your thoughts in the comments, and visit Sar's site here!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,objects ,references ,quiz

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}