Sitemap

JAVA PART-4 (STATEMENTS)

13 min readAug 1, 2018

--

Java statements

Statements in Java are equivalent to sentences in natural languages. Its a complete unit of execution. “;” indicates the end of the statement. When you declare a variable , as you have seen before , it also ends with “;” , meaning that was also a statement. Simply put , any line of code that has to be executed is a statement. It may include variable, constant , operator or an expression. Expressions includes assignment expressions , any use of ++ or — — , method calls , object creation expression.

Another term you might want to know is CODE BLOCK , it is a group of two or more statements between balanced / curly braces “{ and }”. It is a single logical unit that can be used anywhere.

Statements can broadly be classified into two types DECLARATIVE STATEMENTS and CONTROL STATEMENTS. Declarative Statements declares variables. Control statements regulates the flow of execution of statements based on the changes to the state of program.

CONTROL STATEMENTS

Control statements are further classified into 4 types Selection Statements, Iteration statements , Jump statements, Exception handling.

SELECTION STATEMENTS:

Includes two types “if-else and switch-case” . These statements allow you to control the flow of execution based upon the conditions known ONLY during RUNTIME.

If / else statements:

In this the programmer can execute the program based upon the given conditions. Code will execute if the condition is true.

Syntax :

if (expression i.e., condition ){   Statements;}

Example: Single statement execution: with 1 line of code /statement

if (x >y )    System.out.println(“x is greater “ );if (x<y)    System.out.println(“y is greater “);if(x==y)    System.out.println(“both are equal”);

NOTE: You might have noticed that I have not written the statement inbetween the curly braces { } , but instead have indented the statement line. This is ok if only single statement is written within the if case , else if more than one line or statements are to be written then { } must be used . Example,

If ( x > y ){   String name =” hello “;   System.out.println(“ x is greater “ + name );}

The same example can be written using if / else statements :

Syntax:

If (condition){    Statements ;} else if (condition ){    Statements;} //if both the above if conditions were false then execute this
else{
Statements;}

Example:

if (x >y ){    System.out.println(“x is greater “ );}else if (x<y){    System.out.println(“y is greater “);}else {    System.out.println(“both are equal”);}

NOTE: System.out.println is used to print the output to the console (screen).

The ?: operator:

This ternary operator can be used in if / else conditional statements , when the result is to be returned based upon one conditions.

Syntax:

Conditional expression ? expression1 : expression2 ;

If conditional expression is true , return expression1 else return expression2 if its false.

Example:

If (x <=10)   Commission = 10*x;else   Commission = 15 *x;// this can be written asCommission = (x <=10 ) ? (10 * x) : (15 * x );

SWITCH STATEMENTS

For multiple decision statements , we use switch case .

Syntax:

