Results 1 to 10 of 10
Like Tree2Likes
  • 1 Post By jashburn
  • 1 Post By gimbal2

Thread: If-Else vs Switch-Case

  1. #1
    R03
    R03 is offline Member
    Join Date
    Apr 2014
    Posts
    10
    Rep Power
    0

    Default If-Else vs Switch-Case

    Hi everyone..
    I'm still learning about Java, last part I've read now is looping, but before I go post about looping.. I'm still confused about if-else vs switch-case What differentiates both, where is part differentiates both? When we use if-else? when we use switch-case? I've asked for some friends, but still not get a good answer.. where i get the answer "The If-else vs switch-case is the same".

    Thank you..

    Regards,
    R03.

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

    Default Re: If-Else vs Switch-Case

    A switch statement can be (and usually is) much faster than a chain of if-else if .. statements; a switch statement has 'special' code to find the matching case clause, while the chain of if-else if ... statements possibly has to test each clause in each if( ... ) part.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    R03
    R03 is offline Member
    Join Date
    Apr 2014
    Posts
    10
    Rep Power
    0

    Default Re: If-Else vs Switch-Case

    Quote Originally Posted by JosAH View Post
    A switch statement can be (and usually is) much faster than a chain of if-else if .. statements; a switch statement has 'special' code to find the matching case clause, while the chain of if-else if ... statements possibly has to test each clause in each if( ... ) part.

    kind regards,

    Jos
    Hi Jos,

    Thank you for replying..
    I read too on some website were switch statement faster than if-else/if statement as like you said.. , but how to know switch statement faster than if-else/if statement ?

    Below are case..

    Java Code:
    public class Decision_Making_4_Switch {
    	public static void main (String [] args){
    		int x = 6;
    		
    		switch (x){
    		case 1 :
    			System.out.println ("One");
    			break;
    		case 2 :
    			System.out.println ("Two");
    			break;
    		case 3 :
    			System.out.println ("Three");
    			break;
    		case 4 :
    			System.out.println ("Four");
    			break;
    		default :
    			System.out.println ("None of the above");	
    		}
    	}
    
    }
    The result  : None of the above
    Java Code:
    public class Decision_Making_6 {
    	public static void main(String[] args) {
    
    		int x = 6;
    
    		if (x == 1) {
    			System.out.println("One");
    		} else if (x == 2) {
    			System.out.println("Two");
    		} else if (x == 3) {
    			System.out.println("Three");
    		} else if (x == 4) {
    			System.out.println("Four");
    		}
    
    		else {
    			System.out.println("None of above is valid");
    		}
    
    	}
    
    }
    The result : None of above is valid

    i'm sorry about my question :)

    Regards,

    R03.
    Last edited by R03; 04-27-2014 at 11:22 AM. Reason: forget the result

  4. #4
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: If-Else vs Switch-Case

    Hi,

    first of all I would forget this "x is a little faster than y" stuff. That is complete nonsense regarding software development. One big rule is to keep stuff easy and simple and optimizing stuff is often simply misleading. (And if you find, that optimisation is required, then you really check where your code takes to long and then think about the possibilities. And that is NOT "I replace an if else if with a switch statement!")

    And the next important things is clean code. Your code must be readable and if you have to do different things dependend on one variable, then the switch statement is much easier to read. The code is nicely structured.
    But sometimes you have more complex cases e.g.
    if (x == 1) {
    // Do something
    } else if (y == 1) {
    // Do something else when x is not 1 but y is 1
    } else {
    // Do something when x and y are both not 1
    }

    But you should think about the readability and such constructs might be harder to read. There are some nice refactoring methods that could make it much easier to read:
    a) introduction of methods:
    if (this.isCaseA()) {
    // Handle case A
    } else if (this.isCaseB()) {
    // handle Case B
    } else {
    // ...
    }

    But this can still be misleading because a reader might be confused because the second if is only executed when the first if check was negative.

    Regarding the case statement an easy method to make it readable could be an enumeration or constants. So in code like
    switch(x) {
    case 1: // ...
    case 2: // ...
    // ...
    }
    You can replace the 1 / 2 / ... with readable names from a constant or enumeration.

    With kind regards,

    Konrad

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

    Default Re: If-Else vs Switch-Case

    Quote Originally Posted by kneitzel View Post
    first of all I would forget this "x is a little faster than y" stuff. That is complete nonsense regarding software development.
    I (sort of) disagree w.r.t. a switch statement w.r.t. a chain of if-else-if ... statements; the applicability of a switch statement is quite small: it can compare a single integral value against a set of (unique) integral values and determine which of the case clauses is to be executed; but it does this much faster than a chain of if-else-if statements; if a switch condition applies, there is no need (imho of course) to 'mimic' it with a chain of if-else-if ... statements. Most (if not all) compilers are too stupid to do the reverse conversion (from the if-else-if statements to a switch statement) automatically.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: If-Else vs Switch-Case

    A factor to consider is the data type with which code branching is to be performed. The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics) has a good description on the data types that can be used in a switch statement, summarised below:
    • primitives
    • enumerated types
    • String (from Java 7 onwards)
    • special classes that wrap primitives

    If code is to be branched based on arbitrary and/or complex logical conditions, then you'd find that it'll be very awkward to use switch-case. E.g., I wouldn't use switch-case if branching is dependent on:
    • if a File object is associated with a file (as opposed to a directory), and
    • the file's length is < 5000 bytes, or
    • if the File object is associated with a directory

    Doing the above using if-else would be something like
    Java Code:
    if ((file.isFile() && file.length() < 5000) || file.isDirectory())
    I wouldn't implement this using switch-case.

    Another factor to consider is the features that are made available for use. E.g., switch-case supports "fall through." The SwitchDemoFallThrough example from the tutorial link above shows how this feature can be exploited to produce quite-neat code compared to an implementation using if-else (which I'd leave as an exercise for you).

    In general, imo, you choose the one that results in simpler and more readable code.
    kneitzel likes this.

  7. #7
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: If-Else vs Switch-Case

    Jos: First of all I want to point out that I am also saying, that a switch statement should be used when possible.

    But the argument regarding speed could be misleading. If speed starts to be an argument, then people could use this as an argument against other rules that help with clean code. So instead of introducing small functions you start having bigger functions and maybe even double code because a function call comes with an overhead... arguments like that.

    And maybe a chain of if else if is optimized in the future. Maybe they find a way that it is even faster than your switch statement. Do you start rewriting your code? (If that is an real argument you might want to)...

    In my eyes a switch statement is much easier to read and that is the main reason why I am using that wherever possible.

    And that is the same reason why I use which loop. Instead of while (condition) you could write for (;condition;) { } and even add some commands at the initializing step and the increment step ... But the different loops are used in different areas and developers are used to that usage. So for clean code you should stick to that usage.

    I hope I was able to clarify my position. Of course: I do not want to convince anyone. It is completely ok (and normal) that developers have a different view what "clean code" means and which areas are how important.

    Konrad

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,900
    Rep Power
    5

    Default Re: If-Else vs Switch-Case

    Quote Originally Posted by kneitzel View Post
    In my eyes a switch statement is much easier to read and that is the main reason why I am using that wherever possible.
    Fall-through and labels.

    That's why I detest the switch statement and will forever and always avoid it. But I won't recommend other people to do the same, its a personal thing. Enforcing your own opinion on others is not the way to go, people should use what they're comfortable with.
    kneitzel likes this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: If-Else vs Switch-Case

    Quote Originally Posted by gimbal2 View Post
    Fall-through and labels.
    That are good points / arguments! And exchange of arguments is never bad. But it always depends on the persons what they do out of it (e.g. static code checks that gives a warning or error when a break is missing. Or simply be more aware about the risk.)

    With kind regards,

    Konrad

  10. #10
    R03
    R03 is offline Member
    Join Date
    Apr 2014
    Posts
    10
    Rep Power
    0

    Default Re: If-Else vs Switch-Case

    Quote Originally Posted by JosAH View Post
    I (sort of) disagree w.r.t. a switch statement w.r.t. a chain of if-else-if ... statements; the applicability of a switch statement is quite small: it can compare a single integral value against a set of (unique) integral values and determine which of the case clauses is to be executed; but it does this much faster than a chain of if-else-if statements; if a switch condition applies, there is no need (imho of course) to 'mimic' it with a chain of if-else-if ... statements. Most (if not all) compilers are too stupid to do the reverse conversion (from the if-else-if statements to a switch statement) automatically.

    kind regards,

    Jos
    Hi Jos,

    Can you give an example java code about this ? i'm quite not understood about your statement
    where can compare single integral against a set of (unique) integral values

    many thanks

    Regards,
    R03.

    Quote Originally Posted by jashburn View Post
    A factor to consider is the data type with which code branching is to be performed. The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics) has a good description on the data types that can be used in a switch statement, summarised below:
    • primitives
    • enumerated types
    • String (from Java 7 onwards)
    • special classes that wrap primitives

    If code is to be branched based on arbitrary and/or complex logical conditions, then you'd find that it'll be very awkward to use switch-case. E.g., I wouldn't use switch-case if branching is dependent on:
    • if a File object is associated with a file (as opposed to a directory), and
    • the file's length is < 5000 bytes, or
    • if the File object is associated with a directory

    Doing the above using if-else would be something like
    Java Code:
    if ((file.isFile() && file.length() < 5000) || file.isDirectory())
    I wouldn't implement this using switch-case.

    Another factor to consider is the features that are made available for use. E.g., switch-case supports "fall through." The SwitchDemoFallThrough example from the tutorial link above shows how this feature can be exploited to produce quite-neat code compared to an implementation using if-else (which I'd leave as an exercise for you).

    In general, imo, you choose the one that results in simpler and more readable code.
    Hi jashburn,

    thank you for simple explaining.. actually i'm not yet learning like that.. still do simple programming, from the source you have shared, i have a lot of question before i answer your question about (exercise) you asked..

    i apologize.. because i learn very slowly...

    for my exercise could make another simple question ?




    regards,
    R03.




    For Konrad kneitzel
    Thank you very much for explaining, still reading and learning from your comment..

    regards,
    R03.
    Last edited by R03; 04-29-2014 at 02:05 AM.

Similar Threads

  1. switch case help! :(
    By domtay in forum New To Java
    Replies: 12
    Last Post: 12-18-2013, 08:43 AM
  2. switch case help! :(
    By domtay in forum Advanced Java
    Replies: 1
    Last Post: 12-17-2013, 11:34 AM
  3. [SOLVED] switch case with '<='
    By Adomini in forum New To Java
    Replies: 9
    Last Post: 02-17-2013, 04:01 PM
  4. Using a switch/case with my if statements
    By coding in forum New To Java
    Replies: 2
    Last Post: 03-07-2011, 08:01 AM
  5. if else changes to switch-case?
    By noobinoo in forum New To Java
    Replies: 1
    Last Post: 04-23-2010, 05:56 PM

Tags for this Thread

Posting Permissions

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