Java では、equals メソッドを使用して文字列を比較する必要があります。
if ( input.equals("1") ) {
// do something...
}
Java 7 以降、switch ステートメントでも文字列を使用できます。
switch ( input ) {
case "1":
// do something...
break;
case "2":
// do something...
break;
}
編集:私の答えを補完するために、文字列とクラスの逆アセンブルコード(javap -cを使用)でスイッチを使用するクラスの例と、それが機能する理由(ラベル8と11)を次に示します。
Foo.java
public class Foo {
public static void main( String[] args ) {
String str = "foo";
switch ( str ) {
case "foo":
System.out.println( "Foo!!!" );
break;
case "bar":
System.out.println( "Bar!!!" );
break;
default:
System.out.println( "Neither Foo nor Bar :(" );
break;
}
}
}
逆アセンブルされた Foo.class コード:
Compiled from "Foo.java"
public class Foo {
public Foo();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2 // String foo
2: astore_1
3: aload_1
4: astore_2
5: iconst_m1
6: istore_3
7: aload_2
8: invokevirtual #3 // Method java/lang/String.hashCode:()I << hashCode here! (I wrote this!)
11: lookupswitch { // 2
97299: 50 // 97299: hashCode of "bar" (I wrote this!)
101574: 36 // 101574: hashCode of "foo" (I wrote this!) (yep, they where swaped. the lesser hashCode first)
default: 61
}
36: aload_2
37: ldc #2 // String foo
39: invokevirtual #4 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
42: ifeq 61
45: iconst_0
46: istore_3
47: goto 61
50: aload_2
51: ldc #5 // String bar
53: invokevirtual #4 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
56: ifeq 61
59: iconst_1
60: istore_3
61: iload_3
62: lookupswitch { // 2
0: 88
1: 99
default: 110
}
88: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
91: ldc #7 // String Foo!!!
93: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
96: goto 118
99: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
102: ldc #9 // String Bar!!!
104: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
107: goto 118
110: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
113: ldc #10 // String Neither Foo nor Bar :(
115: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
118: return
}
1 つの興味深い点は、別のスイッチ (ラベル 62) が整数で作成され、それが「実際の作業」を行うことです。