Kotlin Decrement

Kotlin Decrement Operator

Kotlin Decrement Operator decrements the value in given operand by one.

Syntax

The syntax to use Arithmetic Decrement operator is

--n

or

n--

where n is the given number, and -- is the symbol used for Decrement operator.

Return value

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

Pre-decrement

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

Post-decrement

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

Examples

Decrement the value in n

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

Kotlin Program

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

Output

n = 5

Decrement floating point value 3.14

In the following program, we take a floating point value in variable n, and decrement it by one using Decrement operator.

Kotlin Program

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

Output

n = 4.140000000000001

Pre-decrement vs Post-decrement

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 decrement operation and after decrement operation.

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

Kotlin Program

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

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

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

Output

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