Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement using a String type

Tags:

android

I'm trying to switch a string type value which I have made static. However I can't figure out how to put this into a switch statement I was previously using an 'if else' statement but due to the number of items I want to switch this doesn't work.

For the if else I was using `

if (item.ActivityFeedType.equals("Comment"))

for switch I;m trying to use

case (item.ActivityFeedType.equals("Comment")):

Is there something I'm missing?

like image 513
Sim Avatar asked Feb 24 '15 11:02

Sim


2 Answers

  1. switch for Strings exists, but it's only available starting from Java 7. The syntax actually is just as with an Integer switch:

    String test = "test";
    switch (test) { 
        case "testt": 
            System.out.println("Wrong"); 
            break; 
        case "test": 
            System.out.println("Got it"); 
            break; 
    }
    
  2. There is no situation that a switch can handle, but a simple if-else could not. A switch simply is more convenient.

  3. I'd recommend selecting lower-case starting letters for a Class' attributes.

like image 70
FD_ Avatar answered Oct 20 '22 00:10

FD_


Thouhg if you are working with Java 1.7,
Java's switch-case allows only constant variable in case.

like image 36
ytRino Avatar answered Oct 20 '22 02:10

ytRino