0% found this document useful (0 votes)
12 views16 pages

BSCCS2005 Week 8 Assignment Solutions

The document contains a series of multiple-choice questions and solutions related to Java programming concepts, including object cloning, type inference, streams, and collections. Each question presents code snippets and asks for the expected output or behavior, followed by explanations of the correct answers. The document serves as a graded assignment for a programming course, focusing on practical understanding of Java syntax and functionality.

Uploaded by

Rishesh Shukla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views16 pages

BSCCS2005 Week 8 Assignment Solutions

The document contains a series of multiple-choice questions and solutions related to Java programming concepts, including object cloning, type inference, streams, and collections. Each question presents code snippets and asks for the expected output or behavior, followed by explanations of the correct answers. The document serves as a graded assignment for a programming course, focusing on practical understanding of Java syntax and functionality.

Uploaded by

Rishesh Shukla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BSCCS2005: Graded Assignment with Solutions

Week 8
1. Consider the code given below. [MCQ:2 points]

public class Point{


private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
public Object clone() throws CloneNotSupportedException{
return [Link]();
}
}

public class FClass{


public static void main(String[] args) {
try {
Point p1 = new Point(10, 20);
Point p2 = p1;
Point p3 = (Point)[Link]();
[Link](100);
[Link](200);
[Link](p1 + " , " + p2 + ", " + p3);
}
catch(CloneNotSupportedException e) {
[Link]("clone() not supported");
}
}
}

What will the output be?


(100, 200), (100, 200), (100, 200)
(100, 200), (100, 200), (10, 20)
(100, 200), (10, 20), (10, 20)

clone() not supported

Page 2
Solution: Since class Point does not implement Cloneable, an attempt to call
clone() would generate CloneNotSupportedException exception. Thus, it prints
clone() not supported.

Page 3
2. Consider the code given below. [MCQ:2 points]

public class Product implements Cloneable{


private String prodname;
private double prodprice;
public Product(String prodname, double prodprice) {
[Link] = prodname;
[Link] = prodprice;
}
public Product(Product p) {
[Link] = [Link];
[Link] = [Link];
}
public void setProdname(String prodname) {
[Link] = prodname;
}
public void setProdprice(double prodprice) {
[Link] = prodprice;
}
public String toString() {
return prodname + " : " + prodprice;
}
protected Product clone() throws CloneNotSupportedException{
return (Product)[Link]();
}
}

public class FClass{


public static void main(String[] args) {
try {
Product p1 = new Product("Pen", 100.0);
Product p2 = new Product(p1);
Product p3 = p1;
Product p4 = [Link]();
[Link]("Pencil");
[Link](30.0);
[Link](p1 + ", " + p2 + ", " + p3 + ", " + p4);
}
catch(CloneNotSupportedException e) {
[Link]("clone() not supported");
}
}
}

Page 4
What will the output be?
Pencil : 30.0, Pencil : 30.0, Pencil : 30.0, Pencil : 30.0
Pencil : 30.0, Pen : 100.0, Pencil : 30.0, Pencil : 30.0

Pencil : 30.0, Pen : 100.0, Pencil : 30.0, Pen : 100.0
clone() not supported

Solution: Since p2 allocates a new and copies the instance variables from p1 (using
copy constructor), the changes in p1 is not reflected on p2.
Since, p1 and p3 refers to the same object, any change to p1 would be reflected on
p3.
However, p4 creates a separate copy of the p1 object. Thus, the changes in p1 are
not reflected on p4.

Page 5
3. Consider the code given below. [MCQ:2 points]

public class FClass{


public static void main(String[] args) {
var a = 10;
var b = "20";
var c = a + b + 30;
var d = a + 30 + b;
[Link](c + ", " + d);
}
}

What will the output be?


60, 60
3030, 4020

102030, 4020
102030, 103020

Solution: a has inferred type int.


b has inferred type String.
Thus, a + b + 30 = "1020" + 30 = "102030",
and a + 30 + c = 40 + "20" = "4020".

Page 6
4. Consider the code given below. [MCQ:2 points]

public class Employee{


public Employee(){}
public String toString(){
return "from Employee";
}
}
public class Manager extends Employee{
public Manager(){}
public String toString(){
return "from Manager";
}
}
public class FClass{
public static void main(String[] args) {
Employee e = new Manager();
var o1 = e;
var o2 = new Employee();
var o3 = new Manager();
[Link](o1);
[Link](o2);
[Link](o3);
}
}

What will the output be?


from Employee
from Employee
from Manager

from Manager
from Employee
from Manager
from Manager
from Manager
from Manager
from Employee
from Employee
from Employee

