All Products
Search
Document Center

OpenSearch:Branch structures in Cava

Last Updated:Sep 09, 2021

Overview

A branch structure in Cava is used to determine the statement block to be executed based on a condition. Cava supports only if branch structures, and does not support switch branch structures. The if branch structures have three types: if, if else, and if else if. You can select a type as required.

if statement

Syntax:

if (condition) { // condition is a Boolean expression.
    // Code to be run if condition is true
}

Sample code:

class Example {
    static int main() {
        int a = 1;
        int b = 2;
        if (a < b) {
            a = b;
        }
        return a;
    }
}

if ... else ... statement

Syntax:

if (condition) { // condition is a Boolean expression.
    // Code to be run if condition is true
} else {
    // Code to be run if condition is false
}

Sample code:

class Example {
    static int main() {
        int a = 1;
        int b = 2;
        if (a < b) {
            a = b * 10;
        } else {
            a = b * 20;
        }
        return a;
    }
}

if ... else if ... else statement

An if ... else if ... else statement is used when multiple conditions need to be checked. Take note of the following points when you use an if ... else if ... else statement:

  • The statement can contain up to one else branch, and the else branch must be after else if branches.

  • The statement can contain multiple else if branches, and the else if branches must be before the else branch.

  • The statement determines whether a condition is true one by one during execution. If one branch is true, other branches are not executed.

Syntax:

if (condition1) { // condition1 is a Boolean expression.
    // Code to be run if condition1 is true
} else if (condition2) {
    // Code to be run if condition2 is true
} else {
    // Code to be run if both condition1 and condition2 are false
}

Sample code:

class Example {
    static int main() {
        int a = 2;
        if (a == b) {
            a = 10;
        } else if (a == 2) {
            a = 20;
        } else if (a == 3) {
            a = 30;
        } else {
            a = 40;
        }
        return a;
    }
}