Sim
Sim

Reputation: 231

Switch statement using a String type

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?

Upvotes: 8

Views: 20242

Answers (7)

Hitesh Sahu
Hitesh Sahu

Reputation: 45110

Add Java 1.7 in build gradle

android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Upvotes: 0

ytRino
ytRino

Reputation: 1459

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

Upvotes: 3

FD_
FD_

Reputation: 12919

  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.

Upvotes: 20

Nagaraju V
Nagaraju V

Reputation: 2757

Note : Below java 7 it is not possible to use strings in switch.

if you are using java 7 or above you can use as below

String item="mango";

switch(item){
case "mango" :
      System.out.println("this is mango");
 break;
 ............
 ............
}

Upvotes: 1

Kiril Aleksandrov
Kiril Aleksandrov

Reputation: 2591

The java 6 compiler does not allow you to use switch with reference types (String, Object, etc.). You can only do this with the following value types - byte, short, char, and int. If you use a higher version of the JVM, you can do a switch over String values too.

Now to your question. The android build tools use JVM 6 so you cannot use the new switch abilities.

Upvotes: 1

Arnav M.
Arnav M.

Reputation: 2609

if you are using java version 7+

switch(item.ActivityFeedType){
case "Comment":
//do stuff
break;
}

Upvotes: 0

Dr. Dreave
Dr. Dreave

Reputation: 539

It is impossible to switch strings below jdk 7.

You should get an error message similiar to:

Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted

Upvotes: 1

Related Questions