Page 7
Solution: o1 has inferred type Manager.
o2 has inferred type Employee.
o3 has inferred type Manager.

Page 8
5. Consider the code given below. [MCQ:2 points]

public class FClass{


public static void main(String[] args) {
var a = 100;
a = 10.5; //LINE 1
var b = 5;
var c = a / b;
[Link](c);
}
}

Choose the correct option regarding the code.


It generates output: 2.1
It generates output: 2
It generates output: 20

It generates a compiler error at LINE 1 due to incompatible types int and
double.

Solution: For the statement var a = 100;, the type of a is inferred from the initial
value. So, a is a int. Thus, the compiler does not allow a = 10.5;.

Page 9
6. The merge method of Map has three arguments - key, value and reference to a function
accepting two arguments - and merges the old value with the new value for a given key.
Consider the code given below. [MCQ:2 points]

import [Link].*;
public class FClass{
public static void main(String[] args){
Map<String, Integer> order1 = new TreeMap<String, Integer>();
[Link]("Pen", 3);
[Link]("Pencil", 10);
[Link]("Notebook", 4);
[Link]("Paper", 50);
Map<String, Integer> order2 = new TreeMap<String, Integer>();
[Link]("Pencil", 20);
[Link]("Eraser", 5);
[Link]("Paper", 10);
[Link]("Pen", 7);
Map<String, Integer> totalSell = new TreeMap<String, Integer>();

for([Link]<String, Integer> e : [Link]())


[Link]([Link](), [Link]());

for([Link]<String, Integer> e : [Link]())


[Link]([Link](), [Link](), (x, y) -> y + x);

[Link](totalSell);
}
}

Choose the correct option regarding the code.



It generates output: {Eraser=5, Notebook=4, Paper=60, Pen=10, Pencil=30}
It generates output: {Eraser=5, Notebook=4, Paper=10, Pen=7, Pencil=20}
It generates output: {Eraser=5, Notebook=4, Paper=50, Pen=3, Pencil=10}
It generates runtime exception: NullPointerException

Solution: For each entry in order2, The statement [Link](...), finds


out if the key is already present in the [Link] the key does exists in totalSell,
it would be added to totalSell alng with corresponding value. Otherwise, it gets the
old value corresponding to the key, add it with the new value, and update totalSell.

Page 10
7. Consider the code given below. [MSQ:2 points]

import [Link].*;
import [Link].*;
public class Product{
private String name;
private double price;
public Product(String n, double p){
name = n;
price = p;
}
public double getPrice(){
return price;
}
public String toString(){
return name + " : " + price;
}
}
public class FClass{
public static void main(String[] args){
var pList = new ArrayList<Product>();
[Link](new Product("Pen", 10.0));
[Link](new Product("Pencil", 5.0));
[Link](new Product("Notebook", 40.0));
[Link](new Product("Eraser", 8.0));

var outputList = ____________________; //LINE 1


[Link](n -> [Link](n));
}
}

Identiy the appropriate option(s) to fill in the blank at LINE 1 such that the output of
the program is:

Pen : 10.0
Notebook : 40.0

[Link]().filter(x -> [Link]() >= 10)
[Link]().filter(x -> x >= 10)

[Link]().filter((Product x) -> [Link]() >= 10)
[Link]().takeWhile(x -> [Link]() >= 10)

Page 11
Solution: The given program extracts the Product objects from the pList that
have price >= 10. In order to access price, the accessor function getPrice is
required to be invoked in filter.

Page 12
8. Consider the code given below. [MCQ:2 points]

import [Link].*;
import [Link].*;

public class FClass{


public static void main(String[] args){
int m = 15;
[Link](1, n -> n + 1)
.limit(m)
.filter(n -> m % n == 0)
.forEach(n -> [Link](n + " "));
}
}

Identify the appropriate option for the above code.


It produces no output.

It produces output as 1 3 5 15
It produces output as 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
It generates compiler error due to invalid pipeline

Solution: iterate(1, n -> n + 1) generate a stream 123 · · · .


