Java Statements II

I started discussion on Java statements in my last post where I explained (i) the importance of Statements using algorithmic steps, (ii) classified the statements we have in Java and (iii) listed out the different types of statements in each category, click here if you missed it. In this post, I will continue the tutorial on these statements and also share sample codes on each of them, their syntax and the output of the sample codes. I hope by the end of this post you would have full understanding of Java Statement and will be able to make use of them appropriately when writing your own code.

Control Flow Statement

  • If statements

Syntax:

  • if(expession){
  • statement;
  • }

If statement checks for the validity of a condition and execute a set of code based on this. This statement only makes provision for what happens when the condition tested is true and could care less about when the condition is tested to be false. See sample code below:

IfStmt

On line 17 of the sample code, if “x is equal to 1”  returns true then the compiler moves to line 18 and prints out “The value of x is one” but if the condition is false line 18 is never executed.

  • If then else statements

Syntax:

  • if(expession){
  •              statement;
  • }else{
  • }

This is similar to If statement except that it makes provision for when the condition tested is true or false. See sample code below:

IfElse

When condition tested on line 17 is true, line 18 is executed and when the condition tested is false, line 20 is executed instead. The If Else statement can also allow for multiple conditions to be tested by adding an if condition to every else -see example on line 19 of the sample code below

 IfElse2

  •  Switch statements

Syntax:

  • switch(expession){
  •           case value: statement
  •                                 break;
  •           case value: statement
  •                                 break;
  •          default:
  •                                 break;
  • }

Switch statement makes it easy to check multiple cases and execute codes based on the condition. It is a good substitute for multiple If Else condition. See sample code below

switch

Output:

  • The while statements

Syntax:

  • while(expession){
  • statement;
  • }

The while statement continues executing some statements while a condition remains true. The while statements checks for the validity of the specified condition before executing the statement.

while

On line 16, value of “i”  is checked to confirm it is less than 10 , if this is tested true then line 17 and 18 are executed else line 17 and 18 are never executed. On line 18 the value of “i” is incremented before the check is conducted again, see previous post on Java operators. The code above will not execute line 17 and 18 because “i” is not less than 10, hence nothing will be printed on the output panel.

Output:

whileOutput

  • Do – while statements

Syntax:

  • do{
  • statement;
  • }while(expression)

The Do-While works just like While statement, the only difference is that the action will always be executed at least once as Do comes before the while check. We can see “While” as a preventive statement and do-while as a corrective statement, however, they both are very useful depending on what a programmer want to achieve.

dowhile

Output

doWhileOutput

  • For statement

Syntax:

  • for (initialization; termination; increment/decrement){
  • statements;
  • }

The “for statement” also repeat a set of statement for as long as a condition remains true. This is achieved by initializing a loop variable, checking for its termination and increment or decrement the variable.

forStatemnt

 Output

forOutput

Branching Statements:

  • Return Statement

Syntax

return returntype;

Return statement is used to terminate the execution of a method and return to the parent method calling the method. Every method created in java must have a pre-defined return type, return type is the value in between the access modifier and the method name, see previous post on method here. A return statement can also go back to the calling method with an output depending on the pre-defined output type of the method (i.e. not void).

returnStatement

When a method is defined with a void return type as seen on line 21 (SayHello method), the method does not necessarily require an explicit return statement hence the reason why a warning is flagged on line 23 (Unnecessary return Statement) however, if a method is defined with any other data type or Object as its return type a return statement must be added else the code will not compile. See sample code below, an error is flagged on line 28 because the method is expecting a return statement however, sayHello method warning sign is no longer there since the unnecessary statement has been removed.

returnMissing

  • Break statement

Syntax

break;

The break statement is similar in function to Continue except that while Continue only skips a part of a loop when continue is called, the break statement exists the loop totally.  Let’s replace the Continue statement with break statement and see what our output looks like as shown below

 breakStatement

When the code above runs, the output below is generated as the loop terminates at the point where break statement is called when i is equal to five.

breakOutput

  • Continue

Syntax

Continue;

Continue statement is used to skip a part of a loop. It is similar to Break statement except that while Continue only skips a part of a loop, the break statement exists the loop totally. It is used mainly when there are some exclusions to a condition. E.g Say you want to give every child below ten years a gift except any child whose age is five. Continue works in a way that when the executor gets to age 5, it skips the gift part and moves to the next age. See sample code and output below.

continue

Output: When the code above executes, the output shows that when “i” is 5 the action is skipped.

ContinueOutput

  •  Expression statement

An expression move value around and performs operation on them. An expression statement is derived when an expression is terminated by semi colon. As listed in my last post, any statement that belongs to any of the four groups below can be categorized as expression statement.

  • Assignment expressions
  • Any use of ++ or —
  • Method invocations
  • Class Initialization or Object creation expressions

 expStatement.PNG

  Line 16==>Assignment statement

Line 18==> Increment Operator

Line 20==> Class ExpressionStatement Initialization or object expStatemt creation

Line 22è==>Method testMethod invocation.

In summary,

Statement Type When is it used?
If statement checks for the validity of a condition and execute a set of code based on this
If then else statements Used when a condition to be tested is either true or false
Switch statements Used when expressions to be checked are based only on a single integer, enumerated value, or String object.
The while statements Used to check for the validity of the specified condition before executing the statement
For statement Used to iterate over a range of values
Return Statement used to terminate the execution of a method and return to the parent method calling the method
Break statement Used to come out of the loop control statements.
Continue Used to skip the part of loop

 With this, we have come to the end of Java statement. Please take time out to practice and remember to get back to me should you have any question. Happy Coding!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s