Java Basics - Lecture 4 - What is class and object in Java

The Hacks of The Day
Java Class and Object

This lecture will cover basic OOP concepts. What is Class and Object? What is the difference between them?

Lecture 4 Agenda


1) Class
2) Object

Classes and objects are the fundamental parts of OOP. In OOP, we try to map real-world entities into software objects. Although there is a confusion between object and class, in this article, we will try to explain the difference between object and class. First, let's understand what they are.

What is a class?

A class is a blueprint or template for objects. It defines the behavior of objects. It determines how an object will behave and what the object will contain. In other words, a set of instructions to build a specific type of object.

Syntax:

public Class {
 Data Members;
 Member Functions;
}

Class Components:

Access Modifiers: A class can be public or has default access.
Class Name: The class name begins with a Capital letter.
Class Body: The class body is shown by curly braces, { }. It contains data members and member functions.

What is an Object?

An object is an entity with some attributes and behavior. When we look around, we see many examples of real-world objects: dog, desk, television, bicycle, etc. The real-world objects have two characteristics one is called "state" and the other is "behavior".

For example, dogs have state (name, color, breed, age, size) and dogs have behavior (barking, eating, running, sleeping). In terms of Software objects, they also have state and behavior.

Remember: To create an object of a class"new" keyword is used.

Syntax:
ClassName ReferenceVariable = new ClassName();

An object consists of :

State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by methods of an object. It also shares the response of an object with other objects.
Identity: It assigns a unique name to an object and enables one object to interact with other objects.

When an object of a class is created the class is called instantiated. All the instances share the attributes and the behavior of the class, the state will be different for each object. A single class can have more than one instance. As shown in the below image.

What is object and class in Java

Let's take an example of a class Car. Below is the Java code for this class.
//Class Declaration

public class Car {
 // Instance Variables
 int model;
 int wheel;
 String color;
 // Member Function
 public String getInfo() {
  return ("Modal is: " + model + " Wheels are: " + wheel + " Color is: " + color);
 } 
 public static void main(String[] args) {
  Car car = new Car();
  car.model = 2015;
  car.wheel = 4;
  car.color = "while";
  System.out.println(car.getInfo());
 }
}
Output: 

Modal is: 2015 Wheels are: 4 Color is: white

In the above example, we created one reference variable (car) and assigned a new instance of the Car class to this variable. Such an object is also called an instance of the class.

Summary:

A class is a user-defined blueprint or template from which objects are created. It determines how an object will behave and what the object will contain.
A Java object consists of methods and properties to make a certain type of data useful.
A class system allows the program to define a new class (child class) in terms of an existing class (parent class) by using a technique like inheritance, Polymorphism, and overriding.

How to find XPath in Selenium WebDriver?

The Hacks of The Day
How to find XPath in Selenium WebDriver?


What is XPath? 

It is a syntax or language for finding the web elements on the web page from an XML document. XPath is used to find the location of any element on a web page using the HTML DOM structure. The Syntax for XPath: The below diagram is showing the format and elements of XPath. It helps to find the complex, dynamic web elements which are not accessible with common locator like ID, Name, CSSSelectors, etc.

XPath=//tagname[@attribute='value']

// : Select current node.
Tagname: Tagname of the particular node.
@: Select attribute.
Attribute: Attribute name of the node.
Value: Value of the attribute.

How to get XPath in Chrome: 

  1. Open the required URL in google chrome browser.
  2. Inspect the required element
  3. Right-click on the selected element
  4. Navigate to Copy -> Copy Full XPath (Absolute XPath)
  5. Navigate to Copy -> Copy XPath (Relative XPath)

Types of XPath: 

XPath has the following two types. Let's explain one by one to get deep understanding of XPath

1- Absolute XPath
2- Relative XPath 

Absolute Xpath: 

The Xpath that is used to find the element from the root node is called absolute XPath. The absolute XPath starts with a single slash(/). It contains the whole DOM structure starting from the root node to the node that we are going to find. The disadvantage of the absolute XPath is that when some changes are made in the path of the element, then that element could not be accessible anymore. Below is the example of absolute XPath.
Absolute XPath: /html/body/div[1]/div/div/form/div/div[1]/div/input

