Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 12 / Stage 2

Java interop and the JVM ecosystem

Goal: Call a Java class from Kotlin and a Kotlin class from Java, understand what a platform type is and why an unannotated Java method is quietly dangerous, use @JvmStatic/@JvmOverloads/@JvmName to make Kotlin pleasant to call from Java, use a plain JDK API with no wrapper at all, and look at the actual bytecode kotlinc generates with javap. Time: ~5 hours · Level: comfortable with Part 9's classes and Part 11's project layout

⚠️ Toolchain note. JDK 21 (Amazon Corretto 21.0.11) and kotlinc 2.4.21 are both installed and verified on this machine (see ../../TOOLING.md); javac and javap ship with that same JDK. Everything in this part — every compile, every run, every javap transcript — was actually executed here; nothing is a guess at what the compiler "should" produce.

What you will learn

  • Calling a Java class from Kotlin: getters/setters as properties, is-prefixed booleans, static methods — and the one real gotcha this part ran into while verifying it
  • Platform types (String!): what Kotlin does when a Java declaration has no nullability annotation, and the crash that's waiting for you if you ignore it
  • Nullability annotations (@Nullable/@NotNull) at the Java/Kotlin boundary, and how they change a platform type into a real, checked one
  • @JvmStatic, @JvmOverloads, and @JvmName — what each one changes in the actual compiled bytecode, proven with javap, not just described
  • Calling a Kotlin class from Java, including a data class's generated members
  • Using a plain JDK API directly from Kotlin, no wrapper needed
  • How Kotlin compiles to bytecode: a peek at a data class, a default-parameter function, and an object with javap

Topics in this part

Practice

Every exercise mixes at least one .java file and one .kt file. Compile in dependency order — whichever file depends on nothing compiles first — exactly like the README's section 1:

$ javac -d out SomeJavaClass.java
$ kotlinc -cp out SomeKotlinFile.kt -d out
$ javac -cp "out:kotlin-stdlib.jar" -d out SomeJavaCaller.java    # only if Java calls Kotlin back
$ java -cp "out:kotlin-stdlib.jar" package.MainClass

