📖 Scenario: You are building a simple app that uses a Java class to perform basic math operations. You want to call this Java code from Kotlin without any trouble.
🎯 Goal: Learn how to create a Java class and call its methods from Kotlin code smoothly.
📋 What You'll Learn
Create a Java class with a method to add two numbers
Create a Kotlin variable to hold two numbers
Call the Java method from Kotlin to add the numbers
Print the result in Kotlin
💡 Why This Matters
🌍 Real World
Many Android apps use both Java and Kotlin code. Knowing how to call Java from Kotlin helps you reuse existing Java libraries easily.
💼 Career
Understanding interoperability between Java and Kotlin is important for Android developers and backend developers working with JVM languages.
Progress0 / 4 steps
1
Create a Java class with an add method
Create a Java class called MathOperations with a public static method add that takes two int parameters named a and b and returns their sum.
Kotlin
Hint
Remember to make the method static so you can call it without creating an object.
2
Create Kotlin variables for numbers
In Kotlin, create two val variables named num1 and num2 and assign them the values 10 and 20 respectively.
Kotlin
Hint
Use val to create variables that won't change.
3
Call the Java add method from Kotlin
In the main function, call the Java method MathOperations.add with num1 and num2 as arguments and store the result in a val named sum.
Kotlin
Hint
Call the Java method using the class name directly because it is static.
4
Print the sum result in Kotlin
Add a println statement in the main function to print the text "Sum is: " followed by the value of sum.
Kotlin
Hint
Use println with an f-string style to show the sum.
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