Relative XPath: 

It does not start from the root node. It starts finding the elements from the middle of the DOM structure. Double forward slash(//) is used to find the relative XPath. It can search the element anywhere on the web page. Below is the example of relative XPath.
Relative xpath: //*[@id="ui"]/div/div/form/div/div[2]/div/input
XPath finding with different locators. Given below are the possible ways to find the XPath.

1) Find By Id: 

Suppose we have the following HTML structure for an element. We can find the XPath by ID because the ID attribute is available.
Xpat h= //input[@id='email'] or we can also use as //*[@id='email']

2) Find By Name:  

If you want to find the XPath by Name attribute then the XPath expression will look like be as given below. Some time "id" attribute is not available in HTML structure for the required element. Then we can use "Name" attribute
XPath=//input[@name='email'] or we can also use as //*[@name='email']
Here is a link of the page https://ui.cogmento.com/

3) Find By Class Name: 

You can also find the XPath by Class Name. Given below is the example of XPath by Class Name.
XPath = //h2[@class='barone']

4) Find By Text() Method:

This method is used to find the element with exact text matching. In our case, we find the element with the text "Login".
XPath = //div[text()='Login']

5) Find By Contains() Method:

Contains() method is used in XPath expression to find the web elements with partial text matching. In the below example we have tried to find the element with partial text. In the XPath expression, you can see the text "Sign" in place of "Sign Up" But we can't find this element with the Text() method directly, because it only works with full-text matching.

XPath = //a[contains(text(),'Sign')] // Full Name Sign Up
Xpath = //*[contains(@type,'btn')] // Full Name btnLogin
If we use text() method with partial text as given below, it will not work.
XPath = //a[text(),'Sign')]

6) Find By Child: 

In the following XPath expression, we have found the child element "a" of the h4 tag. We can not find the "a" tag directly with the text "Java" because some other elements have the same text. So we have started with the top parent div of "a" tag.
XPath = //div[@class='g-block box4 size-24 hidden-phone']
//div[@class='g-content g-particle']//div[@class='canvas-graph']
//div[@class='canvas-middle']//h4//a[text()='Java']

7) Find By Preceding Sibling: 

In the preceding sibling, we can find the nodes that come before the current node, but the level should be the same. In some cases to find an element, we need to do some reverse engineering. We move from bottom to top to find the required element. To click in the checkbox, we will find the name that comes in front of a checkbox.
XPath = //td[text()='Tom Peter']
//preceding-sibling::td//div[@class='ui fitted read-only checkbox']
//input[@name='id']

8) Find By the Following Sibling: 

In the following sibling, we can find the nodes that come after the current node, but the level should be the same. One thing, that you should remember in the following sibling only one forward-slash (/) is used before the keyword (following-sibling). But in the case of preceding sibling double forward-slash (//) is used.
XPath = //div[@class='canvas-middle']
//a[contains(@href, 'http://www.guru99.com/accounting.html')]
/following-sibling::h4//a[text()='ACCOUNTING']

9) Find By Parent: 

It selects the parent of the current node, as shown in the below image.
XPath = //td[text()='Tom Peter']//parent::tr
//td//div[@class='ui fitted read-only checkbox']
//input[@name='id']

10) Find By Starts-with & Ends-with Methods: 

To find the XPath of the dynamic web element, whose attribute value changes on refresh, we will use either Starts-with or Ends-with method. Suppose id of an element is changing dynamically like: Id = message_123 Id = message_234 Id = message_544 So on... In the above examples, initial text is the same (message) but numerical values keep changing. So Starts-with function will be used.
XPath = //input[starts-with(@id,'message_')]
Similarly, we can use the Ends-with method. But it can be used, where the last value remains the same, and the initial value keeps changing. Suppose id of an element is changing dynamically like: Id = 234_test_t Id = 456_test_t
XPath = //input[ends-with(@id,'_test_t')]

Conclusion: 