switch( variable or expression ){case 1 : //do something ;         break ;case 2 : // do something ;         break;.. }

Example:

int num = 2;switch ( num ){   case 1: System.out.println( “ first”);           break;   case  2: System.out.println(“second”);           break;   case  3: System.out.println(“third”);           break;}// here the output will be second as the value of num is 2.

NOTE: the above cases could also be written using if /else statements but it become very lengthy and repetitive, in order to make it less recurrent we use switch case. Also its easy to maintain when too many conditions have to checked to give an output.

NOTE: Noticed the usage of “break “ after each switch case , that’s to terminate the switch case flow through as soon as the condition is met.

Under the hood , what happens is , when the switch case begins it execution , it first will check the value of “num” , then will check which of the cases match that value . In case of , switch case 2 , it matches the value of num i.e., 2 , so its true , now the statements under this case will be executed and print second. “break ; “ statement is used to terminate the switch case flow and come out of the switch-case after the execution of case 2.

NOTE: You may use any conditional statements within the switch cases too.

ITERATIVE STATEMENTS

Includes while , do-while and for statements. These statements enable us to run a loop i.e., perform a task for a number of times as long as the termination condition is met. That is , repeatedly execute the block code until the termination condition is met.

1. while statements

It repeatedly executes the block code , or keep on performing the given task , provided the condition remains “TRUE”. Meaning, as soon as the condition becomes “FALSE” it stops executing.

Syntax:

while ( expression ) {   //body of loop  //statements;}

Example: write table of 6

int count =1;int product ;System.out.println(“ Table of 6 “ );while (count <=10 )  // count is less than or equal to 10{   product  = 6 * count ;   System.out.println(“ 6 X  “ + count + “=  “ + product );   count ++;}OUTPUT:Table of 66 X 1 = 66 X 2 = 126 X 3 = 186 X 4 = 246 X 5 = 306 X 6 = 366 X 7 = 426 X 8 = 486 X 9 = 546 X 10 = 60

NOTE: In the statement ,System.out.println(“ 6 X “ + count + “ = “ + product ); , we have to use “+” concatenation operator to connect the strings together and to add the variable value to the string.

2. do -while statements

In the case of while loop , it executes only when the condition is true , but what if you want to execute the block code at least once , even if the condition is not met! In such , cases we use do — while loop , its almost the same as the while loop , the only difference is that the condition is written in the bottom , and the loop executes at least once no matter what!! In this case too , it stops to execute if the condition becomes “false”.

Syntax:

do {   //body of loop   //statements} while ( expression / condition ) ;

Example: the same table for 6 can also be written using do while loop

int count =1 ;int product ;do {   product = 6 * count ;   System.out.println(“ 6 X  “ + count + “ =  “ + product );   count ++;} while ( count <= 10); //till count is not more than 10

Example : to show that the loop runs at least once

int val = 0;int val1;do {   val1 = val +1;   System.out.println( “ Value Is “ + val1 );} while ( val > 0 );  // condition to start the while loopOutput :Value is 1

3. for statements

The above two loops are usually used when no definite termination point is known , i.e., it may vary from situation to situation as long as the condition is met , say instead of giving the limit to be 10 , we could have just made it such that the loop runs as long as the value is not prime or not divisible by some number etc, which is bothersome to calculate and then state it as the condition. .Thus making our task easy.

Get shaistha fathima’s stories in your inbox

Join Medium for free to get updates from this writer.

Whereas, for loop is used to iterate over a range of values , usually used over arrays or strings . To read or write strings or arrays.

Now , if you are familiar with c programming language , there was no data type called “String” in C , we used to create one using an array , that has been made easy here in Java thanks to string literals. I will discus about arrays in detail in the next post , but for now you may just look at it as , block of the memory boxes that contains certain value of same data type , whereas string can have values of different data types put together in one such as numbers , letters,etc.

Like I said for loops can be used to read or write an array or strings. For Example , iterating over the array of numbers and print it out !!

Syntax:

for ( initialization ; termination ; increment ){  // body statements ;}

(i) initialization : expression / condition to start the loop . It executes ONLY ONCE at the beginning of the loop.

(ii) termination : expression / condition to end/terminate the loop. This is evaluated every time the loop has to iterate , and if the expression evaluates to be “false” the loop terminates.

(iii) Increment : invoked after each iteration , gives the value by which the expression has to be incremented after each loop. Is optional , loop will run even if its not mentioned .

NOTE : All of these may have more than one expressions each , separated by “ , “ .

Example:

int[]  num = { 10,20,30,40,50,60,70,80,90,100 } ;System.out.print(“ The numbers are :  “);for ( int i = 0 ; i < num.length ; i++){    System.out.print(num[i] + “  “ );}
...
OUTPUT :The numbers are : 10 20 30 40 50 60 70 80 90 100

EXPLANATION :

1. Declared and assigned values to an int type array , num .

2. For the for loop , first declare a local variable i , ie., valid only under the given block code and cannot be used outside of the for loop block code .

3. We need “ i “ to show , where to start the iteration from , in this case it begins from 0 because , in an array the numbering starts from 0 and goes like 0 1 2 3 ….

4. Next , set the termination condition to as long as the array extends ,i.e, till the end of array. But , here we need to give the exact number , so we use ” length “ inbuilt method of the Java , which returns the length of the array of string , i.e., total no. of elements present in it . In our example that would be 10 , so it will run until i = 9 and no more.

5. Next, is the count by which we want to increment “ i “ to run the loop , in this case we will increase it by one , as we want to print each of the elements present in the array. In case , you are wondering what if I want to print leaving one element in the middle each time , then , we would have incremented “ i “ by 2 instead.

6. Now , look at the loop statement printing the values the following observations can be made :

(i) Don’t know if you have noticed or not but unlike the previous print statements I have used “print” instead of “println”. Reason , “println” automatically moves the next line without having to write ‘\n’ in the end , if you remember from my previous post or from C programming , ‘\n’ , is an escape sequence used to move to next line. In case of “println” Its automatically added while its execution. And because I wanted to write all the numbers in one line , I have used “print” instead of “println”.

(ii) This you may understand better in my next post, but for now , num [ i] , gives the value of num at position “ i “ in the array . That is , it will return , 10 when position is 1 or array number is 0 , followed by 20 when i = 1, 30 when i=2 , …..

(iii) When the for loop begin its execution , it will first invoke the initialization expression for the first and last time , to know from where to begin the iteration or loop.

(iv) Then will check the termination condition , in this case , initially i = 0 , which is less than the length of array num ( 10 ) , so the expression evaluates to “true” , hence will execute the statements within .

(v) At the end of loop statement execution , before another loop begins to verify and execute , the increment of expression takes place , that is , “ i “ will be incremented to 1.

(vi) Again , termination expression is evaluated , and as 1 < 10 , its “true” , the statements within the for loop body executes. In the end , of loop statement execution again “ i “ value is incremented…..so on…

(vii) Until “ i “ has been incremented to 10 , now again to run the loop , termination expression is evaluated , as 10 <10 is “false “ the loop will terminate.

JUMP STATEMENTS

This includes break statements , continue statements , return statements.

1. The break statements

As suggested by the name , break statements are used to terminate to execution of the code below and move out of the block code. After terminating , executes the statement next to the block statements , unless it’s a labelled break statement , in which case it executes code from the point below the label.Its of two types, Labelled and unlabelled break statements.

(a)Unlabelled break statements :

Usually used with switch-case , but can be used in any conditional statement ,i.e., also used to terminate iteration statements too.

Ex: Search for a number in an array

int[] num ={10,20,30,40,50,60,70,80,90,100};int search = 80;boolean foundIt = false;for (int i=0 ; i < num.length ; i++){    if (num[i] ==search) {        foundIt = true;        break ;    }}If(foundIt) {    System.out.println( search + “ at index “ + i);}else {    System.out.println( search + “ not in the array “);}OUTPUT:80 at index 7

Explanation: set Boolean foundIt to false at first , then run a for loop to find the number in array num. If its found , set foundIt to true , and break the statement. Then flow of control move to the statement immediately following the for loop block code. If foundIt is true , then print the index , else print not found!!

(b) Labelled break statements :

The break statement terminates the labelled statement ; the flow of control moves to the statement immediately following the labelled (terminated ) statement.

Ex: finding a number in 2D array

int search = 122;int i=0 , j=0;boolean foundIt = false;int[][] num={ { 33,64,31,15},{122,45,6,12},{165,123,10,20}};search: //label is followed by the “ : “for (; i<num.length;i++){   for ( j=0 ;j<num[i].length ; j++) {       if (num[i][j] == search) {           foundIt = true;           break search ;       }   }}if (foundIt){    System.out.println(search + “at “ +i + “ , “ +j );}else{   System.out.println( search +” not found” );}OUTPUT:122 at 1,0

2. The continue statements

It is used to skip the current iteration of the for , while or do-while loop. What it actually does is , it also terminates the loop thus preventing it from executing the statements below it , BUT, the ONLY DIFFERENCE is that , the flow of control remains with the loop ,i.e., the loop will run again from the top statement of its block code.

(i) Unlabelled continue statement :

Ex: count the no of even numbers present in an array num

int[] num ={ 12,2,3,4,52,100,7,1,20,21};int count =0;for ( int i=0 ; i < num.length ; i++){   if ( (num[i] % 2) != 0 )        continue;   //no need of {} as contains only 1 line code   count++;}System.out.println(“No of even numbers in the array are “ + count };OUTPUTNo of even numbers in the array are 6

Explanation: In the above example , we have first created an array num and assigned some values to it. Initially the count is kept zero. When the for loop begins its execution , i=0 , will denote first index or position in the array and num[i] will be equal to 12. At this point as per our if condition expression will be evaluated to check whether its even or not , if it is not even i.e., remainder on dividing 12 by 2 is not equal to 0 , then the execution of for loop body will terminate or stop , and again the flow of control will remain with the for loop only , and move to the top , so before the loop begins to execute again , “ i “ is incremented and the loop runs and checks the if condition (first statement here ) , if again its not equal to 0 , execution stops , for loop will enter next iteration. Now , if the remainder turns out to be 0 , i.e., then if statement will not be executed here , and the flow of control moves to the following statement i.e., to count++ , thus incrementing the count. This goes on , and after the loop is terminated , the result is printed out .

(ii) Labelled continue statement :

The continue statement skips the current iteration of the outer loop marked with the given label.

Ex: find the sub-string in the string

String main=”look for the substring in me “;String sb = “sub”;boolean found = false;int max = main.length() — sb.length() ;test:for (int i=0 ; i<=max;i++){    int n = sb.length();    int j=i ;    int k=0;    while ( n — !=0 )   {        if (main.charAt(j++) != sb.charAt(k++))             continue test; // if not found iterate   }   found = true;   break true; // found so break out of loop}System.out.println(found ? “found it “ : “not found” );OUTPUT:found it

3. The return statements

The return statements are used as the method return value , meaning , its value that is to be passed on to the other method maybe. Basically is explicitly used to return from current method . It can return a value or simply return back to the method from another method. IMPORTANT the datatype of the return should match the type of methods declared return value. You wiil understand it better in my other tutorial on the java methods in the future.

Example:

//method for sum of two numbersint sum (int a, int b ) // should return value of datatype int{    return a+b;}int c = sum(2,3);// c = 5

That’s all for today guy’s !!! I will make a separate tutorial post on Exception handling !

Till now whatever I have covered in my tutorials are mostly the same in majority of the programming languages i.e., the variation might be skin deep , but underneath it , its the same for all .Finally , in our next tutorial we will dive deep into the OOP concept of Java , the real Java. Feel free to drop any comments or doubts from the topics I have covered.

Happy coding!!!

--

--

shaistha fathima
shaistha fathima

Written by shaistha fathima

ML Privacy and Security Enthusiast | Research Scientist @openminedorg | Computer Vision | Twitter @shaistha24