0% found this document useful (0 votes)
20 views8 pages

Java Control Statements Explained

The document discusses Java control statements which allow a program's execution to be diverted from its normal sequential flow. It describes different types of control statements including selection statements like if/else which choose between execution paths, and looping statements like while and for which repeatedly execute blocks of code. It also covers structured and unstructured control statements, with structured statements like if/else having a single entry and exit point.

Uploaded by

marye agegn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views8 pages

Java Control Statements Explained

The document discusses Java control statements which allow a program's execution to be diverted from its normal sequential flow. It describes different types of control statements including selection statements like if/else which choose between execution paths, and looping statements like while and for which repeatedly execute blocks of code. It also covers structured and unstructured control statements, with structured statements like if/else having a single entry and exit point.

Uploaded by

marye agegn
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA CONTROL STATEMENTS

An execution path is a sequence of statements that the computer executes as it runs a program. A
control statement tells the computer to divert onto a different path. If a program has no control
statements, the JVM executes it, statement by statement, in sequential order. Often programmers
refer to an execution path as a flow of control.

Example
This application has one execution path through lines 7, 8, 9 and 10.

1 import static [Link].*;


2
3 public class HowOldAreYou
4 {
5 public static void main( String args [ ] )
6 {
7 String prompt = "How old are you?";
8 String age = showInputDialog( prompt );
9 String output = "You are " + age + " years old.";
10 showMessageDialog( null, output );
11 }
12 }

The application uses an input dialog to read the user’s age and an output dialog to display it.

Java Control Statements Page 1


Method Call
A method call is considered a control statement because it diverts the flow of control to the
method’s block, even though it doesn’t introduce any additional paths in the program.

Example
By following one execution path through lines 5, 13, 6, 13, 7, 18, 8 and 13, the application below
outputs:
Happy birthday to you
Happy birthday to you
Happy birthday dear, Tom
Happy birthday to you

1 public class HappyBirthday


2 {
3 public static void main( String args [ ] )
4 {
5 printTo( );
6 printTo( );
7 printDear( "Tom" );
8 printTo( );
9 }
10
11 static void printTo( )
12 {
13 [Link]( "Happy birthday to you" );
14 }
15
16 static void printDear( String name )
17 {
18 [Link]( "Happy birthday dear, " + name );
19 }
20 }

Java Control Statements Page 2


Loops
A major category of control statements are the loops, which repeatedly execute a group of
statements some number of times.

Example
The following code shows a while statement, which repeatedly executes lines 2, 4 and 5,
stopping when c equals 3 (making c < 3 false). Its output is:

c = 1
c = 2
c = 3

1 int c = 0;
2 while ( c < 3 )
3 {
4 c++;
5 [Link]( "c = " + c );
6 }

Here's a list of Java's loops.

Loop Behavior
while repeat statements 0 or more times until some truth value is false
do-while repeat statements 1 or more times until some truth value is false
for repeat statements and an update clause until some truth value is false

Java Control Statements Page 3


Selection Statements
Another major category of control statements are the selection statements, which choose
between groups of statements, deciding which group to execute.

Example
The if statement, shown on lines 2‒9 below, introduces a second execution path into the code.
If the value of age is 21 or more, the computer executes lines 1, 2, 4 and 10. If age is less than
21, the computer executes lines 1, 2, 8 and 10.

1 [Link]( "You " );


2 if ( age >= 21 )
3 {
4 [Link]( "can " );
5 }
6 else
7 {
8 [Link]( "can't " );
9 }
10 [Link]( "purchase liquor!" );

Here's a list of Java's selection statements.

Selection
Behavior
Statement
if choose whether or not to execute a group of statements
if-else choose one of two groups of statements to execute
switch branch to a match point and begin executing from there

Java Control Statements Page 4


Structured Control Statements
You can look at a loop or selection statement in your program and pretty much tell at which
points the flow of control enters and exits it. Some programmers refer to them as being
structured; others say that they have one entrance and one exit.