To find the element by XPath is much more efficient as compared to other locators. That's why in complex projects, Automation Engineers prefer to use XPath for finding the elements. You can use it in a versatile way. You can find an element by moving from child to parent or parent to child. You can navigate to any direction in the HTML DOM structure. You can also control the dynamic values of web elements.

FindElement and FindElements in Selenium WebDriver.

The Hacks of The Day
Find Element and FindElements in Selenium WebDriver.

WebElement Interface Hierarchy: 

Before going into depth, how to find the element in selenium. First, we will have a look at the basic architecture of the WebElement interface. It extends SearchContext and TakesScreenShot interfaces. It has many useful abstract methods like click, sendKeys, isSelected(), etc. Given below is a basic architecture of WebElement interface.



Find Element, or Elements command is used to interact with the web elements. If you want to find a single element, then you will have to use Find Element command, but for more than one element Find Elements command is used.

There are multiple ways to uniquely identify a web element within the web page such as ID, Name, Class Name, CSSSelector, Link Text, Partial Link Text, Tag Name, and XPath, etc.

FindElement Command Syntax: 

Find Element command takes an object "By" as a parameter and returns an object of type WebElement.By object can be used with various locators like ID, Name, Link Text, Class Name, Tag Name, Xpath, and CSSSelector. Find Element method returns a single WebElement. Suppose we wanted to find an element by the "id" attribute, the command will be written as given below
WebElement element = driver.findElement(By.id("id_value"));
Following locators can be used in Selenium WebDriver:
  • ID Name 
  • Class Name 
  • CSSSelector 
  • Tag Name 
  • Link Text 
  • Partial Link Text 
  • XPath 
Locator Value should be a unique value using which a web element can be identified. It is the responsibility of developers to make sure that web elements are uniquely identifiable using certain properties such as ID, Name, or Class.
Example:
WebElement loginName = driver.findElement(By.xpath("//input[@type= 'email']"));

FindElements Command Syntax: 

Find Elements command also takes an object "By" as a parameter and returns a list of web elements. It returns an empty list if there are not elements found using the given locator type and value. Below is the command syntax of find elements
List elementName = driver.findElements(By.LocatorType("LocatorValue"));
Example:
List listOfElements = driver.findElements(By.xpath("//button[@type='button']"));

Working Example of FindElement: 

  1. Go here https://accounts.google.com/
  2. Find the text field to enter email
  3. Enter email

package learning;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindElement {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
  WebDriver driver = new ChromeDriver();
  driver.manage().window().maximize();
  driver.manage().deleteAllCookies();
  driver.get("https://gmail.com");
  WebElement username = driver.findElement(By.xpath("//input[@type= 'email']"));
  username.sendKeys("test@gmail.com");
  //driver.close();
 }
}
The above code will do the following things:

  • Will open the specified URL
  • Will locate the email field
  • Will enter the email into the text field

Working Example of FindElements: 

  1. Open the URL under test
  2. Find all the buttons
  3. Print the tag name

package learning;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindElements {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  System.setProperty("webdriver.chrome.driver", "/home/khawer/Desktop/chromedriver");
  WebDriver driver = new ChromeDriver();
  driver.manage().window().maximize();
  driver.manage().deleteAllCookies();
  driver.get("https://www.google.com/intl/en-GB/gmail/about/");
  List list = driver.findElements(By.xpath("//button[@type='button']"));
  System.out.println("Number of elements:" + list.size());
  for (int j = 0; j < list.size(); i++) {
   System.out.println("Element "+i+" Tag Name:" + list.get(i).getTagName());
  }
 }
}
Output:
Element 0 Tag Name:button
Element 1 Tag Name:button
Element 2 Tag Name:button
Element 3 Tag Name:button
Element 4 Tag Name:button
Element 5 Tag Name:button
Element 6 Tag Name:button
Element 7 Tag Name:button
Element 8 Tag Name:button

Method Detail: 

  findElements

  Find a list of web elements within the web page.

 Parameters: The object reference variable of WebElement Interface

 Returns: A list of all WebElements.

 findElement

 WebElement findElement(By by)

 Find the first web element within the web page.

 Parameters: By class, the object is passed as a parameter

 Returns: The object reference variable of WebElement Interface

 Throws: NoSuchElementException - If no matching element is not found

