0% found this document useful (0 votes)
25 views

Control Statements

The document discusses various control statements in Java including if-else statements, switch statements, iteration statements like while, do-while and for loops, and jump statements like break, continue and return. It provides examples of using these statements and some variations like labeled breaks, empty initialization or condition parts in for loops, and foreach loops.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Control Statements

The document discusses various control statements in Java including if-else statements, switch statements, iteration statements like while, do-while and for loops, and jump statements like break, continue and return. It provides examples of using these statements and some variations like labeled breaks, empty initialization or condition parts in for loops, and foreach loops.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

• Control Statements

• If:
• if (condition) statement1;
• else statement2;

• Nested If:
• if(i == 10) {
• if(j < 20) a = b;
• if(k > 100) c = d; // this if is
• else a = c; // associated with this else
• }
• else a = d; // this else refers to if(i == 10)
• The if-else-if Ladder:
• if(condition)
• statement;
• else if(condition)
• statement;
• else if(condition)
• statement;
• ...
• else
• statement;
switch
• switch (expression) {
• case value1:
• // statement sequence
• break;
• case value2:
• // statement sequence
• break;
• ...
• case valueN:
• // statement sequence
• break;
• default:
• // default statement sequence
• }
• The expression must be of type byte, short, int, or char;
• Each case value must be unique literal
• Value specified in case must be type compatible with the expression
Nested switch Statements