Example
Assuming there are no unstructured control statements between lines 2 and 55, execution enters
this while loop at line 1 when x is positive and exits at line 1 when x equals 0, after which it
proceeds to line 56.

1 while ( x > 0 )
2 {
~ . . .
55 }
56

Java Control Statements Page 5


Unstructured Control Statements
Java has several statements that allow you to create more than one exit in your control structures,
which earns them the title of unstructured control statements. Here's a list.

Unstructured
Control Behavior (roughly described)
Statement
break stop what you're doing and continue after the current loop
continue stop what you're doing and continue with the next loop cycle
return stop what you're doing and go back to calling method
throw stop what you're doing and generate a run-time exception

Example
This loop has two exits: (1) From line 1 to line 56 when x equals 0. (2) From line 31 to line 56 if
y equals 100.

1 while ( x > 0 )
2 {
~ . . .
31 if ( y == 100 ) break;
~ . . .
55 }
56

Java Control Statements Page 6


Structured Programming
In 1966, Corrado Böhm and Giuseppe Jacopini published a paper
showing that any computer program containing unstructured control
statements can be transformed into an equivalent program using only
structured control statements. Specifically, any unstructured control
statement can be replaced by combinations of the while and if-else
statements.1

Corrado Böhm
Of course, just because you can use only two control structures doesn't
mean that you should do so. Thus, during the decade following Böhm's
and Jacopini's paper, computer programmers argued the meaning and merits of structured
programming – What exactly is it? How do you do it? Why should you do it?

Most of this debate has been made irrelevant by the variety of control statements in modern-day
programming languages. However, the essential idea of structured programming survives –
although a conscientious computer programmer strives to use structured control statements and
one-entrance-one-exit code, he or she gives preference to code that (1) is clear to the human
reader and (2) reflects the structure of the problem being solved.

Example
We want an application that asks the user multiplication questions – what’s 2 X 3, what’s 5 X 4,
etc. The program must print a question, read the user’s answer and check it. If correct, the
program must give the user a point and encourage him or her to continue. If the answer is wrong,
the program must quit. The user can also signal that he or she wishes to quit by entering -1 for
the answer. The complete application is shown below.

The looping construct is not, in the strictest sense, “structured” because it has two exits (from
lines 24 and 29) neither of which occurs from line 38, which is where the exit ordinarily should
be. Nevertheless, the code clearly expresses the intent of the programmer and the flow of control
closely resembles the interaction required by the situation.
1 import [Link];
2
3 public class TimesDrill
4 {
5 public static void main( String args [ ] )

1
Böhm and Jacopini, “Flow diagrams, Turing machines and languages with only two formation
rules,” Communications of the ACM, 9:5 (May 1966), pages 366-371.

Java Control Statements Page 7


6 {
7 int a, b; // times operands
8 int ansR; // right answer
9 int ansU; // user's answer
10 int score; // user's score
11 String s; // output string
12 Scanner scanner = new Scanner( [Link] );
13 [Link]( "Practice multiplication" );
14 [Link]( "To quit, enter -1" );
15 score = 0; // initialize score
16 do
17 { // generate question
18 a = (int)( [Link]( )*11 );
19 b = (int)( [Link]( )*11 );
20 s = a + " X " + b + " = ";
21 [Link]( s + "? " );
22 ansR = a * b; // compute right answer
23 ansU = [Link]( ); // get user's answer
24 if ( ansU == -1 ) // user wants to quit
25 {
26 [Link]( "Goodbye" );
27 break; // quit
28 }
29 if ( ansU != ansR ) // user answered wrong
30 {
31 [Link]( "Sorry, " + s + ansR );
32 break; // quit
33 }
34 // user entered a correct answer so add one to
35 // score and encourage continuing
36 score++;
37 [Link](score+" right. Keep going!");
38 } while ( true );
39 }
40 }

