So here is a sample code :
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please type in a number");
Scanner in = new Scanner(System.in);
switch (in.nextInt()){
case 1:
save(in);
break;
case 2:
System.out.println(value);
break;
default:
System.out.println("Default case");
break;
}
in.close();
}
public static String save(Scanner in){
System.out.println("Type in a word");
String value = in.next();
return value;
}
}
In this particular situation all I am trying to do here is to have access to the value
that was stored in case 1.
switch
statement in all c-like languages including java is very general. It jumps to label according to the value of switch variable and then continues untilbreak
statement appears.I am not sure what did you meant in your long explanation but in following example:
op == ONE
first methodfoo()
will be called, then the flow will arrive to block ofTWO
because no break statement was written inONE
, sobar()
will be called. However then the break statement will jump the flow to code that appears just after the switch.This is a short explanation. For more details find a good book or tutorial and read chapter about switch statement.