uiz Space

May 2024 term · Programming Concepts using Java · BSCS2005

Programming Concepts using Java Quiz 2: 4 August 2024 (May 2024 term)

The IIT Madras BS Programming Concepts using Java (Java) Quiz 2 paper sat on 4 Aug 2024, in the May 2024 term: 15 questions for 100 marks in 120 minutes. Every question is below with its answer. Take it as a timed mock test to be marked, or read it through first.

Questions
15
Marks
100
Duration
120 min
MCQ
13
MSQ
2

Updated

Official paper: IIT M DIPLOMA AN EXAM QDD2 4 Aug 2024 · No negative marking.

Question 1

+6 marksOne correct option

Consider the Java code given below.

The method boolean containsKey (Object key) in the class Map returns true if and only if the map contains an entry for a key k such that Objects.equals(key, k).

java
import java.util.*;
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
System.out.println("Starting a Car");
}
}
class Motorcycle implements Vehicle {
public void start() {
System.out.println("Starting a Motorcycle");
}
}
class Garage<T extends Vehicle> {
private Map<String, T> vehicles;
public Garage() {
vehicles = new LinkedHashMap<String, T>();//LINE A
}
public void add(String name, T vehicle) {
vehicles.put(name, vehicle);
}
public void startVehicle(String name) {
if (vehicles.containsKey(name)) {
T v = vehicles.get(name); //LINE B
v.start();
} else {
System.out.println("Vehicle not found");
}
}
}
public class TestGarage {
public static void main(String[] args) {
Garage<Vehicle> g = new Garage<Vehicle>();
Vehicle v1 = new Car();
Vehicle v2 = new Motorcycle();
g.add("car", v1);
g.add("motorcycle", v2);
g.startVehicle("car");
g.startVehicle("bicycle");
}
}

Choose the correct option.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 2

+6 marksOne correct option

Consider two Java files located in two different packages as shown below.

Vehicle.java:

java
package com.transport;
public class Vehicle {
void startEngine() {
System.out.println("Engine started");
}
private void stopEngine() {
System.out.println("Engine stopped");
}
protected void accelerate() {
System.out.println("Accelerating");
}
public void brake() {
System.out.println("Braking");
}
}

Car.java

java
package com.automobile;
import com.transport.Vehicle;
public class Car extends Vehicle {
public static void main(String[] args) {
Car car = new Car();
car.startEngine(); // LINE A
car.stopEngine(); // LINE B
car.accelerate(); // LINE C
car.brake(); // LINE D
}
}

Choose the correct option.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • C

Question 3

+6 marksOne correct option

Consider the Java code given below.

java
class NewUser{
private String name, password;
public NewUser(String s, String p) {
this.name = s;
this.password = p;
}
public String getUserName() {
assert name != null : "Invalid name"; //LINE 1
assert password.length() == 10 : "Should be 10 characters"; //LINE 2
return name + "@acct.com";
}
}
public class Test {
public static void main(String[] args) {
NewUser u1 = new NewUser("", "password");
NewUser u2 = new NewUser("Sudarshan", "1234567890");
String username1 = u1.getUserName(); //LINE 3
assert username1 != null : "Should not be null"; // LINE 4
String username2 = u2.getUserName(); //LINE 5
assert username2 != null : "Should not be null"; // LINE 6
System.out.println(username1);
System.out.println(username2);
}
}

Choose the correct option when the program is executed as:
java -ea Test

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 4

+6 marksOne correct option

Consider the Java code given below.

java
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String, Integer> match1 = new TreeMap<String, Integer>();
match1.put("Sachin", 100);
match1.put("Virat", 75);
match1.put("Dhoni", 50);
match1.put("Rohit", 120);
Map<String, Integer> match2 = new TreeMap<String, Integer>();
match2.put("Sachin", 80);
match2.put("Virat", 90);
match2.put("Dhoni", 60);
match2.put("Rohit", 110);
Map<String, Integer> totalRuns = new TreeMap<String, Integer>();
for (Map.Entry<String, Integer> m1 : match1.entrySet())
totalRuns.put(m1.getKey(), m1.getValue());
for (Map.Entry<String, Integer> m2 : match2.entrySet())
totalRuns.merge(m2.getKey(), m2.getValue(), Integer::sum); //LINE 1
System.out.println(totalRuns);
}
}

Choose the correct option.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 5

+6 marksOne correct option

Consider the Java code given below.

