Switch is another flavor decision in Java. It depends on your problem whether you use IF else of switch. So lets quickly see an example and try to under stand what the switch actually is.
public class SwitchTest {
public static void main(String[] Args)
{
int marks = 80;
switch(marks)
{
case 80:
System.out.println("You have got good grades.");
break;
case 60:
System.out.println("You grades are average.");
break;
case 40:
System.out.println("Poor.");
break;
default:
System.out.println("you didn't told ur marks");
break;
}
}
}
So as you can see in above example we have again the same old variable "mark". And in the next line we have "switch" statement. In the () we have our variable. Next {} have the cases of switch statement. Cases are the conditions. We ask our code that if our variable has this value then do this. For example in above code we have asked if marks have the value of "80" then print "You have got good grades.". And the there is a break statement which will take us out of the {} of the switch. If none of the statement is true then a default code or statement will be executed.
One thing should be remembered that after the case we have ":" NOT ";". So be careful or compiler will give syntax error.
So how was this lesson. Hopefully you have enjoyed it. But if you have any problem please write us. We'll be happy to help you. Bye
No comments:
Post a Comment