logo

Niz u naredbi Switch

U Javi 7, Java vam omogućuje korištenje string objekata u izrazu naredbe switch. Da biste koristili niz, morate uzeti u obzir sljedeće točke:

  • To mora biti samo string objekt.
  •  Object game = 'Hockey'; // It is not allowed String game = 'Hockey'; // It is OK. 
  • String objekt razlikuje velika i mala slova.
  •  'Hickey' and 'hocker' are not equal. 
  • Nema Null objekta

budite oprezni dok prosljeđujete string objekt, prosljeđujući uzrok nultog objekta u NullPointerException.


String u naredbi Switch Primjer 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'); } } } 

Izlaz:

 Let's play Cricket 

Niz u naredbi Switch Primjer 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?'); } } } 

Izlaz:

 This is a indoor game