Menu
Question Index
...

What will be the output of the following program?

import java.util.*;
final class FinalTest {
    final int id;
    String name;
    final HashMap<String, String> testMap = new HashMap<String, String>();
    public int getId() {return id; }
    public String getName() {return name; }
    public HashMap<String, String> getTestMap() {
        return (HashMap<String, String>) Collections.unmodifiableMap(testMap);
    }
    public FinalTest(int i, String name, HashMap<String, String> hm) {
        id = i;
        this.name = name;
        Iterator<String> iterator = hm.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            testMap.put(key, hm.get(key));
        }
    }
}
public class FinalClazz {
    public static void main(String[] args) {
        HashMap<String, String> h1 = new HashMap<String, String>();
        h1.put("1", "first");
        h1.put("2", "second");
        FinalTest ce = new FinalTest(10, "Original", h1);
        System.out.println(ce.getId() + " " + ce.getName() + " " + ce.getTestMap().size());
        h1.put("3", "third");
        ce.name = "Changed";
        System.out.println(ce.getId() + " " + ce.getName() + " " + ce.getTestMap().size());
    }
}


10 Original 2
10 Changed 2
10 Original 2
10 Original 2
10 Original 2
10 Changed 3
Compilation Error
Runtime Error

Doubts

Problems

Topic: Java Read-only Collections And Algorithms

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App