Conclusion: 

  • Find Element command returns a single web element 
  • Find Elements command returns a list of web   element 
  • Find Element command throws NoSUchElementFoundException if it does not find the   matching element 
  • Find the Elements command returns an empty list if there are no matching elements.

First Selenium WebDriver Script in Java

The Hacks of The Day
As in our previous lecture, we have discussed the basic configuration of the selenium web driver. In this article, we will discuss how to write the first script in Java using selenium web driver. let us try to create a WebDriver script of the following test scenario:

Test Scenario: 

Open this URL https://www.gmail.com/
Give Username
Click on Next button
Give Password
Click on the Next button
Below is the selenium web driver code for the above scenario.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GmailLoginScript {

 public static void main(String[] args) {

  // First we need to set path for chromeDriver
  //System.setProperty("webdriver.gecko.driver","/home/khawer/Desktop/geckodriver");
  System.setProperty("webdriver.chrome.driver","/home/khawer/Desktop/chromedriver");
  WebDriver driver = new ChromeDriver();
  driver.manage().window().maximize();
  driver.manage().deleteAllCookies();
  driver.get("https://gmail.com");

  // UserName is given wrong deliberately. You can use your valid UserName.
  WebElement username = driver.findElement(By.xpath("//input[@type= 'email']"));
  username.sendKeys("test@gmail.com");

  WebElement nextBtn = driver.findElement(By.xpath("//span[text()= 'Next']"));
  nextBtn.click();

  // Password is given wrong deliberately. You can use your valid Password.
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  WebElement password = driver.findElement(By.xpath("//input[@type = 'password']"));
  password.sendKeys("abc123");
  driver.findElement(By.xpath("//div[@id = 'passwordNext']")).click();
  // close Firefox
  driver.close();
 }
}
Now let's try to explore the above script written for Gmail login.

Property Settings: 

Before going into detail of this line of code first, we need to understand one thing that is browser driver. Every browser has a browser driver like FirefoxDriver, ChromeDriver, etc. You can download the respective browser driver that you are going to use in your application. For the Firefox browser, we need to download a gecko driver.
In this example we have used the chrome browser, so we have downloaded a chrome driver. In the SetProrpty method, we need to give two parameters one is "value" and the other is "key".
The following are the two parameters for this method. value: webdriver.chrome.driver Key: chrome driver path on your local system, where you have placed the executable.
System.setProperty("webdriver.chrome.driver","/home/khawer/Desktop/chromedriver");

Note: Compatibility is a major issue while using Firefox. For Firefox 35, you should use a gecko driver created by Mozilla to use Web Driver. The use of Selenium 3.0, gecko, and firefox has compatibility issues, and setting them correctly could become an uphill task. In case of any issue, downgrade to Firefox version 47 or below. But for on Chrome things are much easy. Selenium works out of the box for Chrome. Without a Chrome Driver, we can't instantiate the Chrome browser.

If we run the program without setting the system property, the system will through the following exception. "IllegalStateException"

Object and variables Initialization: 

Normally, this is how a driver object is created. Actually, "driver" is a reference variable of the WebDriver interface and an object of ChromeDriver class is assigned to it. It means ChromeDriver class will implement all methods of WebDriver interface.
WebDriver driver = new ChromeDriver();

Clear Cookies & Maximize Window: 

The following two-line is used to clear the cookies before launching the browser. This line of code is not mandatory, but for better performance, we can use it.
driver.manage().deleteAllCookies();
This command is used to maximize the browser window.
driver.manage().window().maximize();

Starting Browser Session: 

In Selenium Web Driver get() method is used to launch a new browser session and directs it to the URL that you specify as its parameter. The following statement will launch a browser and open the Gmail login page.
driver.get("https://gmail.com");

Finding UI Elements: 

To find the UI elements different locators are used in Selenium WebDriver. You can find UI elements by XPath, ID, Name, Class, CSSSelectors, LinkText, etc. We will discuss it in full detail in the upcoming lecture. Here we are using findelement() method of WebDriver interface to find the particular element.
A reference variable of the Web Element interface is used to store the particular element. Basically, the WebElement interface is responsible to interact with web elements like sendkeys(), click(), etc.

