Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Basic If Statements | If and If–Else Expressions
Control Flow in Kotlin

bookBasic If Statements

Swipe um das Menü anzuzeigen

What Is an If Statement?

An if statement lets you run a block of code only when a certain condition is true. This is how you make decisions in your Kotlin programs.

If Statement Syntax

The basic syntax for an if statement in Kotlin looks like this:

if (condition) {
    // Code to run if the condition is true
}
  • The condition must be an expression that returns a Boolean value (true or false);
  • The code inside the curly braces runs only if the condition is true;
  • If the condition is false, the code block is skipped.

Example: Checking a Number

Suppose you want to check if a number is positive:

val number = 10
if (number > 0) {
    println("The number is positive.")
}
  • The condition number > 0 checks if number is greater than zero;
  • If this is true, the message is printed to the console.

No Else Needed

You do not need an else block for a basic if statement. If the condition is false, nothing happens and the program continues.

Indentation and Readability

Indent the code inside the if block for clarity. This makes your code easier to read and understand.

Key Points

  • Use if statements to control what code runs based on conditions;
  • The condition must be a Boolean expression;
  • Only the code inside the block runs when the condition is true;
  • No action is taken if the condition is false and there is no else block.
question mark

When does the code inside an if block in Kotlin execute?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 2. Kapitel 1
some-alt