When you start a new project on the Java Virtual Machine (JVM), should you pick Java or Kotlin? What if you need a language that makes a whole class of bugs impossible, catches errors at compile time rather than at runtime, and protects against security issues? In short, what if you need a language that is safe?
In part 1 of this series, we compared the ecosystems of both languages; in part 2 we looked at the multiplatform capabilities; in part 3 we had a general introduction to Kotlin syntax and its interop with the Java platform. In this part we will get into how safe the languages are.
The example domain for this part will be Martin Fowler’s video store. This is a store where you could go to rent a thing called a “DVD,” which is a shiny disc that stores videos of all kinds. These discs had to be returned in a timely manner, lest we incur “rental fees.” The fee for the rental changed depending on the video we had rented. ‘Twas the time of “Blockbuster,” long ago, before we could stream all our content.
What Do We Mean by Safety?
By “safe,” we typically mean:
- memory safety: protection from memory-related bugs like buffer overflows or dangling pointers
- thread safety: protection from race conditions and data corruption when multiple threads access the same function concurrently
- null safety: protection against dereferencing null references
- injection safety: clear boundaries between code and user input
- type safety: operations are restricted to values of compatible types
These are, of course, not the only features to look at for safety. The OWASP project, for example, enumerates the ten critical web security risks, the top one being “broken access control,” but these risks are not addressed via language design.
What we’ve listed here is what a programming language can do to help us write safer code and we will go over them in the listed order. We will distinguish where the language or the JVM provides a guarantee, where we get checks and where it is just about ergonomics. If you are not familiar with Kotlin syntax, I recommend reading part 3 first before continuing.
Memory Safety
Memory safety is the same for Java and Kotlin, because the memory for both is managed by the JVM. We do not have to remember to release the memory we allocated, because the JVM releases it for us once the memory is no longer needed. Memory leaks can still happen, for example if our code inadvertently holds on to memory references, but generally the JVM manages it for us. In comparison, we have to remember quite a lot to achieve thread safety.
Thread Safety
In Java and Kotlin, memory is managed for us, but thread safety is something we have to manage ourselves. For example, we developers must remember to use ScopedValue (a modern alternative to ThreadLocal, since JDK 25 — September 2025) to share non-reassignable context data with a specific thread and its child threads. We must remember to use AtomicBoolean or ConcurrentHashMap to share data safely between threads. We must remember to use ReentrantLock, the synchronized keyword in Java, or the synchronized() function in Kotlin to guarantee mutual thread exclusion for specific code blocks. There is a lot to remember and little support.
Java and Kotlin do differ substantially in their approaches to concurrency and I/O throughput — most notably virtual threads and coroutines — but those features concern concurrency models and throughput rather than thread-safety guarantees, so we won’t compare them here.
Overall, the situation for thread safety is the same for Java and Kotlin: it is not guaranteed. The situation is better when it comes to null safety, because the compiler can actually help us.
Null Safety
In Java, currently, every object can have two states (initialised or null — we are ignoring JVM particularities like the larval state here). The type system does not signal this, and the compiler does not check it. Project Valhalla might eventually change that with “Null-Restricted and Nullable Types” but it is nebulous when that feature arrives. For now though, we have many NullPointers waiting to be thrown. For example, take the following repository code:
class JRentalRepository {
private Map<JRentalId, JRental> allRentals;
// ...
JRental getOne(JRentalId id){ // <2>
return allRentals.get(id); // <1>
}
}
// somewhere else
JMoney calculatePrice(JRental rental){
if(rental.rentedDays().rawValue() > 5){ // <3>
/* business code here */
}
// etc.
}
Maps return null when the key is not found, but neither in the access <1>, nor in the method signature <2>, is it clear that the reference might be null. This reference is then passed around until eventually a NullPointer is thrown <3> when it is accessed, far away from the place that caused it.
JSpecify annotations and the NullAway compiler plugin (which checks annotations) allow us to add compile-time null checks to Java (for a deeper exploration of those see Fixing the Billion-Dollar Mistake). This is very helpful, which is why Spring Boot 4 and Spring Framework 7 have adopted this setup. We can declare that the default is non-null and then only mark @Nullable what can become null. The compiler plugin will check that our assumptions are valid.
class JRentalRepository {
private Map<JRentalId, JRental> allRentals;
// ...
@Nullable JRental getOne(JRentalId id){ // <2>
return allRentals.get(id); // <1>
}
}
// somewhere else
JMoney calculatePrice(@Nullable JRental rental){ // <3>
if(rental.rentedDays().rawValue() > 5){
// ^
// <4> Error: Might be null
/* business code here */
}
// etc.
}
The compiler plugin knows that maps can return null <1>, sees the data flow and forces us to add @Nullable annotations <2> <3> wherever the value is passed. It will also stop compilation if a nullable object is accessed without a null check <4>.
Note that NullAway has documented cases of deliberate unsoundness for simplicity, speed and a reduced annotation burden. One of these is that zero-argument method calls (e.g. getters) are assumed pure and deterministic, that is they return the same value on every call. That might not be true for mutable objects that are modified by another thread. Thus, even with NullAway we can get a NullPointerException but the chances are significantly reduced.
Kotlin has also documented their cases when a NullPointerException can happen. One major reason is when we have a bug in the initialisation order, the other is interacting with Java code without nullability guarantees. Subjectively speaking, this list has fewer surprises than the NullAway list.
In Kotlin we get the null-checking behaviour out of the box, and it is syntactically more compact:
class KRentalRepository(
private val allRentals: Map<KRentalId, KRental>
){
fun getOne(id: KRentalId): KRental? { // <2>
// ^
// won't compile without explicit nullability marker
return allRentals.get(id) // <1>
}
}
// somewhere else
fun calculatePrice(rental: KRental?): KMoney { // <3>
if(rental.rentedDays.rawValue > 5){
// ^
// <4> Error: Might be null
/* business code here */
}
// etc.
}
In Kotlin non-null is the default and we have to add ? after the type to indicate it can be null <2> <3>. Kotlin also knows what functions in the standard library can return null (e.g. Map.get <1>). Like NullAway it will also force us to add explicit nullability markers and checks because it does not compile when a nullable value is accessed without a check <4>. This feature is also visualised by the Kotlin IDEs directly. Everything nullable becomes red if accessed without a check.
Note that these checks not only work with the Java standard library, but also with custom code that is annotated with JSpecify annotations. Since Kotlin 1.5.20 (June 2021) mismatches are warnings and since 2.1.0 (November 2024) they are reported as errors.
An important side effect of null checking is that non-nullable fields must be initialised in the constructor. That creates problems if the fields are not available at object construction. For example if they are set up in a method of a unit test. Another example is if they are created by dependency injection containers like Spring and need a @PostConstruct method or make heavy use of setter injection. In such cases, a field is essentially non-null but initialised late, it can be marked with the keyword lateinit var. The compiler allows such variables to be un-initialised on object construction, but accessing one without setting a non-null value triggers an immediate UninitializedPropertyAccessException. Most frameworks nowadays support constructor injection, so lateinit is not needed that often, but there are still cases where this is very useful and sorely missed in JSpecify.
Another language feature that Kotlin adds is null-aware operators:
- the
null-safe call operator?.(e.g.first?.second), which accesses the second element only when the first is not null - the Elvis operator
?:(e.g.first ?: fallback), which returns a fallback when the first element isnull
The whimsical operator naming makes sense when you picture rotating the ?: 90° to the right: the question mark becomes the king’s hair. These operators will be familiar to anyone who programs in TypeScript or C#. In these languages the second one looks different (?? not ?:) and is called nullish coalescing operator, but the behaviour is the same.
Together these operators allow us to rewrite calculatePrice in a null-safe way:
fun calculatePrice(rental: KRental?): KMoney {
val rentedDays: Int? = rental?.rentedDays?.rawValue // <1>
if(rentedDays != null && rentedDays > 5){ // <2>
// ^ ^^^^
// if true then this is also non-null
/* business code here */
}
// etc.
}
The null-safe call operator lets us access rawValue only if the two previous references are not null and rentedDays is either the raw value or null <1>. After that we check if rentedDays is not null and if so, the compiler can “smart cast” rentedDays to non-null in the if clause and inside the if body <2>.
By using the Elvis operator we can make this even shorter:
fun calculatePrice(rental: KRental?): KMoney {
val rentedDays: Int = rental?.rentedDays?.rawValue ?: 0 // <1>
if(rentedDays > 5){
/* business code here */
}
// etc.
}
rentedDays is now either the rawValue or 0 <1>.
We can write this even shorter by using the Kotlin extension function takeIf (only returns the value if it satisfies the condition) and ?.let (only called if the previous elements in the chain are non-null). It is debatable whether that is more readable than the previous example.
fun calculatePrice(rental: KRental?): KMoney {
rental?.rentedDays?.rawValue?.takeIf { days -> days > 5 }?.let {
/* only reached if everything before is non-null and days > 5 */
/* business code here */
}
// etc.
}
In Java we do not have these operators. Instead, we can chain null-checks in an if-statement, which might be the most readable way for short element chains:
JMoney calculatePrice(@Nullable JRental rental){
if (rental != null && rental.rentedDays() != null
&& rental.rentedDays().rawValue() > 5){
/* business code here */
}
// etc.
}
We could also use Optional to approximate the behaviour, but it is contested whether using Optional for that is idiomatic Java:
Optional.ofNullable(rental)
.map(JRental::rentedDays)
.map(JDay::rawValue)
.filter(days -> days > 5)
.ifPresent(days -> { /* business code here */ });
An alternative is to use record pattern matching (JDK 21 — September 2023) which would allow us to write the code below. The example also uses the “Unnamed Variables & Patterns” feature (JDK 22 — March 2024) to replace unused variables with an underscore _ for a bit of extra readability:
JMoney calculatePrice(@Nullable JRental rental){
if(rental instanceof JRental(_, JDay(int rawValue))
&& rawValue > 5){
/* business code here */
}
// etc.
}
This works and is arguably more idiomatic than using Optional. Whether it is better than chained null-checks depends on one’s familiarity with pattern matching, whether records can be used, and whether the business code is more readable with JRental taken apart.
So where does that leave us? null-safety can be provided by Java (via the combination of annotations and third-party compiler plugin that checks them) and is provided directly by Kotlin (out-of-the-box, enhanced by special operators).
The guarantees here are very different though. In Java the presence or lack of a null marker does not mean that this marker was checked at compile time. Annotations and compile-time plugin are separate tools after all. Kotlin code, on the other hand, does not compile if we violate the null-ness of the type. This also makes interop with Java code imperfect. For example a Java @Nullable String name cannot be assigned to a Kotlin val name: String but what if the Java type has no annotation? Kotlin treats such references as platform types for which the nullability is unknown. In IntelliJ this is shown as String! name. The compiler allows String! name to be assigned to a Kotlin val name: String but is that correct? That assumption is only safe if the entire Java codebase, no file can be exempt, is checked for nullness violations and an unannotated type is known to mean non-null.
Right now, null-awareness is a feature of the Kotlin compiler while on the Java side it is a combination of compiler plugin, annotations and hand-written null checks. The Kotlin compiler adds null-checks to the constructor and setters, in sync with the null markings, while in Java we have to write the Objects.requireNonNull() checks ourselves. This is because null checks are not enforced by the JVM at runtime. There are ways in which third-party code can ignore the null marker and construct invalid objects. For instance, serialisation libraries often still require a no-argument constructor to create an object, then set the private fields directly, bypassing any setters (for more on this see Destructoring is the future of Javas Encapsulation). This is a problem even for Kotlin code. Libraries like Jackson should check the annotation of fields and respect them during construction. For Jackson this was not always the case and even after support was added, it came with a stark performance penalty. This penalty was resolved with Jackson 2.19 (April 2025) but users still needed to enable the NewStrictNullChecks before null markings were respected. It is only on by default since Jackson 3.0 (October 2025).
In short, the library you use might not respect the markers. More and more libraries are adding support for the JSpecify null markers but it would be wise to write minimal tests before assuming it works. We will not have a guarantee until nullability is enforced by the JVM’s type system. This is something that could happen at some point with Null-Restricted and Nullable Types but that JDK enhancement is still a couple of years away. The same is true for the next feature we will discuss: safe variable embedding. It is not yet stable in the JDK, but it is key to a safe programming language and worth looking into.
Injection Safety and Safe Variable Embedding
Java 21 (September 2023) and Java 22 (March 2024) had a feature in preview that allowed us to safely embed variables in structured languages like SQL, HTML, JSON and circumvent injection attacks. These so-called string templates were never completed — the design was too limited in practical use — but the safety implications are too important not to discuss.
Let us say we want to construct a SQL query in Java, and we use string concatenation to do so:
String queryString = "SELECT * FROM Person p WHERE p.name = '" + name + "'";
// ^^^^^^^^
// UNSAFE! Do not concatenate Sql strings
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(queryString);
// ...
}
Concatenating name like that is a SQL injection waiting to happen. The value of name could be anything, and we would concatenate it verbatim to the queryString. If name is 123456' OR 1=1 --, then the resulting queryString would be "SELECT * FROM Person p WHERE p.name = '123456' OR 1=1 --'", which would be turned into a statement verbatim. This statement would then return every user in the database to the attacker.
If instead we first create the query and set the values afterwards, then a malicious name cannot modify the query itself. In Java the way to do so is a PreparedStatement:
String queryString = "SELECT * FROM Person p WHERE p.name = ?";
try (PreparedStatement query = connection.prepareStatement(queryString)){
query.setString(1, name);
ResultSet resultSet = query.executeQuery();
// ...
}
Now this solves the SQL injection problem but is a bit inconvenient to use because defining the query and embedding the values are two separate steps. The continued prevalence of SQL-injection vulnerabilities shows the limitations of relying on developer discipline alone. Injection ranks fifth in the OWASP Top 10 of 2025, with SQL injection alone accounting for more than 14,000 tracked CVEs (Common Vulnerabilities and Exposures) over all web applications. These CVEs include Java applications but are not limited to them. SQL injection attacks are a problem in multiple languages.
Injection attacks are not limited to SQL, however. Any code that interprets user-supplied data in a String is in danger of such an attack. This is why OpenJDK set out to make this safe and delivered a preview for string templates in JDK 21 and 22. They are quite ergonomic to use:
DB db = new DB(connection);
try (PreparedStatement query = db."SELECT * FROM Person p WHERE p.name = \{name}") { // <1>
ResultSet resultSet = query.executeQuery();
// ...
}
<1> The template "SELECT ...", which contains an embedded expression \{name}, is passed to the template processor DB together with the value of the expression (e.g. “Alex”). It can take the template, create a PreparedStatement, set all the values of the statement and return the result. All of this happens behind the scenes without developers having to worry about SQL injections. Similar processors could be written for JSON or XML to make their creation also safe.
String templates would make writing SQL/JSON/x both safe and ergonomic, a great combination to tackle injection attacks. But the design was deemed not good enough and is back on the drawing board with no new release in sight.
In Kotlin we do not have such string templates. To be more precise, we do not have the possibility of writing a custom template processor (e.g. db."") for string templates. In Kotlin a String can embed variables but the result is always a String. You could say that the template processor is always str."". Simply place a $ in a string and any variable, even a function call, can be interpolated into the string.
val queryString = "SELECT * FROM Person p WHERE p.name = '$name'"
// ^^^^^
// UNSAFE! Do not use String interpolation for Sql
val resultSet = statement.executeQuery(queryString)
// ...
While this is enormously convenient, it is not safe for anything where the end-result is not a String. If we take the resulting string and parse it into a SQL statement or a JSON document, we are in unsafe waters. Having custom string templates in Kotlin would be enormously welcome but is not on the horizon.
What both Java and Kotlin have, however, are type-safe builders that allow us to construct objects safely instead of relying on string parsing.
Type Safety — Through Builders
In the previous section we saw how dangerous it can be to construct a SQL query from a String. The safe alternative, especially for complex data, is to use a builder. For example the previous query can be expressed as follows with the Exposed SQL library:
val results: List<Person> = Persons
.selectAll()
.where { Persons.name eq name }
.toList()
This builder is interesting for two reasons. Not only does it prevent injection attacks, it also provides type-safe guidance for our query language. For example where {} is only available after we have called selectAll(). If where {} should be available on the single-element select() as well, then we can encode this as well. The syntax of our query language is enforced by the type system. This makes it even stronger than the previous string parsing, as that allows an arbitrary order. For example the following String can be written and will only fail at runtime: "WHERE p.name = '$name' FROM Person p SELECT *".
Such type-safety is also interesting for other use cases, for example to create (complex hierarchical) domain data structures and will be the focus of this section.
Let us say we wanted to create a TvSeries. In Java we could do so with the following code:
JTvSeries series = tvSeries(tvSeries -> {
tvSeries.setName("Game of Clones");
tvSeries.addSeason(season -> {
season.setTagLine("Here be Dragoons");
season.addEpisode(episode -> {
episode.setName("Take flight");
});
});
tvSeries.addSeason(season -> {
season.setTagLine("No more Dragoons");
season.addEpisode(episode -> {
episode.setName("Watch out for the fan");
});
});
});
In Kotlin creating the same data structure would look like the following:
val series = tvSeries {
name = "Game of Clones"
season {
tagLine = "Here be Dragoons"
episode {
name = "Take flight"
}
}
season {
tagLine = "No more Dragoons"
episode {
name = "Watch out for the fan"
}
}
}
Both languages make creating these data structures safe because the developer-defined hierarchy cannot be ignored. For example, we cannot create an episode {} inside a tvSeries {}, because the function is only available inside a season {}. An unintentional scoping problem exists in Java where children can call parent builders directly. For example tvSeries.setName can be called from inside the addSeason() lambda. We can prevent unintentional misuse of this in Kotlin with the @DslMarker annotation as explained further down.
Where both code examples differ is in the readability and that comes down to a couple of design choices that Kotlin made (see part 3 for an exploration of these features):
- properties that allow setting the name via equals
- operator overloading
- how lambdas are invoked
- and that these lambdas can have so-called receivers
In Kotlin using these features to create data structures is called type-safe builders, they are inspired by Groovy, and they are used in many Kotlin projects. If you have ever:
- declared
dependencies { }in abuild.gradle.ktsfile - configured a
router { GET("/users", findAllUsers) }in a Spring Boot Kotlin project
then you have used a type-safe builder. They can also be used for SQL, html {} and even domain logic, as the previous code examples show.
These builders are quite easy to, ahem, build. First, we create tvSeries, a function that takes a function as an argument:
fun tvSeries(
init: (builder: KTvSeriesBuilder) -> Unit // <1>
// ^ parameters of function ^^^
// function returns nothing
): KTvSeries {
val builder = KTvSeriesBuilder() // <2>
init(builder) // <3>
return builder.build() // <4>
}
The tvSeries function has the init function as an argument, which in turn takes a builder as an argument and returns nothing (Unit in Kotlin, void in Java) <1>. Inside the function we then create a KTvSeriesBuilder <2>, let the init function set whatever builder values the user wants <3>, before we finally build the object <4>.
In Java we would call the tvSeries like this:
KTvSeries series = tvSeries(series -> {
series.setName("Game of Drones");
});
But in Kotlin lambdas get a special syntax when they are the last parameter of a function. They can be written outside the parentheses (). If we have no other parameters, then the parameter parentheses () can also be omitted and we get the following:
val series: KTvSeries = tvSeries { series ->
series.name = "Game of Drones" // <1>
}
The function we passed to tvSeries {} can set whatever series values we want <1>. This is already a bit more readable than the Java lambda, but we can make it even better. In Kotlin we can declare a so-called function receiver:
fun tvSeries(init: KTvSeriesBuilder.() -> Unit
// ^^^^^^^^^^^
// added KTvSeriesBuilder as the receiver of the function
): KTvSeries {
// same as before
}
We went
- from
tvSeries(init: (builder: KTvSeriesBuilder) -> Unit) {} - to
tvSeries(init: KTvSeriesBuilder.() -> Unit) {}
In both cases the init function requires a KTvSeriesBuilder. In the first one it is an argument, accessed via name (series.name = "abc"), and in the second it becomes an explicit or implicit this(this.name = "abc" or just name = "abc").
If KTvSeriesBuilder now in turn has a fun season(init: KTvSeasonBuilder.() -> Unit) and KTvSeasonBuilder has a fun episode(init: KTvEpisodeBuilder.() -> Unit), we get the example from the beginning: a readable type-safe way to construct hierarchical configuration, generic data (HTML, XML, JSON) or domain data.
fun createCatalog(){
// ...
tvSeries {
// ^
// no parameter needed
name = "Game of Drones"
// ^
// KTvSeriesBuilder is the implicit this
// We can access whatever the KTvSeriesBuilder has
// Previously we still had to write series.name
season {
tagLine = "Here be Dragoons"
episode { }
}
}
// ...
}
We need one more feature to complete the example, because nesting season {} inside tvSeries {} introduced a problem: inside a lambda you can call methods of every available implicit receiver. For example, inside season {} we can set the name of the outer tvSeries {}. In Kotlin we can limit the scope of our receiver by adding @DslMarker to the class, parent class or receiver. In the code example we add it to the parent of all builders.
@DslMarker
@Target(AnnotationTarget.CLASS)
annotation class TvDslMarker
@TvDslMarker
interface KTvBuilder
class KTvSeasonBuilder : KTvBuilder { /** **/ }
class KTvSeriesBuilder : KTvBuilder { /** **/ }
class KTvEpisodeBuilder : KTvBuilder { /** **/ }
Once we have added the annotation, the compiler will report an error if we implicitly access something from the parent scope. This prevents us from violating the builder hierarchy.
The builder concept itself is present in Java, the readable and ergonomic way in which we can represent it is inherent to Kotlin. Which is a good summary of what Kotlin can give us: familiar concepts but expressed safer and more concise.
This section was focused on builders, an often-overlooked way to achieve type-safety. Other forms of type safety, sealed types for instance, will be shown in part 5, because their benefit is easier to show when modelling the domain.
Language for Safety Summary
One of the strongest ways a language can improve the safety of our programs is by making invalid states unrepresentable. In this part of the Kotlin kontra Java series, we looked at five areas where our two languages can support us.
| Area | Java | Kotlin |
|---|---|---|
| Memory safety | JVM-managed | JVM-managed |
| Thread safety | Developer responsibility | Developer responsibility |
| Null safety | Compiler plugin can check JSpecify annotations but no operator ergonomics. Only guarantee at runtime if developer adds all null-checks and keeps them in sync. No guarantee for third-party Java code. No-argument constructor can destroy guarantee. Documented deliberate unsoundness. | Enforced compiler checks in Kotlin code and operator ergonomics (?., ?:). Guarantee at runtime, because null-checks are added and kept in sync by compiler. Guarantee for third-party Kotlin code. No-argument constructor can destroy guarantee. Documented unsoundness mostly when interacting with Java code. |
| Injection safety and safe variable embedding | Developer responsibility. Brief string template previews but never finished. | Developer responsibility. No further plans right now. |
| Type safety through builders | Possible, more verbose, can call outer builders | Compiler support and language features make them particularly expressive |
In short, Kotlin benefits from the same JVM-level safety guarantees as Java, while also enforcing null-safety checks for all Kotlin code. This puts Kotlin ahead in the safety area when working with other Kotlin code or null-annotated and checked Java code. Additionally, its compiler support and language design bring ergonomic type-safe builders. In the fifth and final part we will see how the design choices of both languages come together when we explore the business modelling capabilities of Java and Kotlin.