Java Control Statements Page 8

Common questions

Powered by AI

Loops in Java, including 'while', 'do-while', and 'for', repeatedly execute a block of statements until a specified condition is false, providing controlled repetition within programs. They differ from selection statements, like 'if' and 'switch', which choose between different sets of statements to execute based on conditions. While loops emphasize repeated execution, selection statements focus on branching execution paths depending on conditions .

Structured control statements in Java, such as loops and selection statements, clearly define their entry and exit points within a program. For example, a while loop starts execution when a condition is met and exits once the loop's condition is no longer true. This one-entrance-one-exit structure allows programmers to easily predict and trace the flow of control through the code, enhancing readability and maintainability .

In Java, an 'if' statement evaluates a condition and executes a block of statements only if the condition is true. An 'if-else' statement provides two execution paths: one for when the condition is true and another for when it's false. The 'switch' statement provides multiple branches to choose from, typically used when a variable is compared against multiple constant values. While 'if-else' can handle complex conditions, 'switch' is generally more readable for scenarios with many specific known values, reducing the need for multiple conditional checks .

Programmers can ensure clear and structured code by utilizing structured control statements such as loops and selection statements that have one clear entry and exit point. They should avoid overusing unstructured statements like 'break' and 'continue' that may obscure the flow of control. Additionally, aligning the logical flow of code with the problem's structure and providing clear comments on the intended flow can help enhance code readability. Organizing complex conditions logically and breaking down large methods into smaller, focused methods also maintains clarity and structure .

A 'do-while' loop in Java differs from a 'while' loop in that it guarantees the execution of the loop body at least once before the condition is checked. The 'do-while' loop checks its terminating condition at the end of the loop rather than at the beginning, as is the case with 'while' loops. It is preferred when you want to ensure that the code block is executed at least once regardless of the condition, for instance, when the loop's body initializes variables needed to evaluate the condition .

Method calls in Java are considered control statements because they divert program flow to the method block being called, leading to execution of the sequence of statements within that method before returning to the calling point. This diversion introduces a form of control where execution is paused at the call point and resumed after the method completes, thereby influencing the flow of control without introducing new conditional paths per se .

Corrado Böhm and Giuseppe Jacopini's findings, published in 1966, demonstrated that any program using unstructured control statements could be converted to use only structured statements like 'while' and 'if-else'. This paved the way for structured programming, which emphasizes clarity, simplicity, and reliability in writing code. While modern programming languages offer a variety of control statements, the principles articulated by Böhm and Jacopini remain relevant as they highlight the benefits of predictable and clear code that mirrors the logical structure of the problem being solved, fostering better programming practices .

Execution paths in Java refer to the sequence of statements a program executes as it runs. Control statements alter this flow by introducing new paths based on conditions or loops. Without control statements, the Java Virtual Machine executes program statements sequentially. Control statements, such as 'if', 'while', and method calls, can divert or loop execution through different parts of the code, drastically impacting the flow by determining which code segments are executed and how often .

Structured programming, as introduced by Corrado Böhm and Giuseppe Jacopini, emphasizes the use of structured control statements like 'while' and 'if-else' for clear and understandable code, avoiding multiple exit and entry points typical of unstructured control statements like 'break' or 'continue'. Structured programming aims to make code reflect the structure of the problem being solved, enhancing readability and maintainability. Despite the capability to convert unstructured statements into structured equivalents, the use of structured programming principles is favored for their clarity and the one-entrance-one-exit methodology .

Unstructured control statements like 'break' and 'continue' introduce additional exit points within loops or switch cases, making the flow of control less predictable and more difficult to trace. 'Break' can abruptly exit a loop or switch, while 'continue' skips the current iteration and begins the next cycle of a loop. These statements can disrupt the linearity and clarity of structured programming, potentially leading to unexpected behavior if not carefully managed .

You might also like