TheDerp TheDerp - 2 years ago 73
Java Question

How is the first line of output generated?

The following code showed up in a past paper with multiple mistakes (which i have spotted and fixed easily) but what i struggle to understand is the output.

The classes:

import java.util.*;
class Count {
int i, s, o, l, c;
public Count(Object[] objects){
for(int j=0; j<objects.length; j++){
public void count(Collection x){c++;}
public void count(List x){l++;}
public void count(Double x){i++;}
public void count(Object x){o++;}
public void count(String x){s++;}
public String toString(){
return c + ", " + l + ", " + i + ", " + o + ", " + s;

import java.util.LinkedList;
public class Test {
static Object[] objects = {new Double(10), new String("Q1"),
new Object(), new LinkedList()};
public static void main(String args[]){
System.out.println(new Count(objects));
for(Object o : objects)

Generated output:

0, 0, 0, 4, 0

I'd appreciate if someone could explain the output with reference to the code.

Side note: the first line of output is what puzzles me. The other bit i understand.
Last note: This is a unique question regarding the output. It is not a duplicate of any question (to the best of my knowledge - the link to the 'possible duplicate' is regarding method overloading not "how is this output produced?" and the outcomes in both questions are unique to each other) so a precise answer would be helpful. Thanks.

Answer Source
for(int j=0; j<objects.length; j++){

corresponds to

public void count(Object x){o++;} only

because the argument you're passing when you call count(objects[j]) is an object. You're calling a count function which has an object as parameter, and that's what Java is doing for you.

The number of objects in objects[] is 4. Hence count(Object x) gets called 4 times.

As regards the other integers, they are initialized by default to 0, and hence you see 0.

That's why you see 0 for all variables except o.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download