Results 1 to 4 of 4
  1. #1
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default question about how if statements work

    Consider this if statement:

    if (boolean1 || boolean2) {
    ... blah blah blah
    }

    Will the Java runtime environment always check both boolean values before it executes the code "blah blah blah", or will it check only one of them if it turns out to be true (and if so which one)?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,560
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by gib65 View Post
    Consider this if statement:

    if (boolean1 || boolean2) {
    ... blah blah blah
    }

    Will the Java runtime environment always check both boolean values before it executes the code "blah blah blah", or will it check only one of them if it turns out to be true (and if so which one)?
    If boolean1 turns out to be true boolean2 is not evaluated because the entire expression is true anyway.

    kind regards,

    Jos

  3. #3
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Thanks Jos

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    This is true for the || and && boolean operators -- they both will short-circuit in the appropriate circumstance, but contrast that to the | and & operators which don't.

Similar Threads

  1. if else statements
    By sweetpea123 in forum New To Java
    Replies: 4
    Last Post: 04-12-2010, 07:02 PM
  2. age: using if statements
    By yasmin k in forum New To Java
    Replies: 2
    Last Post: 10-04-2009, 09:50 PM
  3. Help with if-else statements
    By porchrat in forum New To Java
    Replies: 4
    Last Post: 03-23-2009, 04:24 PM
  4. Replies: 2
    Last Post: 11-22-2008, 05:30 AM
  5. Help with if else statements
    By zoe in forum New To Java
    Replies: 1
    Last Post: 07-24-2007, 07:56 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •