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.
Practice
(1/5)
1. What is the main advantage of calling Java code from Kotlin seamlessly?
easy
A. You can reuse existing Java code without extra wrappers or adapters.
B. You must convert Java code to Kotlin before using it.
C. Kotlin cannot call Java code directly; it requires JNI.
D. Java code runs slower when called from Kotlin.
Solution
Step 1: Understand interoperability
Kotlin is designed to work directly with Java code without needing extra conversion or wrappers.
Step 2: Identify the benefit
This direct use allows developers to reuse Java libraries and code easily in Kotlin projects.
Final Answer:
You can reuse existing Java code without extra wrappers or adapters. -> Option A