WebElement username = driver.findElement(By.xpath("//input[@type= 'email']"));
username.sendKeys("test@gmail.com");
WebElement nextBtn = driver.findElement(By.xpath("//span[text()= 'Next']"));

You can also write it in a simple way. For understanding the purpose above statements is good.
driver.findElement(By.xpath("//input[@type='email']")).sendKeys("test@gmail.com");

Clicking on an Element: 

The Click() method is used to click on any web element.
nextBtn.click();
The following lines of code are just a way of making selenium WebDriver to wait, until the next element loads. There are two types of wait in Selenium WebDriver that we will discuss in detail in a separate article.
A brief introduction to wait is:
Implicit wait - A default waiting time that is used throughout the program
Explicit wait - It is used to wait for a particular instance only.

In this article, we are just giving a basic introduction to Selenium WebDriver. In some situations, without using the wait script not works properly. An exception raised, "NoSuchelementFound". So it is necessary to use the wait in Selenium WebDriver where elements are not loaded accurately.
try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
Similarly, we can find the password field by using the findelement() method.
WebElement password = driver.findElement(By.xpath("//input[@type = 'password']"));
  password.sendKeys("abc123");
To click on the sign-in button the following line of code will work.
driver.findElement(By.xpath("//div[@id = 'passwordNext']")).click();

Close Browser Session: 

The close() method is used to close the browser that WebDriver is currently controlling.
driver.close();
It closes all the windows that WebDriver has opened.
driver.quit();
Terminating the Entire Program: This command will close your Java program without closing the window.
System.exit(0);

Conclusion: 

By reading this simple article, you can write your first script in selenium WebDriver. All the lines of code explained in a better way for the ease of readers. So stay tuned for upcoming articles. Cheers!!

How to write a test report?

The Hacks of The Day











Hey Guys! If you are a newbie in the field of software testing and don't know how to write a test report, then you are in the right place. In this article, a brief and simple explanation will give you a full hold on the test report. Writing an effective test report is a vital part of software testing.

When you send a bug to the Project Manager for checking, then the project manager will verify the bug easily if your test report has written simply and descriptively. On the other way, the Project Manager will send it back for more explanation. Now let's see what is the structure of a well-written test report and What are the fundamental elements of a test report?


Structure of the Test Report

The following are the fundamental elements of a test report. Now let's go in more detail and try to understand what about they are?

  1. Environment
  2. Browser
  3. Desktop/Device
  4. Title of Bug
  5. Testing Details
  6. Images
  7. Testing URLs
  8. Status
  9. CC (Participants)
  10. Notes (Optional Part)


Environment: Environment section describes the operating system which you are using to test a bug. If you are using Windows/Ubuntu or any other you can write it in the environment section.

Browser: In this section, you can write the name of browsers you are using for testing. Like Chrome, Firefox, IE, Opera, and Safari.

Desktop/Device: Here you can mention the name of devices that you are using to test a bug. If you are testing on Desktop then you can write "Desktop" if you are testing on Mobile Phones you can write the names of devices like iPhone 6/7/8, Huawei y7 prime, etc.

Title of Bug: Write the title of the bug that you have tested.

Testing Details: This section contains the testing details that you have tested. You should write all the points to clarify what you have tested. Normally points are written in the form of Test Cases. Write all the possible scenarios here so that the Project Manager could get understanding that you have covered all the things. It should be more descriptive.

Images: In this section, images are attached to the test report. Image's attachment is necessary because they will show that things are working fine practically. With the help of images, PM can easily see the corrected things. Without executing the application he can confirm that bug is fixed now.

Testing URLs: In this section, write the URLs that have used for testing.

Status: Status will be Fail or Pass.

CC (Participants): In this section, we tag the participants like Project Manager and Business Guys so that they could get intimated when you attach the test report.

Sample Test Report:

Environment:  Ubuntu 18

Browser: Chrome, Firefox, etc

Desktop/Devices: Desktop

Title:

Login Page - Sign in functionality is not working.