java
import java.util.*;
public class SequenceChecker {
public static boolean isMirroredSequence(List<Integer> sequence) {
Stack<Integer> s1 = new Stack<>();
Deque<Integer> q1 = new ArrayDeque<>();
for (int num : sequence) {
s1.push(num);
q1.add(num);
}
// CODE BLOCK
return true;
}
public static void main(String[] args) {
List<Integer> sequence1 = Arrays.asList(1, 2, 3, 2, 1);
List<Integer> sequence2 = Arrays.asList(1, 2, 3, 4, 5);
System.out.println
("Is sequence1 mirrored? " + isMirroredSequence(sequence1));
System.out.println
("Is sequence2 mirrored? " + isMirroredSequence(sequence2));
}
}

Choose the correct option(s) to fill in place of CODE BLOCK so that the output is:
Is sequence1 mirrored? true
Is sequence2 mirrored? false

Please note the following methods from type Stack and Deque.
pop(): Removes the object at the top of this stack and returns that object as the value of this function.
poll(): Retrieves and removes the head of this deque, or returns null if this deque is empty.
peek(): Retrieves, but does not remove, the head of this deque, or returns null if this deque is empty.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • C

Question 6

+6 marksOne correct option

Consider the Java code given below.

java
import java.util.*;
class Book implements Cloneable {
String title;
String author;
public Book(String t, String a) {
this.title = t;
this.author = a;
}
public Book clone() throws CloneNotSupportedException {
return (Book) super.clone();
}
public String toString() {
return title + ":" + author;
}
}
class Library implements Cloneable {
String libraryName;
List<Book> books;
public Library(String l, List<Book> b) {
this.libraryName = l;
this.books = b;
}
public Library clone() throws CloneNotSupportedException {
Library clonedLibrary = (Library) super.clone();
clonedLibrary.books = new ArrayList<>();
for (Book book : this.books) {
clonedLibrary.books.add(book.clone());
}
return clonedLibrary;
}
}
public class TestCloning {
public static void main(String[] args) throws CloneNotSupportedException {
List<Book> books = new ArrayList<>();
books.add(new Book("1984", "George Orwell"));
books.add(new Book("Outline", "Rachel Cusk"));
Library library1 = new Library("Central Library", books);
Library library2 = library1.clone();
library2.books.get(0).title = "Hanging";
System.out.println(library1.books);
System.out.println(library2.books);
}
}

What will the output be?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • D

Question 7

+6 marksOne correct option

Consider the Java code given below.

java
import java.util.*;
import java.util.stream.*;
class Transaction {
String id;
double amount;
public Transaction(String i, double a) {
this.id = i;
this.amount = a;
}
public String toString() {
return id + ": $" + amount;
}
}
public class TransactionProcessor {
public static void main(String[] args) {
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(new Transaction("TXN1", 999.99));
transactions.add(new Transaction("TXN2", 5000.00));
transactions.add(new Transaction("TXN3", 1234.56));
transactions.add(new Transaction("TXN4", 2500.00));
transactions.add(new Transaction("TXN5", 330.40));
transactions.stream()
.filter(t -> t.amount > 1000)
.forEach(t -> System.out.print(t.id + " "));
}
}

What will the output be?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 8

+7 marksOne correct option

Consider the Java code given below.

java
interface Operable {
void operate();
}
class Robot implements Operable {
public void operate() {
System.out.println("Operating Robot");
}
}
class Drone implements Operable {
public void operate() {
System.out.println("Operating Drone");
}
}
class MachineShop {
private Object[] oArr = new Object[]{new Robot(), new Drone(), "String Object"};
public void operateMachines() {
for (int i = 0; i < oArr.length; i++) {
// LINE X
}
}
}
public class TestMachines {
public static void main(String[] args) {
MachineShop mShop = new MachineShop();
mShop.operateMachines();
}
}

Identify the appropriate option to fill in place of LINE X such that the output is:
Operating Robot
Operating Drone

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 9

+7 marksOne correct option

Consider the Java code given below.

java
public class ArrayOperations {
public <T> void reverse(T[] array) {
// Reverses the order of elements in the array
}
public <T extends Number> double sum(T[] array) {
// Calculates the sum of elements in the array
}
}

After type erasure, which of the following correctly represents the ArrayOperations class?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • A

Question 10

+7 marksOne correct option

Consider the Java code given below.

