Variables in Karel

Here’s the translated code and explanation in Markdown format suitable for Hugo:

Our first example demonstrates how to declare and use variables. In this language, variables are explicitly declared and used by the compiler to check type-correctness of function calls, among other things.

public class Variables {
    public static void main(String[] args) {
        // String variables can be declared and initialized
        String a = "initial";
        System.out.println(a);

        // You can declare multiple variables of the same type at once
        int b = 1, c = 2;
        System.out.println(b + " " + c);

        // The type is inferred for initialized variables
        var d = true;
        System.out.println(d);

        // Variables declared without initialization are given default values
        // For example, the default value for an int is 0
        int e;
        System.out.println(e);

        // Variables can be declared and initialized in a single line
        String f = "apple";
        System.out.println(f);
    }
}

Let’s break down the different ways of declaring and using variables:

  1. We declare a String variable a and initialize it with the value “initial”.

  2. Multiple variables of the same type (in this case, int) can be declared and initialized in a single line.

  3. The var keyword can be used for local variable type inference. The compiler will infer the type based on the assigned value.

  4. Variables declared without initialization are given default values. For numeric types like int, the default value is 0.

  5. We can declare and initialize a variable in a single line, as shown with the String variable f.

When you run this program, you’ll see the following output:

initial
1 2
true
0
apple

This example demonstrates various ways to declare and use variables in the language, including type inference, multiple declarations, and default values.