Find kotlin-stdlib.jar inside your kotlinc install (on this course's machine: /opt/homebrew/Cellar/kotlin/2.4.21/libexec/lib/kotlin-stdlib.jar) — it's needed on the runtime classpath whenever you run compiled Kotlin .class files directly with java.


Exercise 1: A Java tax table, called from Kotlin

Scenario: A Java utility class holds GST rates by category; a Kotlin function applies GST using it. What to do: Write TaxTable.java with public static double gstPercentFor(String category) ("essentials" → 5.0, "standard" → 12.0, "luxury" → 28.0, else throw IllegalArgumentException). Write priceWithGst(amount: Double, category: String): Double in Kotlin that calls it. Compile Java first, then Kotlin, then run a small Kotlin main() printing two prices.

Sample output:

1120.0
1280.0

💡 Hint: amount + amount * TaxTable.gstPercentFor(category) / 100.


Exercise 2: An is-prefixed boolean property

Scenario: An invoice's "paid" flag is exposed from Java the conventional way — isPaid()/setPaid(boolean) — and you want to read and write it as a Kotlin property. What to do: Write Invoice.java with getNumber(), isPaid(), setPaid(boolean). From Kotlin, print the invoice number and paid status, set it paid using property syntax (no parentheses, no set prefix), then print again.

Sample output:

INV-204: paid = false
INV-204: paid = true

💡 Hint: the property keeps the full name isPaid — invoice.isPaid = true, not invoice.paid = true.


Exercise 3: @JvmStatic, both call styles, proven with javap

Scenario: You want to see, not just read about, the difference @JvmStatic makes. What to do: Write a Kotlin object Greeter with @JvmStatic fun staticHello(name: String): String and a second function fun instanceHello(name: String): String with no @JvmStatic. From Java, call Greeter.staticHello(...) directly and Greeter.INSTANCE.instanceHello(...). Run javap -p on the compiled Greeter.class and confirm which method is static and which isn't.

Sample output:

Hello (static), Asha
Hello (instance), Ravi

💡 Hint: if Greeter.staticHello(...) doesn't compile from Java, the @JvmStatic is missing or misplaced — it must sit directly above the function inside the object.


Exercise 4: @JvmOverloads with two defaults

Scenario: A Discount.apply(...) function has two default parameters, and Java callers need to be able to omit either, both, or neither. What to do: Write a Kotlin class Discount with @JvmOverloads fun apply(amount: Double, percent: Double = 10.0, roundToRupee: Boolean = false): Double. From Java, call it three ways: with just amount, with amount and percent, and with all three arguments. Run javap -p and count how many real apply(...) overloads exist.

Sample output:

900.0
800.0
800.0

💡 Hint: three real overloads should appear in javap's output, plus the apply$default(...) synthetic bridge Kotlin uses internally.


Exercise 5: Cause a platform declaration clash, then fix it

Scenario: Two overloads that look perfectly fine in Kotlin source can still collide once generics are erased to raw JVM types. What to do: Write fun total(values: List<Int>): Int and fun total(values: List<String>): Int in the same file, with no @JvmName yet. Compile it and paste the real platform declaration clash error. Then add @JvmName("totalOfLengths") to the second function, recompile, and run both from a main().

Sample output (after the fix):

60
7

💡 Hint: the error message itself tells you the shared signature: total(Ljava/util/List;)I — both functions erase to exactly that, regardless of what's actually inside the List at the type level.


Exercise 6: Crash on a platform type, then fix it for real

Scenario: A Java lookup method has no nullability annotation, and an unknown key returns null — exactly section 3's danger, caused and fixed by hand. What to do: Write Lookup.java with public String cityFor(String pincode) returning null for an unknown pincode, no annotation. Write a Kotlin main() that looks up an unknown pincode and immediately calls .uppercase() on the result with no null check. Run it and paste the real crash. Then write a second main() that treats the result as String? and provides a fallback with ?:, and paste its real, non-crashing output.

Sample output (broken):

Exception in thread "main" java.lang.NullPointerException
	at ...PrintCityBrokenKt.main(PrintCityBroken.kt:6)

Sample output (fixed):

City: UNKNOWN PINCODE

💡 Hint: val city: String? = lookup.cityFor(pincode) — writing the String? yourself is the whole fix; the Java side doesn't need to change at all.


Exercise 7: A data class with a @JvmStatic factory, read with javap

Scenario: A Coupon data class needs a Java-friendly static factory method, and you want to be able to say exactly what calling it generates. What to do: Write data class Coupon(val code: String, val percentOff: Double) with a companion object holding @JvmStatic fun festival(percentOff: Double): Coupon. From Java, create one via Coupon.festival(20.0), print its generated getters, and compare it with .equals() against a manually-constructed equal Coupon. Then run javap -p on both Coupon.class and Coupon$Companion.class and write down, as a comment at the top of your solution file, which class each generated member actually lives on.

Sample output:

FESTIVAL 20.0
true

💡 Hint: @JvmStatic on a companion member adds a forwarding static method to the outer class (Coupon.festival(...)) — the original method is still there too, on Coupon$Companion, which is how Companion.festival(...) would still work from Kotlin.

Show the solutions for Part 12 (14 files)

solutions/ex01/PriceWithGst.kt

package com.stepshala.ex01

fun priceWithGst(amount: Double, category: String): Double {
    val gstPercent = TaxTable.gstPercentFor(category)
    return amount + amount * gstPercent / 100
}

fun main() {
    println(priceWithGst(1000.0, "standard"))
    println(priceWithGst(1000.0, "luxury"))
}

solutions/ex01/TaxTable.java

package com.stepshala.ex01;

public class TaxTable {
    public static double gstPercentFor(String category) {
        switch (category) {
            case "essentials": return 5.0;
            case "standard": return 12.0;
            case "luxury": return 28.0;
            default: throw new IllegalArgumentException("Unknown category: " + category);
        }
    }
}

solutions/ex02/Invoice.java

package com.stepshala.ex02;

public class Invoice {
    private final String number;
    private boolean paidFlag = false;

    public Invoice(String number) {
        this.number = number;
    }

    public String getNumber() {
        return number;
    }

    public boolean isPaid() {
        return paidFlag;
    }

    public void setPaid(boolean paid) {
        this.paidFlag = paid;
    }
}

solutions/ex02/MarkPaid.kt

package com.stepshala.ex02

fun main() {
    val invoice = Invoice("INV-204")
    println("${invoice.number}: paid = ${invoice.isPaid}")   // isXxx getter -> property isPaid
    invoice.isPaid = true                                      // setXxx setter -> same property, assignable
    println("${invoice.number}: paid = ${invoice.isPaid}")
}

solutions/ex03/CallGreeter.java

package com.stepshala.ex03;

public class CallGreeter {
    public static void main(String[] args) {
        System.out.println(Greeter.staticHello("Asha"));           // @JvmStatic: real static method
        System.out.println(Greeter.INSTANCE.instanceHello("Ravi")); // no @JvmStatic: via INSTANCE
    }
}

solutions/ex03/Greeter.kt

package com.stepshala.ex03

object Greeter {
    @JvmStatic
    fun staticHello(name: String): String = "Hello (static), $name"

    fun instanceHello(name: String): String = "Hello (instance), $name"
}

solutions/ex04/CallDiscount.java

package com.stepshala.ex04;

public class CallDiscount {
    public static void main(String[] args) {
        Discount discount = new Discount();
        System.out.println(discount.apply(1000.0));               // uses both defaults
        System.out.println(discount.apply(1000.0, 20.0));          // custom percent, default rounding
        System.out.println(discount.apply(1000.0, 20.0, true));    // all three given
    }
}

solutions/ex04/Discount.kt

package com.stepshala.ex04

class Discount {
    @JvmOverloads
    fun apply(amount: Double, percent: Double = 10.0, roundToRupee: Boolean = false): Double {
        val result = amount - amount * percent / 100
        return if (roundToRupee) Math.round(result).toDouble() else result
    }
}

solutions/ex05/Totals.kt

package com.stepshala.ex05

fun total(values: List<Int>): Int = values.sum()

@JvmName("totalOfLengths")
fun total(values: List<String>): Int = values.sumOf { it.length }

fun main() {
    println(total(listOf(10, 20, 30)))
    println(total(listOf("hi", "there")))
}

solutions/ex06/Lookup.java

package com.stepshala.ex06;

import java.util.HashMap;
import java.util.Map;

public class Lookup {
    private final Map<String, String> pincodeToCity = new HashMap<>();

    public Lookup() {
        pincodeToCity.put("411045", "Pune");
        pincodeToCity.put("560001", "Bengaluru");
    }

    // No annotation -- Kotlin sees this as a platform type (String!), not String or String?.
    public String cityFor(String pincode) {
        return pincodeToCity.get(pincode);
    }
}

solutions/ex06/PrintCity.kt

package com.stepshala.ex06

fun main() {
    val lookup = Lookup()
    val city: String? = lookup.cityFor("999999")   // treat the platform type as nullable ourselves
    println("City: " + (city?.uppercase() ?: "UNKNOWN PINCODE"))
}

solutions/ex06/PrintCityBroken.kt

package com.stepshala.ex06

fun main() {
    val lookup = Lookup()
    val city = lookup.cityFor("999999")   // unknown pincode -> returns null
    println("City: " + city.uppercase())   // compiles fine (platform type); crashes at runtime
}

solutions/ex07/CallCoupon.java

package com.stepshala.ex07;

public class CallCoupon {
    public static void main(String[] args) {
        Coupon coupon = Coupon.festival(20.0);   // @JvmStatic on the companion -- a real static factory
        System.out.println(coupon.getCode() + " " + coupon.getPercentOff());
        System.out.println(coupon.equals(new Coupon("FESTIVAL", 20.0)));
    }
}

solutions/ex07/Coupon.kt

package com.stepshala.ex07

// javap -p Coupon.class: getCode(), getPercentOff(), component1(), component2(), copy(...),
// copy$default(...), toString(), hashCode(), equals(...), the Companion field, AND a forwarding
// static festival(double) -- that last one exists ONLY because of @JvmStatic below.
// javap -p 'Coupon$Companion.class': a private constructor, PLUS the original instance method
// festival(double) -- @JvmStatic doesn't remove it from the companion, it ADDS a copy to Coupon.
data class Coupon(val code: String, val percentOff: Double) {
    companion object {
        @JvmStatic
        fun festival(percentOff: Double): Coupon = Coupon("FESTIVAL", percentOff)
    }
}

Common mistakes

Mistake Why it is wrong Fix
Calling an unannotated Java method and assuming it's non-null It's a platform type (String!) — no compiler warning either way, and section 3's real crash is what's waiting Treat it as nullable yourself: val x: String? = javaCall(), then ?./?:
Writing legacy.surgeActive for an isSurgeActive()/setSurgeActive() pair The is-prefixed property keeps its full name — isSurgeActive, not surgeActive — verified for real while writing this part Use legacy.isSurgeActive
Expecting Obj.method() to work on an object with no @JvmStatic Only INSTANCE carries the method by default Call Obj.INSTANCE.method() from Java, or add @JvmStatic in Kotlin
Giving a Java caller a default-parameter Kotlin function with no @JvmOverloads The JVM has no concept of a default parameter — Java is forced to pass every argument, every time Add @JvmOverloads to generate the real, separate overloads
Two generic functions with the same name whose type parameters erase to one JVM signature platform declaration clash at compile time — List<Int> and List<String> both erase to java.util.List Rename one with @JvmName("newName")
Resolving Kotlin against raw .java source instead of a compiled .class Verified for real in this part: getter/setter property synthesis can silently fail to apply Compile Java first with javac, then point kotlinc at the compiled .class output

Quick recap

  • Java getters/setters become Kotlin properties; is-prefixed booleans keep their full name as the property name — a real surprise, not an assumption.
  • An unannotated Java declaration is a platform type (String!): Kotlin lets you skip the null check, and the JVM will crash at runtime the moment that was the wrong call.
  • @Nullable/@NotNull (or JSpecify's equivalents) turn a platform type into a real, checked T? or T at the boundary.
  • @JvmStatic adds a real static method to an object's class; @JvmOverloads generates real separate overloads for default parameters; @JvmName renames the generated facade class or resolves an erasure-caused signature clash — all three proven with javap, not just described.
  • A data class called from Java exposes plain, ordinary-looking methods — getX(), equals(), toString(), copy() — Java code never has to know it's Kotlin underneath.
  • Most of "the JVM ecosystem" is using JDK and Java library APIs directly, no wrapper needed.

Checklist

  • I compiled a Java class and a Kotlin class together, in dependency order, and ran the result.
  • I triggered the real platform-type NPE myself, then fixed it with an explicit nullable type.
  • I can say what @Nullable/@NotNull change about a platform type.
  • I used javap to prove the bytecode difference @JvmStatic makes.
  • I called a Kotlin function with a default parameter from Java, using @JvmOverloads.
  • I caused a real platform declaration clash, then fixed it with @JvmName.
  • I used a plain JDK API (not a Kotlin wrapper) directly from Kotlin.

Search the guide