0
0
Kotlinprogramming~5 mins

Calling Java from Kotlin seamlessly

Choose your learning style9 modes available
Introduction

Sometimes you want to use Java code inside your Kotlin program without extra work. Kotlin lets you call Java code easily, so you can mix both languages smoothly.

You have existing Java libraries and want to use them in your new Kotlin app.
You want to reuse Java code without rewriting it in Kotlin.
You are working on a project with both Java and Kotlin files.
You want to call Java methods or classes directly from Kotlin.
You want to gradually convert a Java project to Kotlin.
Syntax
Kotlin
val javaObject = JavaClass()
javaObject.javaMethod()
You can create Java objects and call their methods just like Kotlin objects.
Kotlin automatically understands Java classes, methods, and fields.
Examples
Creating a Java class object and calling its method from Kotlin.
Kotlin
val person = Person("Alice")
println(person.getName())
Using Java's ArrayList class in Kotlin code.
Kotlin
val list = ArrayList<String>()
list.add("Hello")
println(list.size)
Sample Program

This Kotlin program creates an object of a Java class Car and calls its methods to print details.

Kotlin
fun main() {
    val car = Car("Toyota", 2020)
    println("Car brand: ${car.brand}")
    println("Car year: ${car.year}")
}

// Java class in the same project
// public class Car {
//     private String brand;
//     private int year;
//     public Car(String brand, int year) {
//         this.brand = brand;
//         this.year = year;
//     }
//     public String getBrand() { return brand; }
//     public int getYear() { return year; }
// }
OutputSuccess
Important Notes

Kotlin treats Java getters and setters as properties, so you can also write car.brand instead of car.getBrand().

Static Java methods can be called using the class name directly in Kotlin.

Null safety is important: Java types may be nullable in Kotlin, so check for nulls.

Summary

Kotlin can use Java classes and methods directly without extra code.

You can create Java objects and call their methods just like Kotlin objects.

This makes mixing Java and Kotlin easy and helps reuse existing code.