Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.
Java allows usage of different control statements which act as conditional or unconditional according to their usage within a program. The control activates in two modes featuring, Selection and Iteration. Hence the control statements of Java are referred to of two types : (i )Selection / Decision control statements : The Selection control statements refer to transfer of control or execution depending on the given condition and a selection is made depending on the given options. The different course of action are performed according to the given condition. They are also termed as Decision Construct Statements as they help in taking decisions for further execution of the statements/instructions within the program. (ii )Iteration/looping control statements : The Iteration Statements on the other hand act as an automatic looping statements. Here the block/compound statement is executed again and again until a given condition is met.
SELECTION STATEMENTS OF java The Java if statement is used to test the condition. It checks Boolean condition: true or false. There are various types of if statement in java. if if-else if-else-if nested if statement statement ladder statement
Java IF Statement The Java if statement tests the condition. It executes the if block if condition is true. Syntax: if(condition) //code to be executed
public class IfExample public static void main(string[] args) int age=20; if(age>18) System.out.print( You are eligible to vote");
tooltiptext property The tooltip text is the text that appears when The tooltip text is the text that appears when the user moves the cursor over a component, without clicking it. private void jbutton1actionperformed(java.awt.event.actionevent evt) // Code to check eligibility to vote: if (Integer.parseInt(jTextField1.getText())>=18) JOptionPane.showMessageDialog(null,"You are eligible To VOTE");
Java IF-else Statement The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed. Syntax: if(condition) //code if condition is true else //code if condition is false
private void jbutton1actionperformed(java.awt.event.actionevent evt) // Code to check eligibility to vote with else condition: if (Integer.parseInt(jTextField1.getText())>=18) JOptionPane.showMessageDialog(null,"You are eligible To VOTE"); else JOptionPane.showMessageDialog(null,"You are NOT eligible To VOTE");
public class IfElseExample public static void main(string[] args) int number=13; if(number%2==1) System.out.println( ODD number"); else System.out.println( EVEN number");
import javax.swing.joptionpane; private void jbutton1actionperformed(java.awt.event.actionevent evt) // Code to check eligibility for scholarship: if (Integer.parseInt(jTextField1.getText())>=75) jtextarea1.settext("congratulation!\nyou Get the SCHOLARSHIP!!"); else jtextarea1.settext("work Hard!\n" + "Make sure that you Get the SCHOLARSHIP in the next Exam!!");
private void jbutton2actionperformed(java.awt.event.actionevent evt) JOptionPane.showMessageDialog(null,"thanks for using This app"); System.exit(0); // to terminate the application
Java IF-else-if ladder Statement The if-else-if ladder statement executes one condition from multiple statements. Syntax: if(condition1) //code to be executed if condition1 is true else if(condition2) //code to be executed if condition2 is true else if(condition3) //code to be executed if condition3 is true... else //code to be executed if all the conditions are false
private void jbutton1actionperformed(java.awt.event.actionevent evt) // To find the day of the week if (jradiobutton1.isselected()) jtextfield1.settext("monday"); else if (jradiobutton2.isselected()) jtextfield1.settext("tuesday"); else if (jradiobutton3.isselected()) jtextfield1.settext("wednesday"); else if (jradiobutton4.isselected()) jtextfield1.settext("thursday"); else if (jradiobutton5.isselected()) jtextfield1.settext("friday"); else if (jradiobutton6.isselected()) jtextfield1.settext("saturday"); else if (jradiobutton7.isselected()) jtextfield1.settext("sunday"); else jtextfield1.settext("day - Not Selected");
public class IfElseIfExample public static void main(string[] args) int marks=65; if(marks<50) System.out.println("fail"); else if((marks>=50 )&& (marks<60)) System.out.println("D grade"); else if(marks>=60 && marks<70) System.out.println("C grade"); else if(marks>=70 && marks<80) System.out.println("B grade"); else if(marks>=80 && marks<90) System.out.println("A grade"); else if(marks>=90 && marks<100) System.out.println("A+ grade"); else System.out.println("Invalid!");
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. switch(expression) case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional... default: code to be executed if all cases are not matched;
public class SwitchExample public static void main(string[] args) int number=20; switch(number) case 10: System.out.println("10") ; break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; default : System.out.println("Not in 10, 20 or 30");
import java.util.scanner; class OddOrEven public static void main(string args[]) int x; System.out.println("Enter an integer to check if it is odd or even "); Scanner a = new Scanner(System.in); x = a.nextint(); if ( x % 2 == 0 ) System.out.println("You entered an even number."); else System.out.println("You entered an odd number.");
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextline() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextline() positions the cursor in the next line. for reading the entire line you can use nextline()
import java.util.scanner; class MaxNum public static void main(string args[]) int x, y, z,max; System.out.println("Enter three integers "); Scanner in = new Scanner(System.in); x = in.nextint(); y = in.nextint(); z = in.nextint(); max=x; if(y>max) max=y; if(z>max) max=z; System.out.println("maximum is = "+max); /* if ( x > y && x > z ) System.out.println("First number is largest."); else if ( y > x && y > z ) System.out.println("Second number is largest."); else if ( z > x && z > y ) System.out.println("Third number is largest."); else System.out.println("Entered numbers are not distinct.");*/
TOTAL_AMMOUNT DIS MORE THAN 30000 15% LESS THAN OR EQUAL TO 30000 BUT > 15000 10% BETWEEN 10000 AND 15000 5% OTHERWISE NIL
A loop statement allows us to execute a statement or group of statements multiple times.
Sr. No. 1 2 3 Loop & Description while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loop Like a while statement, except that it tests the condition at the end of the loop body.
The syntax of a while loop is while(boolean_expression) // Statements // updation public class Test public static void main(string args[]) int x = 1,s=0; while( x < =10) s+=x; //s=s+x; x=x+1; // ++x or x++ System.out.print(" sum=" + s );
for(initialization; Boolean_expression; update) // Statements Here is the flow of control in a for loop The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;). Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop. After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
public class Test public static void main(string args[]) for(int x = 10; x < 20; x = x + 1) System.out.print("value of x : " + x ); System.out.print("\n");
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax Following is the syntax of a do...while loop do // Statements while(boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the control jumps back up to do statement, and the statements in the loop execute again. This process repeats until the Boolean expression is false.
public class Test public static void main(string args[]) int x = 10; do System.out.print("value of x : " + x ); x++; System.out.print("\n"); while( x < 20 );
Enhanced for loop in Java Syntax Following is the syntax of enhanced for loop for(declaration : expression) // Statements
public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) System.out.print( x ); System.out.print(","); System.out.print("\n"); String [] names = "James", "Larry", "Tom", "Lacy"; for( String n : names ) System.out.print( n ); System.out.print(","); 10, 20, 30, 40, 50, James, Larry, Tom, Lacy,
Control Statement & Description break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. OR The break statement in Java programming language has the following two usages 1. When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. 2. It can be used to terminate a case in the switch statement (covered in the next chapter).
public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) if( x == 30 ) break; System.out.print( x ); System.out.print("\n");
Control Statement & Description continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement. In a while loop or do/while loop, control immediately jumps to the Boolean expression.
public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int x : numbers ) if( x == 30 ) continue; System.out.print( x ); System.out.print("\n");
public class Test public static void main(string args[]) int [] numbers = 10, 20, 30, 40, 50; for(int i=0;i<numbers.length;i++) if( numbers[i] == 30 ) continue; System.out.print( numbers[i] ); System.out.print("\n");