Kotlin Increment

Kotlin Increment Operator

Kotlin Increment Operator increments the value in given operand by one.

Syntax

The syntax to use Arithmetic Increment operator is

++n

or

n++

where n is the given number, and ++ is the symbol used for Increment operator.

Return value

The datatype of return value is same as that of the given value.

Pre-increment

++n, called Pre-increment, increments the value by one and then evaluates the statement. The increment happens before (pre) the execution of the present statement, hence the word Pre.

Post-increment

n++, called Post-increment evaluates the statement and then increments the value. The increment happens after (post) the execution of the present statement, hence the word Post.

Examples

Increment the value in n

In the following program, we take a variables: n initialised with a value of 6; and increment it using Increment operator.

Kotlin Program

fun main() {
    var n = 6
    ++n
    println("n = $n")
}

Output

n = 7

Increment floating point value 3.14

In the following program, we take a floating point value in variable n, and increment it using Increment operator.

Kotlin Program

fun main() {
    var n = 3.14
    ++n
    println("n = $n")
}

Output

n = 4.140000000000001

Pre-increment vs Post-increment

In the following program, we take same integer value in two variables an and b. We increment the value in a println statement, and print the values during increment operation and after increment operation.

The pre-increment, first increments the value in the variable and then applies the value in the statement, whereas post-increment first executes the statement and then increments the value.

Kotlin Program

fun main() {
    var a = 6
    var b = 6

    println("Pre-increment")
    println("a = ${++a}")
    println("a = $a")

    println("Post-increment")
    println("b = ${b++}")
    println("b = $b")
}

Output

Pre-increment
a = 7
a = 7
Post-increment
b = 6
b = 7