Menu
Question Index
...

What will be the output of the following program?

public class LinkedClasses {
    public static void main(String[] args) {
        int count = 6;
        M m = new M(); m.print(count--);
        m.n = new N(); m.print(count--);
        m.n.o = new O(); m.print(count--);
        m.n.o.m = m; m.print(count--);
    }
}
class M {
    N n;
    void print(int count) {
        System.out.print("M" + count + " ");
        if (n != null && count > 0) n.print(count - 1);
    }
}
class N {
    O o;
    void print(int count) {
        System.out.print("N" + count + " ");
        if (o != null && count > 0) o.print(count - 1);
    }
}
class O {
    M m;
    void print(int count) {
        System.out.print("O" + count + " ");
        if (m != null && count > 0) m.print(count - 1);
    }
}


M5 M4 N3 M3 N2 O1 M2 N1 O0 M-1
M5 M4 N3 M3 N2 O1 M2 N1 O0
M6 M5 N4 M4 N3 O2 M3 N2 O1 M0
Some other output not shown here
Compilation Error or Run-time Error or goes into infinite loop

Doubts

Problems

Topic: Calling A Class From Another Class In Java

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App