Which code fragment, inserted at the end of line 12, produces the output p is 420?

Given:

class Payload {
private int weight;

public Payload() {

}

public Payload(int w) {
weight = w;
}

public void setWeight(int w) {
weight = w;
}

public String toString() {
return Integer.toString(weight);
}
}

10. public class TestPayload {
11. static void changePayload(Payload p) {
12. /* insert code */
13. }
14.
15. public static void main(String[] args) {
16. Payload p = new Payload(200);
17. p.setWeight(1024);
18. changePayload(p);
19. System.out.println(“p is ” + p);
20. }
21. }

Which code fragment, inserted at the end of line 12, produces the output p is 420?

Given:

class Payload {
private int weight;

public Payload() {

}

public Payload(int w) {
weight = w;
}

public void setWeight(int w) {
weight = w;
}

public String toString() {
return Integer.toString(weight);
}
}

10. public class TestPayload {
11. static void changePayload(Payload p) {
12. /* insert code */
13. }
14.
15. public static void main(String[] args) {
16. Payload p = new Payload(200);
17. p.setWeight(1024);
18. changePayload(p);
19. System.out.println(“p is ” + p);
20. }
21. }

Which code fragment, inserted at the end of line 12, produces the output p is 420?

A.
p.setWeight(420);

B.
p.changePayload(420);

C.
p = new Payload(420);

D.
Payload.setWeight(420);

E.
p = Payload.setWeight(420);

Explanation:
A: p is 420

B:
Main.java:23: cannot find symbol
symbol : method changePayload(int)
location: class Payload
p.changePayload(420);
^
1 error

C: p is 1024

D:
Main.java:23: non-static method setWeight(int) cannot be referenced from a static context
Payload.setWeight(420);
^
1 error

E:
Main.java:23: non-static method setWeight(int) cannot be referenced from a static context
p = Payload.setWeight(420);
^
Main.java:23: incompatible types
found : void
required: Payload
p = Payload.setWeight(420);
^
2 errors



Leave a Reply 3

Your email address will not be published. Required fields are marked *


Alvaro

Alvaro

Correct answer is option A. Option B is false because method changePayload doesn’t belongs to class “Payload”, it belongs to class “TestPayload”. Option C is false because in Java parameters are passed by value not by reference, changing the internal reference to original object not will affect it after return. Option D is false because method setWeight can’t be called statically. Option E is false because same reason of option C and D.