Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A class has private int retries = 3; and no no-arg constructor. After new Gson().fromJson("{}", Settings.class), retries is 0, not 3. Explain why and how to fix it.

Because Settings has no no-arg constructor, Gson cannot call any constructor, so it allocates the object through sun.misc.Unsafe, which creates the instance without running constructors or field initializers. The field therefore keeps the JVM default 0, and since the JSON is empty nothing overwrites it. We fix it by adding a no-arg constructor, which may be private, so the initializer runs, or by registering an InstanceCreator that builds a properly initialised Settings.

Why this question is asked

This bug is subtle because nothing fails. No exception, no warning, just a value of 0 where the code clearly says 3, and in a retry setting that can mean a job that never retries. It appears whenever a class gets a constructor with parameters and loses its implicit default constructor, often in a refactoring that seemed harmless. Interviewers ask it to see whether we know how Gson creates objects, which is something most people never think about. In this answer, we will reproduce the problem, look at how Java normally runs field initializers, see the three ways Gson can create an instance, apply both fixes, and look at records and at why relying on Unsafe is fragile.

1Reproducing the Problem

Here is the class. It looks perfectly reasonable.

Java
public class Settings {
private int retries = 3;
private String name;
public Settings(String name) { this.name = name; } // the only constructor
}
Settings s = new Gson().fromJson("{}", Settings.class);
System.out.println(s.retries); // 0, not 3
System.out.println(s.name); // null
Settings t = new Settings("job");
System.out.println(t.retries); // 3: a normal constructor call runs the initializer

2A Quick Recap of Field Initializers

In Java, a field initializer such as retries = 3 is not stored as a property of the field. The compiler copies it into the beginning of every constructor of the class, right after the call to the superclass constructor. So the value 3 is only ever assigned by running a constructor. Memory for a new object is first zero-filled by the JVM, which is why every field starts as 0, false or null, and then the constructor body, including the copied initializers, sets the real values.

That is the key to the bug. If something creates the object without running any constructor, the initializer never runs, and the field stays at the zero-filled value.

3How Gson Creates the Instance

When Gson needs a new Settings, it tries several strategies in order. If we registered an InstanceCreator for the type, it uses that. Otherwise, if the class has a no-arg constructor, of any visibility, it calls it by reflection. Otherwise, for an ordinary class, it falls back to Unsafe.allocateInstance, a JDK-internal method that allocates a zero-filled object without calling a constructor at all.

Settings only has Settings(String), so Gson takes the third path. The object comes out with retries = 0 and name = null, and because the JSON {} contains no properties, Gson sets nothing. The 0 is exactly what we observed.

Step throughHow Gson gets a new instance
  1. InstanceCreator registered for the type?
    YesUse itNoNext check
  2. Class has a no-arg constructor?
    YesCall it: initializers run, retries = 3NoNext check
  3. Unsafe allowed?
    YesUnsafe.allocateInstance: no constructor, retries = 0NoThrow an error naming the class
  4. Set fields present in the JSONmissing ones keep the value from creation

4 steps in order. Play them, or step through them one at a time.

4Fix 1: Add a No-Arg Constructor

The simplest fix is to give Gson a constructor it can call. It can be private, because Gson uses reflection and is allowed to call it, so the public API of the class stays the same.

Java
public class Settings {
private int retries = 3;
private String name;
private Settings() { } // for Gson; initializers run here
public Settings(String name) { this.name = name; }
}
Settings s = new Gson().fromJson("{}", Settings.class);
System.out.println(s.retries); // 3
Settings u = new Gson().fromJson("{\"retries\":5}", Settings.class);
System.out.println(u.retries); // 5: the JSON value overwrites the default

Notice the order in the second call: the constructor runs first and sets 3, then Gson overwrites the field with 5 from the JSON. That is exactly the behaviour we want for defaults.

5Fix 2: Register an InstanceCreator

When we cannot change the class, for example because it belongs to another library, we tell Gson how to create it.

Java
Gson gson = new GsonBuilder()
.registerTypeAdapter(Settings.class, (InstanceCreator<Settings>) type -> new Settings("default"))
.create();
Settings s = gson.fromJson("{}", Settings.class);
System.out.println(s.retries); // 3: a real constructor ran
System.out.println(s.name); // default

The creator is called for every new instance, and Gson then fills in the fields from the JSON as usual. It is also a convenient place to apply defaults that depend on configuration.

6Records and Newer Gson Versions

Records are a different case. A record has no no-arg constructor and its fields are final, so neither strategy above fits. Since Gson 2.10, Gson supports records by reading the JSON first and then calling the canonical constructor with the values; check your version. A component missing from the JSON is passed as its default, 0 or null, so defaults belong in the record's compact constructor if we need them.

Java
record Settings(int retries, String name) {
Settings { if (retries == 0) retries = 3; } // compact constructor applies the default
}
System.out.println(new Gson().fromJson("{}", Settings.class).retries()); // 3

7Follow-up questions

Why can Unsafe allocation be a problem with the module system or in native images?

sun.misc.Unsafe lives in the jdk.unsupported module and is not a supported API; the JDK has been deprecating and restricting parts of it, so behaviour may change in future releases, so check your version. In GraalVM native images, classes created reflectively or through Unsafe must be registered at build time, otherwise allocation fails at run time even though it worked on the JVM. Gson offers GsonBuilder.disableJdkUnsafe() so that it fails fast with a clear message instead, which forces every class to have a constructor or an InstanceCreator.

Would making retries final help?

No. A final field with an initializer is still assigned only inside the constructor, so Unsafe allocation leaves it at 0 as well. It also becomes more confusing: a final int with a constant initializer can be inlined by the compiler where the field is read by its simple name, so some code may see 3 while the stored field is 0. Mutable DTOs with a no-arg constructor, or records, are the cleaner options.

How would we catch this in tests?

A test that deserializes {} and asserts the defaults catches it immediately. Running all DTO tests with a Gson built with disableJdkUnsafe() catches every class that relies on Unsafe allocation, before it reaches production.

8Conclusion

In this answer, we saw that field initializers run only as part of a constructor, and that Gson, finding no InstanceCreator and no no-arg constructor, creates Settings through Unsafe allocation without running any constructor. The field keeps the zero-filled value 0, and an empty JSON never replaces it. A no-arg constructor, which can be private, or a registered InstanceCreator restores the default, and records from Gson 2.10 go through their canonical constructor instead.

What to say in the interviewAbout 80 seconds aloud

Open with

The class only has a constructor with a parameter, so Gson has no constructor it can call. It checks for an InstanceCreator, then for a no-arg constructor, and when both are missing it falls back to Unsafe.allocateInstance, which creates a zero-filled object without running any constructor.

Then, if they want more

In Java, a field initializer like retries = 3 is compiled into the constructors, so if no constructor runs, the field stays at 0. The JSON is empty, so Gson sets nothing and we see 0. The simplest fix is to add a no-arg constructor; it can be private, since Gson uses reflection, so the public API does not change.

Gson then calls it, the initializer sets 3, and any value in the JSON overwrites it. If I cannot change the class, I register an InstanceCreator that builds a properly initialised object. For records, Gson 2.10 and later call the canonical constructor, so defaults go in the compact constructor.

I would also mention that relying on Unsafe is fragile, both because it is a JDK-internal API and because native images need build-time registration, so I like to build test Gson instances with disableJdkUnsafe to catch classes that depend on it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A class has private int retries = 3; and no no-arg constructor. After new...": https://scrivio-interview-library.netlify.app/java/json-libraries/1453ec96e7/