Skip to content

Control structures

Kay Kasemir edited this page Apr 18, 2019 · 2 revisions

Invoke Method

Invoke method in same class:

name_of_method();
method_that_takes_arguments(42, "Some Text");

Invoke method in another object:

some_object.name_of_method();

Invoke a class method (static on that class):

NameOfClass.name_of_method();

The code within a method usually runs instruction by instruction until reaching the end of the method. You can return early from the method via the return instruction:

void some_method()
{
    int i=2;
    if (i>1)
        return;
    i = 10;
}

When a method is not of type void but has a value, it uses that same return instruction to return the value:

double average(double a, double b)
{
    double result = (a + b)/2.0;
    return result;

'If'

if (some_true_or_false_condition)
    do_one_thing();
if (some_true_or_false_condition)
    do_one_thing();
else
    do_something_else();
if (some_true_or_false_condition)
{
    do_one_thing();
    do_another_thing();
}
else
{
    do_something_else();
    and_then_yet_something_else();
}

Beware of

if (some_true_or_false_condition);
    will_always_do_this();

because that's really

if (some_true_or_false_condition)
    /* Do nothing, really */;

will_always_do_this();

'while'

while (some_condition)
{
    do_something();
    do_another_thing();
}
do
{
    do_something();
    do_another_thing();
}
while (some_condition);

'for'

The 'for' loop is syntactical sugar for an equivalent 'while' loop.

for (/* Initial code */ ;  /* while condition */;   /* end-of-while-loop-code */)
{
    /* while loop code */
}

Example:

// Print numbers 0 to 99
for (int i=0; i<100; ++i)
{
    System.out.println(i);
}

is the same as

int i=0;
while (i<100)
{
    System.out.println(i);
    ++i;
}

break, continue

Within the { ... } block of a while or for loop, you can use break to exit the loop early, or continue to jump to the next loop iteration.

This will only print multiples of 3, and stop when reaching 30:

// Print numbers 0 to 99
for (int i=0; i<100; ++i)
{
    if ( (i%3) != 0)
        continue;
    System.out.println(i);
    if (i >= 30)
        break;
}
Clone this wiki locally