Comprog - Java Chap 4
Comprog - Java Chap 4
CONTROL STRUCTURES
BRANCHING STATEMENTS
Branching Statements or Decision-Making Statements describes
how to use operators in expressions (expression consist of
operand and operator and/or constant value) in your code and
how those expressions in decision-making statements allows the
programmers to select specific sections of code to be executed.
The if Construct
Syntax:
if (boolean_expression)
{
code_block;
}// end of if construct
False
Condition
True
True Action
Syntax:
if (boolean_expression)
{
code_block;
}// end of if construct
else
{
code_block;
}// end of else construct
False True
Condition
Syntax:
if (boolean_expression)
{
code_block1;
}// end of if construct
else if (boolean_expression)
{
code_block2;
}// end of else if construct
else
{
code_block3;
}// end of else construct
Y
Condition 1 Action 1
N
Y
Condition 2 Action 2
N
Y
Condition 2 Action 3
N
Action N
If-Statement
Example.
If (sexCode = ‘M’){
System.out.println(“Male”);
}
If-Else Statement
Example.
Example.
if (grade == ‘A’)
{
System.out.println(“OUTSTANDING!);
}
else if (grade == ‘B’)
{
System.out.println(“VERY GOOD!);
}
else if (grade == ‘C’)
{
System.out.println(“GOOD!);
}
else if (grade == ‘D’)
{
System.out.println(“STUDY HARD!);
}
else
{
System.out.println(“Invalid code!”);
}
}
}
Syntax:
switch (variable)
{
case literal_value:
code_block;
[break;]
case another literal_value;
code_block;
[break;]
[default:]
code_block;
}
JAVA PROGRAMMING-CHAPTER 4
Flowchart switch-statement
Y Action 1
Case 1 Break
N
Y Action 2
Case 2 Break
N
Y Action 3
Case 2 Break
N
Default Block
Examples #3.
Name: Rating:
LOOPING STATEMENTS
while (boolean_expression){
code_block;
}// end of while construct
Example.
int ctr = 0;
while (i < 5){
System.out.println(ctr);
++ ctr;
}
JAVA PROGRAMMING-CHAPTER 4
int colCount = 0;
int rowCount = 0;
Name: Rating:
Problem 2 & 3. Make the same square image like what you did
in WhileSquare.java, this time, develop a class by using:
Name: Rating:
Examples:
Break_Ex1.java
Sample Output
The value is : 0
The value is : 1
The value is : 2
Sample Output
The value is : 0
The value is : 1
The value is : 2
The value is : 3
The value is : 4
JAVA PROGRAMMING-CHAPTER 4
continue;
When the value of [i] becomes more than 4 and less than
9, continue statement is executed, which skips the execution
of System.out.println(i); statement.
1
2
3
4
9
10
JAVA PROGRAMMING-CHAPTER 4
Any method declared void doesn't return a value. It does not need
to contain a return statement, but it may do so. In such a case,
a return statement can be used to branch out of a control flow
block and exit the method and is simply used like this:
return;
Syntax:
return returnValue;
The data type of the return value must match the method's
declared return type; you can't return an integer value from a
method declared to return a boolean.
Name: Rating: