Chaîne dans l'instruction Switch
Dans Java 7, Java vous permet d'utiliser des objets chaîne dans l'expression de l'instruction switch. Pour utiliser une chaîne, vous devez prendre en compte les points suivants :
- Il doit s'agir uniquement d'un objet chaîne.
Object game = 'Hockey'; // It is not allowed String game = 'Hockey'; // It is OK.
'Hickey' and 'hocker' are not equal.
soyez prudent lorsque vous passez un objet chaîne, en passant un objet nul à NullPointerException.
Chaîne dans l'instruction Switch, exemple 1
public class StringInSwitchStatementExample { public static void main(String[] args) { String game = 'Cricket'; switch(game){ case 'Hockey': System.out.println('Let's play Hockey'); break; case 'Cricket': System.out.println('Let's play Cricket'); break; case 'Football': System.out.println('Let's play Football'); } } } Sortir:
Let's play Cricket
Chaîne dans l'instruction Switch, exemple 2
public class StringInSwitchStatementExample { public static void main(String[] args) { String game = 'Card-Games'; switch(game){ case 'Hockey': case'Cricket': case'Football': System.out.println('This is a outdoor game'); break; case 'Chess': case'Card-Games': case'Puzzles': case'Indoor basketball': System.out.println('This is a indoor game'); break; default: System.out.println('What game it is?'); } } } Sortir:
This is a indoor game