Exercises for the chapter “Variables in Kotlin”

Exercise #1

  • Declare an immutable variable named age with the type int.
  • Assign to the variable the value 35 .
  • Print the value of the variable in the console using the function println() .
Solution to exercise # 1

fun main() {
    val age: Int 
    age = 35    
    println(age) 
}

Exercise #2

  • Declare an immutable variable named age with the type int.
  • Assign to the variable the value 35 .
  • Print the value of the variable in the console using the function println() .
  • Assign the value 55 to the variable.
  • Run the code. Explain the reason for the error.

Solution to exercise # 2

// Den folgenden Code solltest du geschrieben haben:

fun main() {
    val age: Int 
    age = 35    
    println(age) // Output of the value "35"

    age = 55 // At this point, an error occurs because the variable "age" is immutable.
    println(age)
}

Exercise #3

  • Correct the error from exercise #2.
Solution to exercise # 3

fun main() {
    var age: Int   // Declaration of the mutable variable "age" using the keyword "var"
    age = 35    
    println(age)  // Output of the value "35"
    age = 55      // Assignment of a new value to the variable "age"
    println(age)  // Output of the value "55"
}




Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked