Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 71
Question ID: UKOCP30884
Given code:
- package com.udayankhattry.ocp;
- import java.io.*;
- class Counter implements Serializable {
- private static int count = 0;
- public Counter() {
- count++;
- }
- public static int getCount() {
- return count;
- }
- }
- public class Test {
- public static void main(String[] args) throws IOException, ClassNotFoundException {
- var ctr = new Counter();
- try( var oos = new ObjectOutputStream(
- new FileOutputStream("C:\\Counter.dat")) ){
- oos.writeObject(ctr);
- }
- new Counter(); new Counter();
- try( var ois = new ObjectInputStream(
- new FileInputStream("C:\\Counter.dat")) ){
- ctr = (Counter)ois.readObject();
- System.out.println(Counter.getCount());
- }
- }
- }
There is full permission to list/create/delete files and directories in C:.
What is the result?
- A Runtime Exception
- B 1
- C 2
- D 3
Reveal correct answer
Correct answer: D
Explanation
UKOCP30884:
Counter class implements Serializable, hence objects of Counter class can be serialized using ObjectOutputStream.
State of transient and static fields are not persisted.
While de-serializing, transient fields are initialized to default values (null for reference type and respective Zeros for primitive types) and static fields refer to current value.
In this case, count is static, so it is not persisted. On de-serializing, current value of count is used.
new Counter(); simply increments the variable count by 1.
System.out.println(Counter.getCount()); => Prints 3 on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
