Saturday, 2 February 2013

Introduction to Control Statements in Java


Control statements decide flow of a program

JAVA CONTROL STATEMENTS

if, if-else, switch, nested if, switch, for, while, do-while, break, continue and return control statements


Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program. The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
In Java, control statements can be divided under the following three categories:



  1. Selection statements
  2. Iteration statements or Repetition Statements
  3. Jump statements or Branching Statements


1. SELECTION STATEMENTS

Selection statements are used in a program to choose different paths of execution based upon the outcome of an expression or the state of a variable.
  • if and if...else
  • Nested if Statements
  • Using switch Statements


2. ITERATION STATEMENTS OR REPETITION STATEMENTS


It is essential that a program be able to execute the same set of instructions many times: otherwise a computer would do only as much work as a programmer! Repeating the same code fragment several times is called iterating. Java provides three iteration control statements

  • For Loop
  • While Loop
  • Do-while Loop


3. JUMP STATEMENTS OR BRANCHING STATEMENTS

Jump statements are used to unconditionally transfer the program control to another part of the program.
  • Break
  • Continue
  • Return
The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. The while and do-while statements continually execute a block of statements while a particular condition is true. The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once. The for statement provides a compact way to iterate over a range of values. It has two forms, one of which was designed for looping through collections and arrays.

No comments :

Post a comment