Testing Details:

Test Case1: Sign-in is working fine with valid credentials
Test Case2: Error messages are shown with invalid credentials
Test Case3: Error messages are shown with empty fields
So on...

Images:

!image1.png|thumbnail!
!image2.png|thumbnail!
!image3.png|thumbnail!
!image3.png|thumbnail!
So on...

URLs:

https://abc.com/login
https://abc.com/user/login
So on...

Status: PASS

Progress made:

=> This has been implemented. All things that are mentioned in Ticket's description are done.

=> Please check and let me know if I missed anything OR there's any kind of work that still needs to be done under this card.

CC: Rock, Steve ...

Notes: It is an optional part of a test report. Here you can write some special notes if you want to mention something related to the bug for Project Manager.

Thanks,
Tester Name

This is a basic structure of a test report. Little things can vary as per company requirements, but the basic structure will remain the same.

Java Basics - Lecture 3 - Loops in Java

The Hacks of The Day

Loops in Java














Loops are used to perform a task repeatedly. There are 3 types of loops

  1. while loop
  2. for loop
  3. do-while loop

Suppose if you want to print first 5 digits

You need to write 5 print statements

System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);

Instead of writing repeated code, we use loops

While loop :

A control flow statement which is used to perform the repeated tasks based on a given Boolean condition. In while loop number of iterations is not fixed. Loop will be executed only if the condition is true. It is also called the entry control loop.

Flow Chart Diagram



Disadvantage: It generates an infinite loop if we don't give an incremental part

For Loop:

A control flow statement which is used to perform repeated tasks. But in for loop number of iterations are fixed.

Flow chart Diagram



Parts of for loop (Initialization, Conditional part, Incremental part)

Initialization: In this part, the variable is initialized. It is a starting point of the loop

Condition: In this part condition is checked, it returns a boolean. In the case of the true, the loop body is executed.

Increment/Decrement: Variable is incremented or decremented here for next iteration

Loop termination: When the condition becomes false, then the loop is getting terminated.

For Loop Example




public class ForLoop {
public static void main(String[] args)  {
  for(int j=1;j<=10;j++){
  System.out.println("Values of ==> " + j);
  }
 }
}

Output:
value of j ==> 1
value of j ==> 2
value of j ==> 3
value of j ==> 4
value of j ==> 5
value of j ==> 6
value of j ==> 7
value of j ==> 8
value of j ==> 9
value of j ==> 10
If you want to print 10 digits in reverse order then below code will work fine.

public class ForLoop{
 public static void main(String[] args){
  for(int k=1;k<=10;j--){
  System.out.println("Values of ==> " + k);
    }
  }
}

Post Increment

An operator that is used to increment the value of the variable after the expression is executed in which post-increment is used. The value is first used in an expression and then incremented.
public class PostIncrement{
 public static void main(String[] args){
 int i = 1;
 int j = i++; //post increment

   }
}

Pre Increment

An operator that is used to increment the value of the variable before the expression is executed in which post-increment is used. The value is first incremented in an expression and then used.  
public class PreIncrement{
 public static void main(String[] args){
 int a = 1;
 int b = ++a; //pre-increment
   } 
}

Post Decrement

An operator that is used to decrement the value of the variable before the expression is executed in which post-increment is used. The value is first decremented in an expression and then used.  
public class PostDecrement{
 public static void main(String[] args){
 int i = 2;
 int j = i--; //post decrement
   }
}

Pre Decrement

An operator that is used to decrements the value of the variable before the expression is executed in which post decrement is used. The value is first decremented in an expression and then used.  
public class PreDecrement{
 public static void main(String[] args){
 int a = 2;
 int b = --a; //pre-decrement
 System.out.println("Value of a ==> "+a);
 System.out.println("Value of b ==> "+b); 
  }
}

do-while loop :

The do-While loop is similar to while loop but the difference is that the body of the do-while loop is executed once and then the condition is verified. A control flow statement that executes a piece of code at least once.

Flow Chart Diagram


If the test expression is true, the body of the loop is executed again and the test expression is evaluated.

The first loop body is executed then the condition is checked, this process continues until the condition is false.

