Menu
Topics Index
...
`

Play Fair


If you need explanation Read this topic

If you need Answer Take test on this topic

Play Fair
What will be the output of the following program?
public class PlayFair {
    public static void main(String[] args) {
        StringIterator si = new StringIterator("PlayFair");
        p(si.next());         p(si.next());
        p(si.previous());     p(si.next());
        p(si.next());         p(si.previous());
        p(si.previous());
    }
    private static void p(Character c) { System.out.print(c); }
}
interface IIterator<T> {
    T next();
    T previous();
}
class StringIterator implements IIterator<Character> {
    String s;
    int position = 0;
    public StringIterator(String s) { this.s = s; }
    public Character next() {
        return position++ < s.length() ? s.charAt(position++) : null;
    }
    public Character previous() {
        return position-- >= 0 ? s.charAt(position--) : null;
    }
}

A. Plalaya
B. lalayal
C. lyyyaay
D. Some other output or Compilation Error
E. Runtime Error
Topic: Java Iterator

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is C. For the first call, position value is 0 and is incremented in the return statement and the condition is true so s.charAt() prints l and position is further incremented. for the second next(), position is 3 and incremented to 4 and the condiion satisfies ( 4 < 8) so y gets printed and position is further incremented. for the previous() position is first decremented i.e.,  equal to 3 and condition satisfies and y get printed and so on.

Posted by Nikhil Sulibhavi    2014-05-01 12:43:34


Ans is b ...the next previous functions print the corresponding characters in the string..Initially the pointer is at position 0..The next function called will print l and then a an d so on...So the output will be lalayal

Posted by Badam Swathi    2014-05-01 12:55:36


Congratulations Nikhil Sulibhavi. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-05-02 04:13:34


© meritcampus 2019

All Rights Reserved.

Open In App