Example: Kotlin Program to Add Two Integers
fun main(args: Array<String>) {
val first: Int = 10
val second: Int = 20
val sum = first + second
println("The sum is: $sum")
}
When you run the program, the output will be:
The sum is: 30
In this program, similar to Java, two integers 10
and 20
are stored in integer variables first and second respectively. It is not mandatory to add :Int
in the variable declaration, Kotlin automatically assigns a type (in this case Int
).
Then, first and second are added using the +
operator, and its result is stored in another variable sum.
Finally, sum is printed on the screen using println()
function.
Here's the equivalent code in Java: Add two integers in Java.