Python Logo

Kotlin Basic Example


Simple basic Kotlin sample code with explanation:

 

fun main() {
  // Declare and initialize a variable of type String
  val name: String = "John Doe"

  // Print a greeting message using the variable
  println("Hello, $name!")

  // Calculate the sum of two integers
  val num1 = 10
  val num2 = 20
  val sum = num1 + num2
  println("The sum of $num1 and $num2 is $sum")

  // Check if a number is even or odd
  val num3 = 15
  if (num3 % 2 == 0) {
    println("$num3 is an even number.")
  } else {
    println("$num3 is an odd number.")
  }
}
 

Explanation:

  1. The fun main() line defines the main function, which is the entry point for the program.
  2. The val name: String = "John Doe" line declares a variable named name of type String and initializes it with the value "John Doe".
  3. The println("Hello, <span class="math-inline">name\!"\)\ line prints the greeting message "Hello, John Doe!" to the console. The `symbol is used to embed the value of thename` variable into the string.
  4. The val num1 = 10 and val num2 = 20 lines declare and initialize two variables, num1 and num2, of type Int with the values 10 and 20, respectively.
  5. The val sum = num1 + num2 line calculates the sum of the values of num1 and num2 and stores the result in the variable sum.
  6. The println("The sum of $num1 and $num2 is $sum") line prints a message to the console stating the sum of num1 and num2.
  7. The val num3 = 15 line declares and initializes a variable named num3 of type Int with the value 15.
  8. The if (num3 % 2 == 0) line checks if the value of num3 is divisible by 2, which indicates whether it is an even number.
  9. If the condition is true, the println("$num3 is an even number.") line prints a message to the console indicating that num3 is even.
  10. If the condition is false, the println("$num3 is an odd number.") line prints a message to the console indicating that num3 is odd.

This simple code demonstrates basic programming concepts such as variable declaration, data types, arithmetic operations, conditional statements, and string formatting.