Friday, January 19, 2018

Very important information asked frequently in interviews

Facts related to the switch statement in Java programming language.

1. We can not pass float, double, boolean, or long type value or variable inside switch
Only byte, short, int, char, and String is permissible 

Example :

long x = 1L;

float y = 2.0f;

int z = 3;

String str = "hello";

switch(x) <== this is wrong

switch(y) <== this is also wrong

switch(z) <== but, this is correct

switch(str) <== this is also correct

2. We can pass Object name of Integer or Character class inside switch (but the JDK must be 1.5 or above).
     Reason : The Integer will be translated to int (primitive) before using inside switch

 Example :

  Integer ref = 1;
 
  switch(ref) <== this is correct

 3. Only constant can be used along with case keyword.

 Example :

  int number = 1;
  final int choiceOne = 1; <== choiceOne is a constant
  int choiceTwo = 2; <== choiceTwo is a variable
 
switch(number)
{
case choiceOne :  <== this is correct, since we can use a constant 
                along with case
case choiceTwo :  <== this is not correct, since we can not use 
                a variable along with case, it is compiler error
}

4. Order of case of default can be anything, means the default can be written before the case

switch (key)
{
default:
break;

case value:
break;
}

Note : Create a java project in Eclipse IDE and save this class in TheSwitch.java file

public class TheSwitch
{
public static void main(String[] args)
{
int number = 2;
final int choiceOne = 1;
final int choiceTwo = 2;

switch (number)
{
case choiceOne:
System.out.println("case one executes");
break;

case choiceTwo:
System.out.println("case two executes");
break;

default :
System.out.println("default segment executes");
}
}
}

No comments:

Post a Comment