0
0
Kotlinprogramming~30 mins

Calling Java from Kotlin seamlessly - Mini Project: Build & Apply

Choose your learning style9 modes available
Calling Java from Kotlin seamlessly
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use println with an f-string style to show the sum.