Master C
Master C

Reputation: 1546

break statement in Java

I wrote a 'setX' method in Java that says that if x value ( (x,y) ) is negative, the value of x wont be change, and the main() will continue as usual.

void setX (int num)
{
       if (num < 0)
            break;
       else
       {
            _x = num; 
       }
}

Am I right ? I am not sure because of the break issue, is the break statement just break from the current method ?

thnx

Upvotes: 0

Views: 2376

Answers (7)

Chris McAtackney
Chris McAtackney

Reputation: 5222

I think your intention might be a bit clearer if your logic was reversed;

void setX (int num)
{
    if (num >= 0)
        _x = num;
}

Upvotes: 0

John Kane
John Kane

Reputation: 4443

That looks like it should work, but the break really isn't doing anything anyway. why not just if(num>=0) _x = num;

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

Perhaps you meant

public void setX(int x) {
   if (x >= 0)
        _x = x; 
}

Upvotes: 3

justkt
justkt

Reputation: 14766

According to the Java tutorial, break is for use with switch, for, while, and do-while loops. It doesn't go in if statements. For a switch the break keeps the switch from falling through to the next case, which it would otherwise do. For loops it stops looping regardless of the loop guards.

A break statement can either be unlabeled, in which case it goes to where control would normally resume after the switch or loop, or labeled, in which case it goes to the label (almost as if it were a goto with strict constraints on where it can come from).

To get out of the current method, use return. A return with no value is the proper statement to leave a void method.

Upvotes: 0

anthonyvd
anthonyvd

Reputation: 7590

Use return; here. break is used to break out of loops.

Upvotes: 0

kdabir
kdabir

Reputation: 9868

you should use return. break is to break loops.

Upvotes: 0

user703016
user703016

Reputation: 37945

break is used only in loops (while, for).

If you want to exit the method, use return instead.

Upvotes: 10

Related Questions