java
class InvalidTemperatureException extends RuntimeException {
public InvalidTemperatureException(String message) {
super(message);
}
}
class Thermostat {
private double temperature;
private final double MIN = 0.0;
private final double MAX= 35.0;
public Thermostat(double t) {
if (t < MIN || t > MAX) {
throw new InvalidTemperatureException
("Temperature out of operating range");
}
this.temperature = t;
}
}
public class ClimateControl {
public static void main(String[] args) {
try {
Thermostat t1 = new Thermostat(22.0);
Thermostat t2 = new Thermostat(36
.0);
} catch (InvalidTemperatureException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Choose the correct option.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 11

+7 marksOne correct option

Consider the Java code given below.

java
import java.util.*;
class Player {
String nickname;
int score;
boolean isPremium;
//Constructor to initialize instance variables
public String toString() {
return nickname;
}
}
public class GameLobby {
public static boolean isEligible(int score, boolean isPremium) {
if(isPremium){
return true;
}
return (score >= 10);
}
public static void filterPlayers(List<Player> players) {
ListIterator<Player> iterator = players.listIterator();
while (iterator.hasNext()) {
Player p = iterator.next();
if (!isEligible(p.score, p.isPremium))
-------------------------------- // LINE 1
}
}
public static void main(String[] args) {
var players = new LinkedList<Player>();
players.add(new Player("Sharon", 15, false));
players.add(new Player("Rohit", 8, false));
players.add(new Player("Arjun", 20, true));
players.add(new Player("Ambani", 9, true));
filterPlayers(players);
System.out.println(players);
}
}

Choose the correct option to be filled in place of LINE 1 so that the output is:
[Sharon, Arjun, Ambani]

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 12

+7 marksOne correct option

From among the options, choose the code segment that gives the same output as is given by the Java code inside the CODE BLOCK.

java
import java.util.stream.*;
public class Example {
public static void main(String[] args) {
//CODE BLOCK starts here
long count = Stream.iterate(1, n -> n + 2)
.map(n -> n * n)
.limit(4)
.count();
//CODE BLOCK ends here
System.out.println(count);
}
}
  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 13

+7 marksOne correct option

Consider the Java code given below.

java
import java.util.*;
public class MapTest {
public static void printPlayers(Map<String, Integer> m) {
var map1 = new LinkedHashMap<String, Integer>();
var map2 = new TreeMap<String, Integer>();
String[] players = {"Virat", "Rohit", "Rahul"};
for (String p : players) {
if (m.containsKey(p)) {
map1.put(p, m.get(p));
map2.put(p, m.get(p));
} else {
map1.put(p, 0);
map2.put(p, 0);
}
}
System.out.println(map1);
System.out.println(map2);
}
public static void main(String[] args) {
var map = new HashMap<String, Integer>();
map.put("Rohit", 45);
map.put("Rahul", 60);
map.put("Virat", 100);
map.put("Pant", 32);
printPlayers(map);
}
}

What will the output be?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • D

Question 14

+8 marksOne or more correct options

Consider the Java code given below.

java
interface Element {
void display();
}
class PeriodicTableElement {
private String group;
public void setGroup(String g) {
this.group = g;
}
public String getGroup() {
return group;
}
public Element createElement() {
switch (getGroup()) {
case "Metal":
return new Metal();
case "Nonmetal":
return new Nonmetal();
case "Metalloid":
return new Metalloid();
default:
return null;
}
}
private class Metal implements Element {
public void display() {
System.out.println("Metal properties");
}
}
private class Nonmetal implements Element {
public void display() {
System.out.println("Nonmetal properties");
}
}
private class Metalloid implements Element {
public void display() {
System.out.println("Metalloid behavior");
}
}
}
public class ChemistryLab {
public static void main(String[] args) {
PeriodicTableElement pt = new PeriodicTableElement();
pt.setGroup("Metalloid");
// --------- Line X ---------
}
}

Identify the appropriate option to fill in place of LINE X such that the output is:
Metalloid behavior

Select all that apply.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answers

  • A
  • C

Question 15

+8 marksOne or more correct options

Consider the Java code given below that prints the most impressive act among a set of given Performer objects. From among the options, identify the appropriate function header for the function printMostImpressiveAct that takes as input an array of Performer objects and prints the act with the highest score.

java
import java.util.*;
interface Performer {
int performAct();
}
class Magician implements Performer {
private int tricksPerformed;
public Magician(int tricks) {
this.tricksPerformed = tricks;
}
public int performAct() {
return tricksPerformed;
}
}
class Juggler implements Performer {
private int ballsJuggled;
public Juggler(int balls) {
this.ballsJuggled = balls;
}
public int performAct() {
return ballsJuggled;
}
}
public class TalentShow {
// LINE X: FUNCTION HEADER
{
// invokes method performAct()
// to print the value of the most impressive act
}
public static void main(String[] args) {
Performer[] performers = {new Magician(5), new Juggler(3), new Magician(8)};
printMostImpressiveAct(performers);
}
}

Choose the correct option(s).

Select all that apply.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answers

  • B
  • D