Is there any appreciable difference between if and if-else?

前端 未结 9 889
执笔经年
执笔经年 2021-01-12 06:55

Given the following code snippets, is there any appreciable difference?

public boolean foo(int input) {
   if(input > 10) {
       doStuff();
       retur         


        
9条回答
  •  别那么骄傲
    2021-01-12 07:48

    Think of this case when the two examples won't be similar:

        public boolean foo(int input) {
            if (input > 10) {
                // doStuff();
                return true;
            }
            System.out.println("do some other intermediary stuff");
            if (input == 0) {
                // doOtherStuff();
                return true;
            }
    
            return false;
        }
    

    vs.

        public boolean foo(int input) {
            if (input > 10) {
                // doStuff();
                return true;
            } 
            //System.out.println("doing some intermediary stuff... doesn't work");
            else if (input == 0) {
                // doOtherStuff();
                return true;
            } else {
                return false;
            }
            return false;
        }
    

    The first approach is probably more flexible, but both formulas have their use in different circumstances.

    Regarding performance, I think the differences are to small to be taken in consideration, for any regular java application, coded by sane programmers :).

提交回复
热议问题