Kotlin Static Methods in Java
Introduction
Kotlin Static Methods in Java is a fundamental concept every Kotlin developer should understand. Kotlin and Java compile to the same JVM bytecode, so you can mix both languages in one project with minimal friction.
Companion object functions can be exposed as static methods. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Companion object functions can be exposed as static methods.
- Annotate with @JvmStatic for direct Java call syntax.
- Useful for utility and factory methods.
Syntax
@JvmStatic fun utility() { }Kotlin Static Methods in Java Example Program in Kotlin
class MathUtil {
companion object {
@JvmStatic
fun add(a: Int, b: Int) = a + b
}
}
fun main(args: Array<String>) {
println(MathUtil.add(4, 5))
}Sample Output
9When to use
Use interop when migrating a Java codebase incrementally or calling mature Java libraries from Kotlin.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
fun add(a: Int, b: Int) = a + bassigns or updates a value used later in the program. -
The
println(MathUtil.add(4, 5))statement writes a line to the console — this produces part of the sample output below. -
Companion object functions can be exposed as static methods.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Companion object functions can be exposed as static methods.
- Annotate with @JvmStatic for direct Java call syntax.
- Useful for utility and factory methods.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Nullability annotations help Kotlin and Java agree on which values can be null at boundaries.
- Semicolons at the end of statements are optional in Kotlin.