Reputation: 231
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
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
Reputation: 1459
Thouhg if you are working with Java 1.7,
Java's switch-case
allows only constant variable in case
.
Upvotes: 3
Reputation: 12919
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;
}
There is no situation that a switch can handle, but a simple if-else could not. A switch simply is more convenient.
I'd recommend selecting lower-case starting letters for a Class' attributes.
Upvotes: 20
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
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
Reputation: 2609
if you are using java version 7+
switch(item.ActivityFeedType){
case "Comment":
//do stuff
break;
}
Upvotes: 0
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