Results 1 to 4 of 4
  1. #1
    killutch is offline Member
    Join Date
    Sep 2012
    Posts
    70
    Rep Power
    0

    Default short circuit && || rules

    so my book talks about short circuiting and I understand most of it but on testing stuff I found these 2 cases represented in methods. I don't understand why the && short circutes in one but not the other. Anyone have explanation for this or even a link to a explanation.

    Java Code:
    public class myTest {
    	public static void main(String[] args){
    		 test1();
    		 test2();
    	}
    
    	private static void test1() {
    		if(false && true | true)
    		System.out.println("Test 1 Worked");
    	}
    	
    	private static void test2(){
    		if(false && true || true){
    			System.out.println("Test 2 Worked");
    		}
    	}
    }
    output is as follows:

    Test 2 Worked

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: short circuit && || rules

    That's not illustrating shortcircuiting rather it's operator precedence.

    & and | come before && and ||. So "false && true | true" is the same as "false && (true | true)" which is false.

    But in "false && true || true" the operators are of equal precedence so they evaluate left to right: as "(false && true) || true" which is true.

    -----

    In general precedence is all about where to put such implied parentheses. To see shortciruiting in action replace "true" and "false" with calls to a couple of methods t() and f() which should be implemented to print something to say they were called, and return the corresponding boolean value.

  3. #3
    killutch is offline Member
    Join Date
    Sep 2012
    Posts
    70
    Rep Power
    0

    Default Re: short circuit && || rules

    Thank you so much wow ya this isn't confusing at all then. your the best

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

Similar Threads

  1. Package to draw simple circuit and BDD.
    By kapil1089theking in forum Java 2D
    Replies: 6
    Last Post: 11-05-2011, 10:14 PM
  2. Replies: 6
    Last Post: 10-27-2011, 07:40 PM
  3. Replies: 3
    Last Post: 02-20-2011, 01:15 PM
  4. Circuit optimization
    By MIA6 in forum New To Java
    Replies: 1
    Last Post: 10-18-2009, 03:14 AM
  5. Replies: 1
    Last Post: 07-05-2008, 04:08 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
  •