limit(m) limit the stream at m = 15.
filter(n -> m % n == 0) filters the values which divides m, i.e. 13515. forEach(n
-> [Link](n + " ") prints each element.

Page 13
9. Consider the Java code given below, and answer the question that follows.
[MCQ:2pts]

import [Link];
import [Link].*;

public class StreamEx{


int j=0;
public static void main(String []args){
ArrayList<Integer> list = new ArrayList<Integer>();

for(int i = 1; i< 10; i++){


[Link](i);
}
//CODE BLOCK 1
}
}

From among the options, what should be filled in CODE BLOCK 1 so that the code prints
the even numbers between 1 and 9?

Stream<Integer> stream = [Link]().filter(j -> j%2 == 0);
[Link](s -> [Link](s));
Stream<Integer> stream = [Link]().filter(j -> j%2 = 0);
[Link](s -> [Link](s));

Stream<Integer> stream = [Link]();
stream = [Link](j -> j%2 == 0);
[Link](s -> [Link](s));
Stream<Integer> stream = [Link]();
List<Integer> newList = (List)[Link](j -> j%2 == 0);
[Link](s -> [Link](s));

Solution: Option 1 is correct.


In Option 2, the filtering condition must return a boolean value, here it is an assign-
ment.
Option 3 is only a split form of Option 1, and hence is correct. In Option 4, the out-
put of filter cannot be directly assigned to a List object (typecasting is not possible
from Stream to List).

Page 14
10. What is the likely outcome of the following code? [MCQ:2pts]

import [Link];
public class StreamRandom {
public static void main(String[] args) {
Stream random = [Link](Math::random)
.map(i -> [Link](i * 100))
.filter(j -> j > 50).limit(5);
[Link](s -> [Link](s));
}
}

92
71
98
96
52
78
39
49
29
54
53
94
86
75
82
74
0.14161383465857424
0.9951624577496674
0.1500299618014398
0.8523339358885837
0.20299930897974205
6200
7400
9100
5100
5800

Solution: Math::round generates random numbers between 0.0 and 1.0.


[Link](i * 100) multiplies it by 100 and rounds it to an integer. filter(j

Page 15
-> j > 50) filters in only those numbers that are greater than 50. limit(5) limits
the number of numbers generated to 5. Option 1 is the only option that satisfies all
the conditions.

Page 16

Common questions

Powered by AI

Achieving the desired output requires correctly configuring the stream pipeline stages. Initialize the stream with the desired sequence, use filter to apply logical conditions, and limit to constrain the count of output elements. In the provided example, filter ensures that only divisors of 15 are selected, and limit guarantees that stream processing stops after processing 15 elements in the sequence. This coordination of methods results in displaying specific numbers .

Math::random generates pseudo-random double values between 0.0 and 1.0. When used in a stream pipeline with map(i -> Math.round(i * 100)), it produces rounded integer values between 0 and 100. The filter(j -> j > 50) ensures only values greater than 50 pass through, and limit(5) restricts the output to five numbers, explaining why the output is a set of five integers all greater than 50 .

Directly casting a Stream to a List is incorrect because Streams and Lists are fundamentally different structures. Streams represent sequences of elements supporting sequential and parallel aggregate operations, while Lists are collections. The filter method retains a Stream output, hence requiring terminal operations like collect(Collectors.toList()) to convert to a List, making direct casting invalid .

The merge method in the Map interface updates the value for each key by applying a function to the old and new values, if the key is already present. In the given example, when an entry from order2 is merged into totalSell, if the key exists, the provided function adds the values. Hence, for overlapping keys like 'Pencil' and 'Pen', the values are aggregated, resulting in the final map having the combined totals .

In Java, when using type inference (var), the type is inferred at compile time. In the operation a + b + 30 where a is an integer and b is a string, Java automatically converts the integer to a string before concatenation. Thus, a + b becomes a string "1020", and adding 30 results in "102030" because it continues as string concatenation. Conversely, in a + 30 + b, 30 is added to a first, resulting in 40, then concatenated to b, resulting in "4020" .

The Product class implements the Cloneable interface, and the clone method is defined to return a copy of the Product object. It uses super.clone() to create a shallow copy, ensuring the fields prodname and prodprice are copied into the new instance .

The compiler error is caused by assigning a double value to a variable whose type was inferred as int. In Java, the type of a variable declared with var is inferred from its initializer, and once inferred, the type cannot change. Since a starts with an integer value, the compiler infers it as an int, and attempting to assign a double value results in an incompatible types error .

The code throws a CloneNotSupportedException because the class Point does not implement the Cloneable interface. In Java, if a class does not implement Cloneable, calling the clone() method on its object results in a CloneNotSupportedException .

Filtering in Java Streams is achieved using the filter method which takes a Predicate. In the example, the stream filters products with prices greater than or equal to 10 by invoking getPrice() in a lambda expression passed to the filter method. This approach ensures that only products meeting that condition are included in the outputList .

The output includes 1, 3, 5, and 15 because the stream is created using Stream.iterate, which generates numbers starting from 1 up to 15 (due to .limit(15)). The filter condition m % n == 0 keeps only the divisors of 15, resulting in those specific numbers being printed .

You might also like