Question 20
Back to Exercise
What is the output of the following Java program?
class Stock {
private int available;
private int reserved;
Stock(int available) { this.available = available; }
boolean reserve(int qty) {
if (qty <= 0 || qty > available) return false;
available -= qty;
reserved += qty;
return true;
}
void release(int qty) {
int r = Math.min(qty, reserved);
reserved -= r;
available += r;
}
String show() { return available + "/" + reserved; }
}
public class Main {
public static void main(String[] args) {
Stock s = new Stock(10);
System.out.print(s.reserve(4) + " " + s.reserve(7) + " " + s.reserve(6) + " ");
s.release(15);
System.out.println(s.show());
}
}
- A true false true 10/0 Correct
- B true true false 0/10
- C true false true 5/5
- D true false true 25/0
Correct Answer: Option A
7 is more than the 6 left, so it is refused. release never returns more than was reserved, so available + reserved always stays 10.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!