This process goes on until the test expression becomes false.

If the test expression is false, the loop ends.


public class DoWhileLoop{
 public static void main(String[] args){
 int counter = 5;
 int factorial = 1;
 do{
    factorial *= counter--;
 }while (counter > 0);
 System.out.println("result " +factorial);
  }
}
Output:
 result ==> 120

Array in Java

Array: Stores similar data type values in an array variable.
  1. A collection of similar data types
  2. The lowest index is always “0”
  3. The highest index is always n-1 (n is the size of the array)
Int array
Integer array stores the integer data type. 
 int arr[] = new int[4];
 arr[0] = 10;
 arr[1] = 20;
 arr[2] = 30;
 arr[3] = 40;
 System.out.println(arr[2]);
 System.out.println(arr[3]);

Output:
value of arr[2] ==> 30
value of arr[3] ==> 40

If you will try to find the arr[4], it will give exception

When you go beyond the limit, an exception will raise “ArrayIndexOutOfBoundsException”

Size of array
The size of the array is determined by using length() method.
System.out.println(arr.length)
Print all the values of the array: use for loop
 for(int i=0; i < arr.length; i++){
 System.out.println(arr[i]);
 }
Double array
Double array stores the double data type. 
double d[] = new double[3];
d[0] = 3;
d[1] = 14.33;
d[2] = 44.89;
Character array
Character array stores the character data type. 
char c[] = new char[3];
c[0] = 'a';
c[1] = '3';
c[2] = '$';
String array
String array stores the string data type. 
String s[] = new String[3];
s[0] = "test";
s[1] = "World";
s[2] = "Hello";
Disadvantages:
  1. The array size is fixed. Therefore it is called a static array
  2. Stores only similar data types
To overcome size problem we use Collections like ArrayList, HashTable
To overcome data type problem we use Object array
Object array(Object is a class) – It is used to store different data types

Object array
 Object obj[] = new Object[6];
 obj[0] = "Tom";
 obj[1] = 25;
 obj[2] = "M";
 obj[3] = 12.33;
 obj[4] = "1/10/1998";
 obj[5] = "London";
Find all elements of Object array
for(int i=0; i<obj.length; i++) {
 System.out.println(obj[i]);
}
Output
value of obj[0] ==> Tom
value of obj[1] ==> 25
value of obj[2] ==> M
value of obj[3] ==> 12.33
value of obj[4] ==> 1/10/1998
value of obj[5] ==> London

2D Array in Java
Collection of data in the form of cells
Represented as a matrix with a number of rows and columns
String x[][] = new String[3][5];
Output:
System.out.println(x.length);
Number of row ==> 3
System.out.println(x[0].length);
Number of columns ==> 5
//1st row

x[0][0] = "A";
x[0][1] = "B";
x[0][2] = "C";
x[0][3] = "D";
x[0][4] = "E";
//2nd row

x[1][0] = "A1";
x[1][1] = "B1";
x[1][2] = "C1";
x[1][3] = "D1";
x[1][4] = "E1";
//3rd row

x[2][0] = "A2";
x[2][1] = "B2";
x[2][2] = "C2";
x[2][3] = "D2";
x[2][4] = "E2";
Output
System.out.println(x[1][2]);
value of x[1][2] ==> C1</
System.out.println(x[2][2]);
value of x[1][2] ==> C2
System.out.println(x[0][4]);
value of x[1][2] ==> E
Print all the values of 2D array
Two for loops are required to get array values
//row = 0, col = 0 to 4
//row = 1, col = 0 to 4
//row = 2, col = 0 to 4

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

  value of x[0][0] ==> A value of x[0][1] ==> B
  value of x[0][2] ==> C value of x[0][3] ==> D
  value of x[0][4] ==> E

  value of x[1][0] ==> A1 value of x[1][1] ==> B1
  value of x[1][2] ==> C1 value of x[1][3] ==> D1
  value of x[1][4] ==> E1

  value of x[2][0] ==> A2 value of x[2][1] ==> B2
  value of x[2][2] ==> C2 value of x[2][3] ==> D2
  value of x[2][4] ==> E2