09-2 Control Flow

9.2 | Looping Statements

Java supports four looping statements.

  • for...statement
  • for each...statement
  • while...statement
  • do while...statement

for ...statement

It executes a block of code specified number of times.

   For example - the code below prints numbers from 1 to 9.

for ...statement


for...each statement

It executes a block of code for each item in a collection or each element in an array.

For example - the code below prints all numbers in an array.

for each ...statement


while...statement

It executes a block of code while or until the condition is true.

For example - The code below executes the loop until array value <4.

while...statement


do...while statement

It executes a block of code until the condition becomes false.

do...while statement


Note: while loop is executed only if the condition is true. So while loop can execute zero or more times. Whereas do...while loop is executed first time without validating the condition, i.e. it will always execute for the first time. At the end of the first loop, the execution condition is checked. So, do...while loop always executes 1 or more times.




09-1 Control Flow

Java, like any other programming language, supports both conditional and loop statements to control code flow.


9.1 | Conditional Statements

In Java, we have four conditional statement:

1. if(condition=true){}: Execute a set of code when the specified condition is true. 
2. if(condition=true){}else{}: Execute first block of code when the specified condition is true else executes the second block of code. 
3. if(condition1=true){}elseif{condition2=true}{}else{}: Execute the first block of code for which the condition is true. If no condition is found true and else block exists, then this block of code is executed. If no condition is found true and else block does not exist, then none of the if block code is executed. 
4. Switch(choice)...case: Executes a set of code for which the choice condition is true. switch...case is used when the number of available alternatives and options are many and at a time only one holds true. Though the same can be implemented using if condition too but that makes the code cumbersome and less readable.

9.1.1 | if...Statement

Consider a scenario where code logic to be implemented is as follows:

  • If the specified number is less than 5, then print "number<5".
  • Elseif the specified number is >=5 and <10, then print "number is between 5 and 10".
  • Else, print "number is >=10".

if...statement




9.1.2 | switch...Statement

Consider a scenario where the code logic to be implemented is as follows:

  • If grade = 5, then print "Excellent".
  • If grade = 4, then print "Very Good".
  • If grade = 3, then print "Good".
  • Else, print "Poor".

switch..statement



08 Arrays

8.1 | Arrays

An array is a data structure that stores a collection of values of the same data type. Values stored in the array are accessible through the array index

//Declaring an array of integers

int arr1[];


//Creating an integer array with values

int[] arr0 = {2,3,4,5,6,7};


//Creating an integer array which can hold 100 integers

int arr2[] = new int[100];

//Or,

int arraySize = 100;

int arr3[] = new int[arraySize];


//Assigning values to the array

arr3[0] = 1;
arr3[1] = 2;


//Creating a string array which can hold 100 values

String arr4[] = new String[100];


//Assigning values to the array

arr4[0] = "This";
arr4[1] = "is a string array by";
arr4[2] = "testinganswers.com";


//Accessing array values by using for loop

for(int i=0;i<arr3.length; i++){
     System.out.println("arr3["+i+"] = "+arr3[i]);
}

//Or by using for each loop,

for(int element:arr3){

    System.out.println(element +",");

}

//Copying array

int[] arr5 = arr3;
String[] arr6 = arr4;





8.1.1 | Multi-dimensional Arrays

Multi-dimensional arrays are arrays of an array. They use more than one index to store and access values.

//Declaring a multi-dimensional array

int[][] arr0;


//Creating a multi-dimensional array

int[][] arr1 = {
                       {1,2,3}
                       {4,5,6}
                       {7,8,9}
                    };



//Creating a multi-dimensional array of size 2*3
int[][] arr2 = new int[2][3];


//Creating a multi-dimensional array using variables

int arrayXsize = 3;
int arrayYsize = 3;
int[][] arr3 = new int[arrayXsize][arrayYsize];



//Assigning values to multi-dimensional arrays

arr3[0][0] = 1;
arr3[0][2] = 3;


//Accessing values from multi-dimensional arrays

for(int i=0;i<arr2.length;i++){
    for(int j=0;j<arr2[i].length;j++){
         System.out.println("arr2["+i+"]["+j+"] = "+arr2[i][j]);
    }
}


//Copying multi-dimensional arrays

int[][] arr4 = arr3;


07 Data Types, Literals, Variables, Expressions and Operators

7.1 | Data Types

Each variable declaration in Java must define the data type of the variable. The data type defines what values a variable can store. The variable type can be as follows:
  • One of the eight basic primitive data types
  • An Array
  • The name of a class
The eight primitive data types hold values for integers, floating-point numbers, characters and boolean values. They are called primitive because they are built into the system and are not actual objects. This makes them more efficient to use.


Data Type Width (bits) Minimum value/ Maximum value
boolean
NA
True, false
byte
8
-27 , -27-1
short
16
-215 , -215-1
char
16
0x0, 0xffff
int
32
-231 , -231-1
long
64
-263 , -263-1