• switch(count) {
• case 1:
• switch(target) { // nested switch
• case 0:
• System.out.println("target is zero");
• break;
• case 1: // no conflicts with outer switch
• System.out.println("target is one");
• break;
• }
• break;
• case 2: // ...
Iteration Statements

• While:
• while(condition) {
• // body of loop
• }
• class NoBody {
• public static void main(String args[]) {
• int i, j;
• i = 100;
• j = 200;
• // find midpoint between i and j
• while(++i < --j) ; // no body in this loop
• System.out.println("Midpoint is " + i);
• }
• }
do-while
• do {
• // body of loop
• } while (condition);
• // Using a do-while to process a menu selection
• class Menu {
• public static void main(String args[])
• throws java.io.IOException {
• char choice;
• do {
• System.out.println("Help on:");
• System.out.println(" 1. if");
• System.out.println(" 2. switch");
• System.out.println(" 3. while");
• System.out.println(" 4. do-while");
• System.out.println(" 5. for\n");
• System.out.println("Choose one:");
• choice = (char) System.in.read();
• } while( choice < '1' || choice > '5');
• System.out.println("\n");
• switch(choice) {
• case '1':
• System.out.println("The if:\n");
• System.out.println("if(condition) statement;");
• System.out.println("else statement;");
• break;
• case '2':
• System.out.println("The switch:\n");
• System.out.println("switch(expression) {");
• System.out.println(" case constant:");
• System.out.println(" statement sequence");
• System.out.println(" break;");
• System.out.println(" // ...");
• System.out.println("}");
• break;
• case '3':
• System.out.println("The while:\n");
• System.out.println("while(condition) statement;");
• break;
• case '4':
• System.out.println("The do-while:\n");
• System.out.println("do {");
• System.out.println(" statement;");
• System.out.println("} while (condition);");
• break;
• case '5':
• System.out.println("The for:\n");
• System.out.print("for(init; condition; iteration)");
• System.out.println(" statement;");
• break;
• }
• }
• }
for

• for(initialization; condition; iteration) {


• // body
• }
• class Comma {
• public static void main(String args[]) {
• int a, b;
• for(a=1, b=4; a<b; a++, b--) {
• System.out.println("a = " + a);
• System.out.println("b = " + b);
• }
• }
• }
Some for Loop Variations

• boolean done = false;


• for(int i=1; !done; i++) {
• // ...
• if(interrupted()) done = true;
• }
• // Parts of the for loop can be empty.
• class ForVar {
• public static void main(String args[]) {
• int i;
• boolean done = false;
• i = 0;
• for( ; !done; ) {
• System.out.println("i is " + i);
• if(i == 10) done = true;
• i++;
• }
• }
• }
• for( ; ; ) {
• // ...
• }

• This loop will run forever, because there is


no condition under which it will terminate

• Nested Loops - concept


For –each statement
• This is introduced after JDK5
• For-each style of loop is designed to cycle
thro’ a collection of objects such as an
array in strictly sequential fashion, from
start to finish.
• General form
• for (type itr_var:collection) statement
block;
• type specifies datatype of itr_var.
• itr_var is name of iteration variable that will
receive the elements from a collection,
one at a time from begin to end.
• The collection being cycled thro’ is
specified as collection
• Various types of collection can be used.
But now we use simple collection called
array.
• With each iteration of the loop, the next
element in the collection is retrieved and
stored in iter variable. The loop repeats
until all elements in the collection are
obtained.
• type must be same or compatible with
elements stored in collection.
• For e.g. in array type should match woth
basetype.
• int nums[]={1,2,3,4,5,6,7,8,9,10};
• int sum=0; for(int i=0;i<10;i++)
sum+=nums[i];
• OR
• int nums[]={1,2,3,4,5,6,7,8,9,10};
• int sum=0;
• for(int x:nums) sum+=x;
• int nums[]={1,2,3,4,5,6,7,8,9,10};
• int sum=0;
• for(int x:nums) { System.out.println(x);
• sum+=x;}
• System.out.println(sum);
• Suppose if you change x in loop array is
unaffected
Iterating over multidimensional
arrays
• int nums[][]={{1,2,3},{3,4,5},{6,7,8}};
• for(int x[]:nums)
• for(int y:x) sum+=y;
Linear Search using for-each
• class Search{
• public static void main(String s[]){
• { int nums[]={6,7,5,9,10};
• int val=5; boolean found=false;
• for(int x:nums) {
• if(value==x) {found=true; break;}}
• if(found) System.out.println(“Elt is found”);
• }
• }
Jump Statements
• Using break to Exit a Loop:
• class BreakLoop {
• public static void main(String args[]) {
• for(int i=0; i<100; i++) {
• if(i == 10) break; // terminate loop if i is 10
• System.out.println("i: " + i);
• }
• System.out.println("Loop complete.");
• }
• }
• More than one break statement may
appear in a loop

• Too many break statements have the


tendency to destructure your code

• The break that terminates a switch


statement affects only that switch
statement and not any enclosing loops
Using break as a Form of Goto
• Java defines an expanded form of the
break statement

• By using this form of break, you can break


out of one or more blocks of code

• The general form of the labeled break


statement is :
• break label;
• A label is any valid Java identifier followed
by a colon

• You can use a labeled break statement to


exit from a set of nested blocks

• You cannot use break to transfer control


to a block of code that does not enclose
the break statement
• class Break {
• public static void main(String args[]) {
• boolean t = true;
• first: {
• second: {
• third: {
• System.out.println("Before the break.");
• if(t) break second; // break out of second block
• System.out.println("This won't execute");
• }
• System.out.println("This won't execute");
• }
• System.out.println("This is after second block.");
• }
• }
• }
• class BreakLoop4 {
• public static void main(String args[]) {
• outer: for(int i=0; i<3; i++) {
• System.out.print("Pass " + i + ": ");
• for(int j=0; j<100; j++) {
• if(j == 10) break outer; // exit both loops
• System.out.print(j + " ");
• }
• System.out.println("This will not print");
• }
• System.out.println("Loops complete.");
• }
• }
• // This program contains an error.
• class BreakErr {
• public static void main(String args[]) {
• one: for(int i=0; i<3; i++) {
• System.out.print("Pass " + i + ": ");
• }
• for(int j=0; j<100; j++) {
• if(j == 10) break one; // WRONG
• System.out.print(j + " ");
• }
• }
• }
Using continue
• class Continue {
• public static void main(String args[]) {
• for(int i=0; i<10; i++) {
• System.out.print(i + " ");
• if (i%2 == 0) continue;
• System.out.println("");
• }
• }
• }
• As with the break statement, continue may specify a label
to describe which enclosing loop to continue

• class ContinueLabel {
• public static void main(String args[]) {
• outer: for (int i=0; i<10; i++) {
• for(int j=0; j<10; j++) {
• if(j > i) {
• System.out.println();
• continue outer;
• }
• System.out.print(" " + (i * j));
• }
• }
• System.out.println();
• }
• }
Output:
• 0
• 01
• 024
• 0369
• 0 4 8 12 16
• 0 5 10 15 20 25
• 0 6 12 18 24 30 36
• 0 7 14 21 28 35 42 49
• 0 8 16 24 32 40 48 56 64
• 0 9 18 27 36 45 54 63 72 81
return
• Used to explicitly return from a method

• The return statement immediately terminates the


method in which it is executed

• class Return {
• public static void main(String args[]) {
• boolean t = true;
• System.out.println("Before the return.");
• if(t==true) return; // return to caller
• System.out.println("This won't execute.");
• }}

• return causes execution to return to
the Java run-time system, since it is the
run-time system that calls main( )

You might also like