switch statement
The switch statement is a multi way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
Syntax:switch (expression)
{
case value1:
statement 1;
break;
case value2:
statement 2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:-
class Casedemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Output:-
i is greater than 2.
jump statement:-
java supports three jump statement: break, continue and return. These three statements transfer control to other part of the program.
Break:-
In Java, break is majorly used for:
- Terminate a sequence in a switch statement (discussed above).
- To exit a loop.
- Used as a “civilized” form of goto.
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Example:-
class Demo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:-
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Continue:-
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.
Example:-
class Demo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
if (i%2 == 0)
continue;
System.out.print(i + " ");
}
}
}
Output:-
1 3 5 7 9
return:-
The return statement is used to explicitly return from a method. That is, it causes a program control to transfer back to the caller of the method.
Example:-
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if (t)
return;
System.out.println("This won't execute.");
}
}
output:-
Comments
Post a Comment