Kotlin Program – Add Two Numbers

In Kotlin, you can add two numbers using Arithmetic Addition Operator `+`. The addition operator accepts two operands and returns the result of their sum.

We can take values of same data type or combination of supported numeric data types: int, float, double, etc., to compute the sum.

Syntax

The syntax of arithmetic addition operator to find the sum of given two operands is is

``result = operand1 + operand2``

`+` operator adds the numbers operand1operand2; and returns the result. In the above syntax, we are storing the result in a variable named result.

Examples

In the following example, we will take two numbers of integer data type and add these two numbers.

Kotlin Program

``````fun main() {
val a = 4
val b = 8
val sum = a + b
println("Sum : \$sum")
}``````

Output

``Sum : 12``

The data type of both `a` and `b` is int. Therefore, the data type of the result, `sum`, is also int.

In the following example, we add two numbers of data type float. The returned value will be of type float.

Kotlin Program

``````fun main() {
val a = 4.56f
val b = 1.23f
val sum = a + b
println("Sum : \$sum")
}``````

Output

``Sum : 5.79``

In the following example, we have a variable `a` with data of type float and another variable `b` holding data of type int. We will add these two numbers using `+` operator.

Kotlin Program

``````fun main() {
val a = 4
val b = 1.23f
val sum = a + b
println("Sum : \$sum")
}``````

Output

``Sum : 5.23``

As already mentioned, the type of variable a is float and the type of variable b is int. When you add two numbers with different data types, the lower type is promoted to higher data type, and this promotion happens implicitly. As in here, when you add int and float, int is promoted to float. The higher data type of the operands becomes the data type of result.