In this tutorial, you shall learn about Increment operator in Kotlin, its syntax, and how to use Increment operator in programs, with examples.

Kotlin Increment

Kotlin Increment Operator takes a variable as operand and increments the value in variable by one.

++ symbol is used for Increment Operator.

There are two types of increment operations based on the position of operand for the operator.

  1. Pre-increment
  2. Post-increment

Syntax

The syntax for Increment Operator is

</>
Copy
//pre-increment
++operand

//post-increment
operand++

The operands could be of any numeric datatype.

For Pre-increment operation, first the value in the variable is incremented, and then the value is substituted in the expression or current statement.

For Post-increment operation, first the current statement is executed, and then the value in the variable is incremented.

Examples

1. Increment a variable

In the following example, we take an integer value in a, and increment its value using Increment Operator.

Main.kt

</>
Copy
fun main() {
    var a = 5
    a++
    println("a : $a")
}

Output

a : 6

2. Increment a decimal value

In the following example, we take a decimal value in a, and increment its value using Increment Operator.

Main.kt

</>
Copy
fun main() {
    var a = 5.748
    a++
    println("a : $a")
}

Output

a : 6.748

3. Pre-increment

In the previous examples, we have seen post-increment operation. But in this example, we will see how a pre-increment operation works.

In the following example, we take an integer value in a, and pre-increment its value using Increment Operator.

Main.kt

</>
Copy
fun main() {
    var a = 5
    var result = ++a * 4
    println("a : $result")
}

Output

a : 24

The value in a is incremented by 1, and then that value of a is substituted in the expression.

Now, let us take the same example, but with post-increment operation.

Main.kt

</>
Copy
fun main() {
    var a = 5
    var result = a++ * 4
    println("a : $result")
}

Output

a : 20

First the expression a * 4 is evaluated, and then the increment of a happens. If you print the value of a after the third line, then you would observe that the value in a is incremented.

Conclusion

In this Kotlin Tutorial, we learned how to use Increment Operator to increase the value in a variable by one.