Float
32
±1.40129846432481707e - 45f,
±3.402823476638528860e + 38f

double
64
±4.94065645841246544e - 324,
±1.7976931348623157e + 308



7.2 | Literals

A literal denotes a constant value, i.e., the value that a literal holds. A literal can represent boolean, numerical, character, string or null value


Literal
Literal Type
Example
Integer
Decimal
Octal
Hexadecimal
8, 10L, -90
010, 012L, -0132
0 x 8, 0 x aL, -05 x a

Floating
Double
Float
0.41, 4100e-2 , 0.41e2
0.41F, 4100e-2F, 0.41e2F

Boolean

True, false

Character

'', '1', 'A', 'a'

Escape Sequences
\b, \t, \n, \f, \', \”, \\

String

“This is a String”



7.3 | Variable Declaration

A variable stores a value of specific type. Variable declaration is used to specify the type and name of the variable, The following code shows how to declare and initiate variables.

int i;                                          // Declaring interger variable
i=1;                                          // Initializing integer variable
int j=2;                                   // Declaring and initializing integer variable
long k=2L;                             // Declaring and initializing integer variable
boolean status=false;           // Declaring and initializing boolean variable
float f1 = i/3;                      // Declaring and initializing float variable
float f2 = (float) (i/3.0);    // Declaring and initializing float variable

String str = "This is a string." // Declaring and initializing a String variable


7.4 | Expression & Operators

Expressions are statements in Java that return a value. Operators are special symbols that perform an operation, for example, add and subtract.

7.4.1 | Arithmetic Operators

List Java arithmetic operators


Operator
Description
Example
+
Addition
5 + 2 = 7
-
Subtraction
5 – 2 = 3
*
Multiplication
5 * 2 = 10
/
Division
5/2 = 2
%
Modulus
5%2 = 1



7.4.2 | Comparison Operators

All Java comparators return a boolean value. 


OperatorDescriptionExample
==
Equal
5 == 2 = false
!=
Not Equal
5 != 2 = true
<
Less Than
5 < 2 = false
>
Greater Than
5 > 2 = true
<=
Less Than Equal To
5 <= 2 = false
>=
Greater Than Equal To
5 >= 2 = true


7.4.3 | Logical Operators

Logical operators are used to implementing logical AND, OR, XOR and NOT condition.


Operator
Description
Example
&&
AND
(5<2) && (2>10)
||
OR
(5<2) || (2>10)
^
XOR
(5<2) ^ (2>10)
!
NOT
!(5 < 2)


7.4.4 | Bitwise Operators

Bitwise operators perform operations on individual bits in integers.


Operator
Description
Example
&
Bitwise AND

|
Bitwise OR

^
Bitwise XOR

<<
Left shift

>>
Right shift


>>>
Zero fill right shift

-
Bitwise complement

<<=
Left shift assignment

>>=
Right shift assignment

x&=y
AND assignment
Equivalent to x=x&y
x|=y
OR assignment
Equivalent to x=x|y
x^=y
NOT assignment
Equivalent to x=x^y

06 Introduction to Java

Java is an object-oriented programming language (OOP) developed by Sun Microsystems, which enables programmers to create flexible, modular and reusable codes. The important feature of OOP language which help programmers achieve this are encapsulation, polymorphism, and inheritance.



  • Encapsulation: It is a mechanism that binds together codes and data and manipulates to keep the code safe from outside interference and misuse. Java implements encapsulation by defining the accessibility condition of variables, methods, and classes (private, protected and public). Java's basic unit of encapsulation is class. A class specifies the data and the code that will operate on the data. A class specification is used to construct objects which are instances of a class.

  • Polymorphism: It is an OOP feature that enables an object to determine which method to implement or invoke upon receiving a method call. One of the ways Java implements this is through method overloading and method overriding.

  • Inheritance: It is an OOP feature which enables building new classes from the existing ones. With inheritance, subclasses get access to all the attributes of its superclass. This allows one object to acquire the properties of another. One way of implementing this in Java is by defining abstract classes.

  • Abstraction: It is an OOP feature that used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface).

6.1 | Classes

One of the fundamental ways in which Java handles complexity is an abstraction. A class models an abstraction by defining the properties and behaviors of objects representing the abstraction. Class acts as a blueprint for creating objects.

6.1.1 | Writing First Java Class Program

The following steps describe how to create a new java class and write a code to it.

1. Open Eclipse and create a new project, say 'SeleniumAutomation'.

2. Right-click on the 'src' and select New --> Package. 'New Java Package' window pops is opened. Enter the package name as 'com.testinganswers'.

3. Right-click on the 'com.testinganswers' package and select New --> Class. 'New Java Class' window pops is opened.

4. Specify the class name say 'MyFirstClass' and click on 'Finish' button. Specified class is created as shown in below figure.

5. Write code for the class. Below figure shows a simple class code with 'main' method to display 'Hello World!!!' on Eclipse console.


6. To execute this code from Eclipse, right click on the Eclipse editor window and select Run As --> Java Application.