<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Development of net banking application]]></title><description><![CDATA[Development of net banking application]]></description><link>https://development-of-net-banking-application.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 19 Jun 2026 23:18:13 GMT</lastBuildDate><atom:link href="https://development-of-net-banking-application.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Selenium Pom Framework]]></title><description><![CDATA[Page Object Model and Page Factory in Selenium
Know about Page Object Model & Page Factory in Selenium for better object repository structuring
Page Object Model and Page Factory in Selenium
Page Object Model and Page Factory are tools in Selenium th...]]></description><link>https://development-of-net-banking-application.hashnode.dev/selenium-pom-framework</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/selenium-pom-framework</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 18:27:36 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-page-object-model-and-page-factory-in-selenium">Page Object Model and Page Factory in Selenium</h1>
<p>Know about Page Object Model &amp; Page Factory in Selenium for better object repository structuring</p>
<h2 id="heading-page-object-model-and-page-factory-in-selenium-1">Page Object Model and Page Factory in Selenium</h2>
<p>Page Object Model and Page Factory are tools in <a target="_blank" href="https://www.browserstack.com/selenium">Selenium</a> that are popularly used in <a target="_blank" href="https://www.browserstack.com/guide/automation-testing-tutorial">test automation</a>. This tutorial will demonstrate how to use Page Object Model and Page Factory in Selenium automation projects to maintain test cases easily.</p>
<h3 id="heading-what-is-page-object-model-in-selenium">What is Page Object Model in Selenium?</h3>
<p>Page Object Model, also known as POM, is a <a target="_blank" href="https://www.browserstack.com/guide/design-patterns-in-selenium">design pattern in Selenium</a> that creates an object repository for storing all web elements. It helps reduce code duplication and improves test case maintenance.</p>
<p>In Page Object Model, consider each web page of an application as a class file. Each class file will contain only corresponding web page elements. Using these elements, testers can perform operations on the website under test.</p>
<p><strong>Read More:</strong> <a target="_blank" href="https://www.browserstack.com/guide/design-patterns-in-automation-framework"><strong>Design Patterns in Automation Framework</strong></a></p>
<h4 id="heading-advantages-of-page-object-model"><strong>Advantages of Page Object Model</strong></h4>
<ul>
<li><p><strong>Easy Maintenance</strong>: POM is useful when there is a change in a UI element or a change in action. An example would be: a drop-down menu is changed to a radio button. In this case, POM helps to identify the page or screen to be modified. As every screen will have different Java files, this identification is necessary to make changes in the right files. This makes test cases easy to maintain and reduces errors.</p>
</li>
<li><p><a target="_blank" href="https://www.browserstack.com/guide/importance-of-code-reusability"><strong>Code Reusability</strong></a>: As already discussed, all screens are independent. By using POM, one can use the test code for one screen, and reuse it in another test case. There is no need to rewrite code, thus saving time and effort.</p>
</li>
<li><p><strong>Readability and Reliability of Scripts</strong>: When all screens have independent java files, one can quickly identify actions performed on a particular screen by navigating through the java file. If a change must be made to a specific code section, it can be efficiently done without affecting other files.</p>
</li>
</ul>
<h4 id="heading-implementing-pom-in-selenium-project">Implementing POM in Selenium Project</h4>
<p>As already discussed, each java class will contain a corresponding page file. This tutorial will create 2-page files.</p>
<ul>
<li><p>BrowserStackHomePage</p>
</li>
<li><p>BrowserStackSignUpPage</p>
</li>
</ul>
<p>Each of these files will contain UI elements or Objects which are present on these screens. It will also contain the operations to be performed on these elements.</p>
<p><strong>Also Read:</strong> <a target="_blank" href="https://www.browserstack.com/guide/build-and-execute-selenium-projects"><strong>How to Build and Execute Selenium Projects</strong></a></p>
<h4 id="heading-sample-project-structure-for-pom">Sample Project Structure for POM</h4>
<p><img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/POMSetUp.png" alt="page object model in selenium" /></p>
<p><img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/BrowserStackHomePage-700x459.png" alt="POM in selenium - Java File" /></p>
<p><strong>Explanation of Code</strong></p>
<ul>
<li><p><strong>Code Line-10 to 11:</strong> Identifying elements present on BrowserStack Home Page such as <strong>header</strong> and <strong>Get Started</strong> button</p>
</li>
<li><p><strong>Code Line-17 to 24:</strong> Performing actions on identified objects on BrowserStack Home Page</p>
</li>
</ul>
<p><strong>Code Snippet</strong></p>
<pre><code class="lang-plaintext">package browserStackPages;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class BrowserStackHomePage {

WebDriver driver;
By Header=By.xpath("//h1");
By getStarted=By.xpath("//*[@id='signupModalButton']");

public BrowserStackHomePage(WebDriver driver) {
this.driver=driver;
}

public void veryHeader() {
String getheadertext=driver.findElement(Header).getText();
assertEquals("App &amp; Browser Testing Made Easy", getheadertext);
}
public void clickOnGetStarted() {
driver.findElement(getStarted).click();
}
}
</code></pre>
<p><img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/BrowserStackSignUpPage-700x656.png" alt="pom in selenium" /></p>
<p><strong>Explanation of Code</strong></p>
<ul>
<li><p><strong>Code Line-10 to 14:</strong> Identifying elements present on <a target="_blank" href="https://www.browserstack.com/users/sign_up">BrowserStack SignUp Page</a> such as <strong>header</strong> and <strong>Get Started</strong> button</p>
</li>
<li><p><strong>Code Line-20 to 35:</strong> Performing actions on identified objects on the BrowserStack SignUp Page</p>
</li>
</ul>
<p><strong>Code Snippet</strong></p>
<pre><code class="lang-plaintext">package browserStackPages;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class BrowserStackSignUpPage {
WebDriver driver;
By Header = By.xpath("//h1");
By userName = By.xpath("//*[@id='user_full_name']");
By businessEmail = By.xpath("//*[@id='user_email_login']");
By password = By.xpath("//*[@id='user_password']");

public BrowserStackSignUpPage(WebDriver driver) {
this.driver = driver;
}

public void veryHeader() {
String getheadertext = driver.findElement(Header).getText().trim();
assertEquals("Create a FREE Account", getheadertext);
}
public void enterFullName(String arg1) {
driver.findElement(userName).sendKeys(arg1);
}
public void enterBusinessEmail(String arg1) {
driver.findElement(businessEmail).sendKeys(arg1);
}
public void enterPasswrod(String arg1) {
driver.findElement(password).sendKeys(arg1);
}
}
</code></pre>
<p><strong>BrowserStackSetup Java File</strong></p>
<p><img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/BrowserStackSetup-700x623.png" alt="pom in selenium" /></p>
<p><strong>Explanation of Code</strong></p>
<ul>
<li><p><strong>Code Line-21 to 27:</strong> Setting up browser and website to execute test scripts</p>
</li>
<li><p><strong>Code Line-29 to 43:</strong> Initializing driver object to <strong>BrowserStackHomePage</strong> &amp; <strong>BrowserStackSignUpPage</strong> and performing actions on those pages</p>
</li>
</ul>
<p><strong>Code Snippet</strong></p>
<pre><code class="lang-plaintext">package browserStackSetup;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import browserStackPages.BrowserStackHomePage;
import browserStackPages.BrowserStackSignUpPage;

public class BrowserStackSetup {
String driverPath = "C:\\geckodriver.exe";
WebDriver driver;
BrowserStackHomePage objBrowserStackHomePage;
BrowserStackSignUpPage objBrowserStackSignUpPage;

@BeforeTest
public void setup() {
System.setProperty("webdriver.chrome.driver", "C:\\BrowserStack\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.browserstack.com/");
}

@Test(priority = 1)
public void navigate_to_homepage_click_on_getstarted() {
objBrowserStackHomePage = new BrowserStackHomePage(driver);
objBrowserStackHomePage.veryHeader();
objBrowserStackHomePage.clickOnGetStarted();
}

@Test(priority = 2)
public void enter_userDetails() {
objBrowserStackSignUpPage = new BrowserStackSignUpPage(driver);
objBrowserStackSignUpPage.veryHeader();
objBrowserStackSignUpPage.enterFullName("TestUser");
objBrowserStackSignUpPage.enterBusinessEmail("TestUser@gmail.com");
objBrowserStackSignUpPage.enterPasswrod("TestUserPassword");
}
}
</code></pre>
<p><a target="_blank" href="https://www.browserstack.com/users/sign_up?ref=guide-page-object-model-in-selenium-mid&amp;product=automate"><strong>Run Selenium Tests</strong></a></p>
<h3 id="heading-what-is-page-factory-in-selenium">What is Page Factory in Selenium?</h3>
<p>Page Factory is a class provided by <a target="_blank" href="https://www.browserstack.com/guide/selenium-webdriver-tutorial">Selenium WebDriver</a> to support Page Object Design patterns. In Page Factory, testers use <strong>@FindBy</strong> annotation. The <strong>initElements</strong> method is used to initialize web elements.</p>
<ul>
<li><p><strong>@FindBy</strong>: An annotation used in Page Factory to locate and declare web elements using different locators. Below is an example of declaring an element using <strong>@FindBy</strong></p>
<pre><code class="lang-plaintext">  @FindBy(id="elementId") WebElement element;
</code></pre>
<p>  Similarly, one can use <strong>@FindBy</strong> with different location strategies to find web elements and perform actions on them. Below are <a target="_blank" href="https://www.browserstack.com/guide/locators-in-selenium">locators</a> that can be used:</p>
<ul>
<li><p>ClassName</p>
</li>
<li><p>CSS</p>
</li>
<li><p>Name</p>
</li>
<li><p><a target="_blank" href="https://www.browserstack.com/guide/find-element-by-xpath-in-selenium">Xpath</a></p>
</li>
<li><p>TagName</p>
</li>
<li><p><a target="_blank" href="https://www.browserstack.com/guide/find-element-by-text-using-selenium">LinkText</a></p>
</li>
<li><p>PartialLinkText</p>
</li>
</ul>
</li>
<li><p><strong>initElements()</strong>: <strong>initElements</strong> is a static method in Page Factory class. Using the <strong>initElements</strong> method, one can initialize all the web elements located by <strong>@FindBy</strong> annotation.</p>
</li>
<li><p><strong>lazy initialization:</strong> <strong>AjaxElementLocatorFactory</strong> is a lazy load concept in Page Factory. This only identifies web elements when used in any operation or activity. The timeout of a web element can be assigned to the object class with the help of the <strong>AjaxElementLocatorFactory</strong>.</p>
</li>
<li><h4 id="heading-implementing-page-factory-in-selenium-project"><strong>Implementing Page Factory in Selenium Project</strong></h4>
<p>  This will try to use the same project used for the POM Model. It will reuse the 2-page files and implement Page Factory.</p>
<ul>
<li><p>BrowserStackHomePage</p>
</li>
<li><p>BrowserStackSignUpPage</p>
</li>
</ul>
</li>
</ul>
<p>    As discussed earlier, each of these files will only contain UI elements or Objects present on these screens along with the operations to be performed on these elements.</p>
<h4 id="heading-sample-project-structure-for-page-factory"><strong>Sample Project Structure for Page Factory</strong></h4>
<p>    The project structure will not change as the same project is being used. As already mentioned, Page Factory supports Page Object Model design pattern.</p>
<p>    <img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/POMSetUp.png" alt="page factory in selenium " /></p>
<p>    <img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/BrowserStackHomePage_PageFactory-700x605.png" alt="page factory in selenium - java file" /></p>
<p>    <strong>Explanation of Code</strong></p>
<ul>
<li><p><strong>Code Line-13 to 17:</strong> Identifying elements present on BrowserStack Home Page such as <strong>header</strong> and <strong>Get Started</strong> button using Page Factory <strong>@FindBy</strong> annotation</p>
</li>
<li><p><strong>Code Line-23 to 30:</strong> Performing actions on identified objects on the BrowserStack Home Page</p>
</li>
</ul>
<p>    <strong>Code Snippet</strong></p>
<pre><code class="lang-plaintext">    package browserStackPages;
    import static org.testng.Assert.assertEquals;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;

    public class BrowserStackHomePage {
    WebDriver driver;
    @FindBy(xpath = "//h1")
    WebElement Header;
    @FindBy(xpath = "//*[@id='signupModalButton']")
    WebElement getStarted;

    public BrowserStackHomePage(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
    }

    public void veryHeader() {
    String getheadertext = Header.getText();
    assertEquals("App &amp; Browser Testing Made Easy", getheadertext);
    }
    public void clickOnGetStarted() {
    getStarted.click();
    }
    }
</code></pre>
<p>    <img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/BrowserStackSignUpPage_PageFactory.png" alt="page factory in selenium - Sign up page" /></p>
<p>    <strong>Explanation of Code</strong></p>
<ul>
<li><p><strong>Code Line-14 to 24:</strong> Identifying elements on <a target="_blank" href="https://www.browserstack.com/users/sign_up">BrowserStack SignUp Page</a>, such as the <strong>header</strong> and <strong>Get Started</strong> button, using Page Factory <strong>@FindBy</strong> annotation.</p>
</li>
<li><p><strong>Code Line-26 to 46:</strong> Performing actions on identified objects on the BrowserStack SignUp Page</p>
</li>
</ul>
<p>    <a target="_blank" href="https://www.browserstack.com/guide/page-object-model-in-selenium#"><strong>Talk to an Expert</strong></a></p>
<p>    <strong>Code Snippet</strong></p>
<pre><code class="lang-plaintext">    package browserStackPages;
    import static org.testng.Assert.assertEquals;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;

    public class BrowserStackSignUpPage {
    WebDriver driver;

    @FindBy(xpath = "//h1")
    WebElement Header;

    @FindBy(xpath = "//*[@id='user_full_name']")
    WebElement userName;

    @FindBy(xpath = "//*[@id='user_email_login']")
    WebElement businessEmail;

    @FindBy(xpath = "//*[@id='user_password']")
    WebElement password;

    public BrowserStackSignUpPage(WebDriver driver) {
    this.driver = driver;
    PageFactory.initElements(driver, this);
    }

    public void veryHeader() {
    String getheadertext = Header.getText().trim();
    assertEquals("Create a FREE Account", getheadertext);
    }
    public void enterFullName(String arg1) {
    userName.sendKeys(arg1);
    }
    public void enterBusinessEmail(String arg1) {
    businessEmail.sendKeys(arg1);
    }
    public void enterPasswrod(String arg1) {
    password.sendKeys(arg1);
    }
    }
</code></pre>
<p>    <img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/BrowserStackSetup-700x623.png" alt="page factory in selenium - sample project" /></p>
<p>    <strong>Explanation of Code</strong></p>
<ul>
<li><p><strong>Code Line-21 to 27:</strong> Setting up of browser and website to execute our scripts</p>
</li>
<li><p><strong>Code Line-29 to 43:</strong> Initializing driver objects to BrowserStackHomePage &amp; BrowserStackSignUpPage and performing actions on those pages.</p>
</li>
</ul>
<p>    <strong>Code Snippet</strong></p>
<pre><code class="lang-plaintext">    package browserStackSetup;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;
    import browserStackPages.BrowserStackHomePage;
    import browserStackPages.BrowserStackSignUpPage;

    public class BrowserStackSetup {
    String driverPath = "C:\\geckodriver.exe";
    WebDriver driver;
    BrowserStackHomePage objBrowserStackHomePage;
    BrowserStackSignUpPage objBrowserStackSignUpPage;

    @BeforeTest
    public void setup() {
    System.setProperty("webdriver.chrome.driver", "C:\\BrowserStack\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.get("https://www.browserstack.com/");
    }

    @Test(priority = 1)
    public void navigate_to_homepage_click_on_getstarted() {
    objBrowserStackHomePage = new BrowserStackHomePage(driver);
    objBrowserStackHomePage.veryHeader();
    objBrowserStackHomePage.clickOnGetStarted();
    }

    @Test(priority = 2)
    public void enter_userDetails() {
    objBrowserStackSignUpPage = new BrowserStackSignUpPage(driver);
    objBrowserStackSignUpPage.veryHeader();
    objBrowserStackSignUpPage.enterFullName("TestUser");
    objBrowserStackSignUpPage.enterBusinessEmail("TestUser@gmail.com");
    objBrowserStackSignUpPage.enterPasswrod("TestUserPassword");
    }
    }
</code></pre>
<p>    <strong>Test Result</strong></p>
<p>    <img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2020/06/TestResults.png" alt="page object model with pagefactory in selenium " /></p>
]]></content:encoded></item><item><title><![CDATA[Contact List App]]></title><description><![CDATA[I am successfully storing contacts in dashboard data browser by this code.
public void readContacts(){
         ContentResolver cr = getContentResolver();
         Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);

...]]></description><link>https://development-of-net-banking-application.hashnode.dev/contact-list-app</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/contact-list-app</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 18:16:15 GMT</pubDate><content:encoded><![CDATA[<p>I am successfully storing contacts in dashboard data browser by this code.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">readContacts</span><span class="hljs-params">()</span></span>{
         ContentResolver cr = getContentResolver();
         Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,<span class="hljs-keyword">null</span>, <span class="hljs-keyword">null</span>, <span class="hljs-keyword">null</span>, <span class="hljs-keyword">null</span>);

         <span class="hljs-keyword">if</span> (cur.getCount() &gt; <span class="hljs-number">0</span>) {
            <span class="hljs-keyword">while</span> (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                <span class="hljs-keyword">if</span> (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) ==<span class="hljs-number">1</span>) {
                    System.out.println(name );
                    ParseObject testObject = <span class="hljs-keyword">new</span> ParseObject(<span class="hljs-string">"Contacts"</span>);

                    testObject.put(<span class="hljs-string">"names"</span>, name);

                    <span class="hljs-comment">// get the phone number</span>
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,<span class="hljs-keyword">null</span>,
                                           ContactsContract.CommonDataKinds.Phone.CONTACT_ID +<span class="hljs-string">" = ?"</span>,
                                           <span class="hljs-keyword">new</span> String[]{id}, <span class="hljs-keyword">null</span>);
                    <span class="hljs-keyword">while</span> (pCur.moveToNext()) {
                          String phone = pCur.getString(
                                 pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                         System.out.println( phone);
                        testObject.put(<span class="hljs-string">"phonenumber"</span>, phone);

                    }
                    pCur.close();
                    testObject.saveInBackground();
           }
        }
     }
  }
</code></pre>
<p>But there is no check for the duplicate contacts !</p>
<p>It stores all the contacts duplicate from sim / phone memory.</p>
<p>How can it be avoided ?</p>
<p><em>One possible method I think is to store distinct names(contact) in local database</em></p>
]]></content:encoded></item><item><title><![CDATA[Automated Testing]]></title><description><![CDATA[Manual Testing On Real Time Project - Adactin Hotel Booking AppManual Testing On Real Time Project - Adactin Hotel Booking App


Description :    Using this system user can view and check for various rooms available and simultaneously book    them by...]]></description><link>https://development-of-net-banking-application.hashnode.dev/automated-testing</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/automated-testing</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 18:07:04 GMT</pubDate><content:encoded><![CDATA[<p>Manual Testing On Real Time Project - Adactin Hotel Booking AppManual Testing On Real Time Project - Adactin Hotel Booking App</p>
<ul>
<li><ul>
<li>Description :<br />    Using this system user can view and check for various rooms available and simultaneously book<br />    them by making online payment via credit card.The system calculates the total cost on booking the services. Once the user makes the payment, system will provide online receipt to the user. User can view<br />    the room booking in an effective graphical user interface. Since room bookings will be displayed in<br />    effective graphical user interface user will get to know which rooms are booked and how many rooms<br />    are available for booking. Using this application user can select the room according to his<br />    preference.The rooms which are already will be disabled and the rooms which are available user just<br />    have to select it and then proceed to payment option.Once user makes the payment system will<br />    generate receipt and it will be sent to respective users email id and it will be reported to the admin,<br />    when user visits the hotel, he must show the receipt for the accommodation.<br />    Roles and Responsibilies :<br />    Understanding the Requirements and Functional Identified Test Scenarios required for testing.<br />    Prepared and Executed Test Cases as per System. Defect Reporting using Templates.<br />    Test Management (Test Case Execution and Defect Reporting). Extensively performed Manual Testing process to ensure the quality of the software.</li>
</ul>
</li>
<li><p><strong>TOOL FORN FRAMEWORKS:</strong></p>
</li>
<li><h2 id="heading-list-of-software-frameworks-tools-and-libraries">**List of Software Frameworks, Tools, and Libraries</h2>
<p>  **</p>
<p>  <strong>1.</strong> <a target="_blank" href="https://nodejs.org/en/"><strong>NodeJS</strong></a></p>
<p>  Nodejs, the javascript runtime framework built on the Chrome V8 engine leads the list. It’s asynchronous, event-driven, and based on a non-blocking I/O model, which makes it the right fit for applications that are data-intensive and render output to the users in real-time. </p>
<p>  Launched in 2009, this javascript framework for backend development is a part of various corporate software applications. Some of the popular names (amongst many) include GoDaddy, Walmart, Yahoo, Netflix, Linkedin, Groupon, etc.</p>
<ul>
<li><p>NodeJS leverages javascript benefits. The Input/Output operations in Javascript are non-blocking, which makes it competent to handle multiple, concurrent events at a point. That is why, applications built with Nodejs uses less RAM, execute operations faster, and therefore are a primary choice for apps that include heavy I/O bound workflows, such as Single Page Applications, team collaboration apps, streaming apps, etc.   </p>
</li>
<li><p>The Node Package Manager (npm) helps to manage modules in projects by downloading packages, resolving dependencies, and installing command-line utilities. Thanks to its ever-expanding community, npm is the largest ecosystem of open-source libraries in the world.   </p>
</li>
<li><p>Javascript has been used for front-end development since its introduction. When Nodejs developers (for backend) collaborate with front-end developers, managing lines of code, spotting, and fixing bugs become efficient. </p>
</li>
</ul>
</li>
</ul>
<p>    For the incredible range of benefits that Nodejs comes integrated with, businesses are <a target="_blank" href="https://appdevelopment.daffodilsw.com/nodejs-application-development-company">hiring Nodejs developers</a> to raise the performance standards of software applications. </p>
<p>    <strong>2.</strong> <a target="_blank" href="https://angularjs.org/"><strong>AngularJS</strong></a></p>
<p>    AngularJs is a structural framework, meant for building dynamic web pages. Introduced by Google in 2012, this javascript framework for front-end development is great for building Single Page Applications (SPAs). </p>
<ul>
<li><p>With AngularJS, there is flexibility in development. Developers with expertise in HTML can use the language with new HTML syntax with new attributes (called directives) to extend the functionality of web pages.   </p>
</li>
<li><p>AngularJS is an MVC framework, where synchronization between the model and view happens with two-way data binding. The changes made in the model data are immediately reflected in the view (and vice versa). This automated and immediate updation ascertains that the components of the framework are updated all the time.   </p>
</li>
<li><p>The AngularJS directives can be used to create reusable components. A component enables hiding complex DOM structure, CSS, and behavior. That way, you can separately focus on how an application looks and how it works, separately.</p>
</li>
</ul>
<p>    <strong>3.</strong> <a target="_blank" href="https://reactjs.org/"><strong>React</strong></a></p>
<ul>
<li><p>ReactJS is a javascript library by Facebook for building user interfaces (for web). With its launch in 2013, ReactJS outpowered its contenders in the row and one of the major reasons was the Virtual DOM. Instead of directly manipulating the DOM, ReactJS save two copies of the changes made; one in the original DOM and another in Virtual DOM. Whenever a React component is changed, both the DOMs are compared and only the changes in the view are updated. This ensures that the changes in the view are rendered faster.  </p>
</li>
<li><p>React Native is a javascript software framework by Facebook for building mobile-friendly user interfaces. React Native enables building cross-platform native apps using Javascript that would have otherwise required Objective-C or Swift. Popular <a target="_blank" href="https://appdevelopment.daffodilsw.com/blog/10-amazing-apps-that-are-built-using-react-native">apps that are built using React Native</a> showcase the acceptance that this JS framework for mobile app development has. </p>
</li>
</ul>
<p>    <strong>4.</strong> <a target="_blank" href="https://netcore.in/"><strong>.NET Core</strong></a></p>
<p>    .NET Core is an open-source, next-gen .NET framework by Microsoft. If the application needs to run on multiple OS platforms (Windows, Linux, macOS), then .NET is a good fit. </p>
<p>    This software framework, .NET Core, proves to be a compatible choice for server-based applications when there are cross-platform app requirements when there are high-performance and scalable systems, involves the use of Docker containers, microservices, etc. </p>
<p>    <strong>5.</strong> <a target="_blank" href="https://spring.io/"><strong>Spring</strong></a></p>
<p>    Another example in the software framework list is Spring.  </p>
<p>    Spring is an open-source application framework for developing Java enterprise applications. It offers an infrastructure that enables developing well-structured and easily-testable java applications, web applications, applets, etc.</p>
<ul>
<li><p>Spring is a dependency injection framework (Inversion of Control) that assigns dependencies to the object during runtime. When standalone programs start, the main program starts, create dependencies and executes appropriate methods. This makes the code loosely coupled and thus easy to maintain.  </p>
</li>
<li><p>Spring framework is built-in with templates for Hibernate, JPA, JDBC, JTA, etc., saving developers from writing too much code.  </p>
</li>
<li><p>Spring provides a consistent programming model, which is usable in any environment. There are web applications that don't even need high-end servers and can be run on a web container like Jetty or Tomcat. Also, not all applications are server-side applications. Spring provides application models that insulate application code from environment details like JNDI, making code less dependent on its run time context. </p>
</li>
</ul>
<p>    <strong>6.</strong> <a target="_blank" href="https://www.djangoproject.com/"><strong>Django</strong></a></p>
<p>    Django is an open-source framework for web app development, written in Python. It follows the model-view-template (MVT) architectural pattern and is a fit for complex, database-driven applications. </p>
<p>    Django, launched in 2005 is a part of well-known websites today, including Instagram, Nextdoor, BitBucket, Disqus, Pinterest, and more. The <a target="_blank" href="https://insights.daffodilsw.com/blog/top-10-python-frameworks-for-web-application-development">Python-based software framework</a> supports reusability, rapid development, less code, and low coupling. The main Django distribution includes a number of applications, which simplifies development to an extent. This includes an extensible authentication system, built-in mitigation for web attacks (like SQL injection, cross-site scripting, password cracking, etc.). </p>
<p>    <strong>7.</strong> <a target="_blank" href="https://www.tensorflow.org/"><strong>TensorFlow</strong></a></p>
<p>    Tensorflow is one of the most popular software framework examples for <a target="_blank" href="https://www.daffodilsw.com/ai-application-development-solutions">AI application development</a>. </p>
<p>    Tensorflow is a machine learning framework by Google, meant for creating Deep Learning models. Deep Learning, a subclass of ML deals with Artificial Neural Networks (ANN) that makes a system learn and progressively improve with experiences. Tensorflow is based on a computational graph, having a network of nodes. Each node is an operation, running some function, which could a simple mathematical calculation or complex multivariate analytics. </p>
<p>    While a number of brands are putting in their trust in this ML framework (like Dropbox, Twitter, Uber, Intel, etc.), Google itself utilizes the power of TensorFlow in many of its services. This includes Google Recognition, Google Search, Google Photos, etc. This mature framework is a part of small and large-scale AI development projects. </p>
<p>    “According to Stack Overflow survey results 2018, machine learning is one of the important trends in the software development industry. Languages and frameworks associated with ML are on rising, and developers working in these areas are high in demand.” </p>
<p>    <strong>8.</strong> <a target="_blank" href="https://www.xamarin.com/"><strong>Xamarin</strong></a></p>
<p>    Cross-platform native apps are the future of mobile app development, and Xamarin is one of them. Xamarin offers an edge over the proprietary and hybrid development models as it allows the development of full-fledged mobile apps using a single language, i.e. C#. Moreover, Xamarin offers a class library and runtime environment, which is similar to the rest of the development platforms (iPhone, Android, and Windows). If you want to develop reliable and scalable cross-platform applications then <a target="_blank" href="https://www.daffodilsw.com/hire-xamarin-developers/">hire Xamarin developers</a> from us to accelerate your project delivery.</p>
<ul>
<li><p>Xamarin offers a less complex environment for development, as compared to other native cross frameworks. When it's about code sharing, cost-saving, and ease at maintenance, Xamarin for cross-platform native development proves to be a better option over hybrid apps. Less memory utilization, faster loading of datasets, less CPU time utilization are some of the benefits that Xamarin offers over hybrid app development.   </p>
</li>
<li><p>As compared to other cross-platform native development platforms in the market, Xamarin has the most stable and updated SDK. Also, Xamarin integrates well with Azure, which gives the benefit of developing advanced and secure cloud backend for the apps. </p>
</li>
</ul>
<p>    <strong>9.</strong> <a target="_blank" href="http://sparkjava.com/"><strong>Spark</strong></a></p>
<p>    Spark is an open-source, micro framework, meant for creating web applications in Kotlin and Java. Spark was open-sourced in the year 2011 and its new version Spark 2.0 was launched for use in the year 2014, which was primarily centered on the Java 8 lambda philosophy.</p>
<p>    The Java Virtual Machine (JVM), one of the biggest programming ecosystems, has got a number of java web frameworks. However, java web development has always been cumbersome. For those who love JVM but don’t want the frameworks or verbose code, Spark is the solution.</p>
<p>    <strong>10.</strong> <a target="_blank" href="http://cordova.apache.org/"><strong>Cordova</strong></a></p>
<p>    Apache Cordova (formerly Phonegap) is a hybrid app development framework that uses HTML, CSS, and Javascript for building mobile apps. It extends the features of HTML and Javascript so that they work in accordance with a specific device. As a result, the application developed is neither native (as the layout rendering is done through web views, instead of native platform UI framework), nor it is a web app (as they are wrapped as mobile apps for distribution). Therefore, with Cordova, hybrid app development is possible, which saves time, effort, and cost with code sharing for multiple platforms.</p>
<p>    There is a long list of tools, software frameworks, and cloud services that are available to augment the performance of Cordova. Some of the popular names include Visual Studio, Ionic, Framework7, Monaca, Mobiscroll, etc. Considering the potential that Cordova brings in, the contributors to this software development framework are some of the tech giants, including Adobe, Microsoft, Blackberry, IBM, Intel, etc.</p>
<p>    <strong>11.</strong> <a target="_blank" href="http://hadoop.apache.org/"><strong>Hadoop</strong></a></p>
<p>    Hadoop is an open-source framework by Apache that stores and distributes large data sets across several servers, operating parallel. One of the major benefits of Hadoop over traditional RDBMS is its cost-effective system for storing giant data sets.</p>
<p>    The core of Apache Hadoop is Hadoop Distributed File System (the storage part) and Mapreduce Programming Model (the processing part). Hadoop is written in Java, the widely used language by developers, which makes it easy for developers to handle tasks and process data efficiently. Hadoop’s MapReduce enables processing terabytes of data in minutes; it’s that fast!</p>
<p>    <strong>12.</strong> <a target="_blank" href="http://pytorch.org/"><strong>Torch/ PyTorch</strong></a></p>
<p>    PyTorch is a machine learning library for Python. PyTorch is primarily created to overcome the challenges of its predecessor, Torch. Owing to the unwillingness among the developers to learn the language Lua, Torch was unable to experience the success that Tensorflow did, in spite of being the mainstay for computer vision for years. It enables writing new neural layers in Python by using libraries and packages like Cython and Numba.</p>
]]></content:encoded></item><item><title><![CDATA[Manual Testing Task:]]></title><description><![CDATA[Epics for Net banking app: Using project management tool Jira
Creation of 5 Epics with user stories post that backlog creation and created 3 sprints and moved to sprint execution.
https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64y...]]></description><link>https://development-of-net-banking-application.hashnode.dev/manual-testing-task</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/manual-testing-task</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 17:40:10 GMT</pubDate><content:encoded><![CDATA[<p><strong>Epics for Net banking app: Using project management tool Jira</strong></p>
<p>Creation of 5 Epics with user stories post that backlog creation and created 3 sprints and moved to sprint execution.</p>
<p><a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU">https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU</a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit"><strong>Sprint review:</strong></a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit">A sprint review is an informal meeting held at the end of a sprint, during which the team shows what was accomplished, wh</a>ile the stakeholders provide feedback. I<a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit">t’s a collaborative working session rather than a one-sided presentation.</a></p>
<h2 id="heading-scruhttpsdocsgooglecomdocumentd1tca-nrotjegdz7tom4ln6qmcuvqev64yg3yteijhueditm"><a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit"><strong>Scru</strong></a><strong>m:</strong></h2>
<p><a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit">Scrum is a management framework that teams use to self-organize and work towards a common goa</a>l. It describes a set of meetings, tools, and roles for efficient project delivery. Much like a sports team practicing for a big match, Scrum practices allow <a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit">teams to self-manage, learn from experience, and adapt to change. Software teams use S</a>crum to solve complex problems cost effectively and sustainably.</p>
<p><strong>Sprint retrospective:</strong></p>
<p>A sprint retrospective is a meeting typically held at the end of an Agile development cycle to review what went well, what could be improved upon, and any other issues that need to be addressed in order to become more effective as a te<a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit">am.</a></p>
<p><a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit"><strong>A Scrum Release Planning</strong> is the creation process of a very high-level plan for multiple Scrum Spr</a>ints <strong>.</strong> It is a guideline that reflects expectations about which features will be implemented and when they are completed. It also serves as a base to monitor pro<a target="_blank" href="https://docs.google.com/document/d/1T__cA-NroTjEgDZ7Tom4LN6QmcUvQeV64yG3YtEijHU/edit">gress within the project. Releases can be intermediate deliveries done during t</a>he project or the final delivery at the end.</p>
]]></content:encoded></item><item><title><![CDATA[Selenium Web Component]]></title><description><![CDATA[How to Maximize Chrome Window in Selenium Webdriver using Java
Run Selenium Tests on real Chrome Browser and Devices for a first hand user like experience
How to Maximize Chrome Window in Selenium Webdriver using Java
When browser windows are maximiz...]]></description><link>https://development-of-net-banking-application.hashnode.dev/selenium-web-component-1</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/selenium-web-component-1</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 17:29:27 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-how-to-maximize-chrome-window-in-selenium-webdriver-using-java">How to Maximize Chrome Window in Selenium Webdriver using Java</h1>
<p>Run Selenium Tests on real Chrome Browser and Devices for a first hand user like experience</p>
<h2 id="heading-how-to-maximize-chrome-window-in-selenium-webdriver-using-java-1">How to Maximize Chrome Window in Selenium Webdriver using Java</h2>
<p>When browser windows are maximized, it reduces the chances of <a target="_blank" href="https://www.browserstack.com/guide/run-selenium-test-script">Selenium scripts</a> missing out on web elements they must interact with during <a target="_blank" href="https://www.browserstack.com/guide/automation-testing-tutorial">automated tests</a>. It is possible that certain elements may not be visible to or recognized by <a target="_blank" href="https://www.browserstack.com/selenium">Selenium</a> if the browser window is not in a maximized state.</p>
<p>Maximizing a browser window at first also provides better visibility to the QAs for the test cases being executed. Thus QAs must consider maximizing the browser window as a best practice.</p>
<p>As Chrome is the most widely used browser, this article will explore two simple ways to maximize a Chrome window in <a target="_blank" href="https://www.browserstack.com/guide/selenium-webdriver-tutorial">Selenium Webdriver</a> using Java.</p>
<h3 id="heading-1-use-the-maximize-method-from-webdriverwindow-interface">1. Use the maximize() method from WebDriver.Window Interface</h3>
<p>The code snippet below implements four basic scenarios:</p>
<ol>
<li><p>Launching the Chrome browser</p>
</li>
<li><p>Navigating to the desired URL</p>
</li>
<li><p>Maximizing the Chrome Window</p>
</li>
<li><p>Terminating the browser</p>
<p> <strong>Code:</strong></p>
<pre><code class="lang-plaintext"> import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.chrome.ChromeDriver;

 public class Max {

 public static void main(String args[]) throws InterruptedException
 {
 System.setProperty("&lt;Path of the ChromeDriver&gt;");
 WebDriver driver = new ChromeDriver();

 // Navigate to a website
 driver.get("https://www.browserstack.com/");

 //Mazimize current window
 driver.manage().window().maximize();

 //Delay execution for 5 seconds to view the maximize operation
 Thread.sleep(5000);

 //Close the browser
 driver.quit();
 } 
 }
</code></pre>
<p> Successful execution of the selenium script above will do the following: launch the Chrome browser, navigate to maximize the Chrome Window, and wait for five seconds.</p>
<p> <strong>Code:</strong></p>
<pre><code class="lang-plaintext"> import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.chrome.ChromeDriver;

 public class Max {

 public static void main(String args[]) throws InterruptedException
 {

 System.setProperty("&lt;Path of the ChromeDriver&gt;");

 ChromeOptions options = new ChromeOptions();
 options.addArguments("start-maximized");

 WebDriver driver = new ChromeDriver(options);

 // Navigate to a website
 driver.get("https://www.browserstack.com/")

 //Close the browser
 driver.quit();
 } 
 }
</code></pre>
<p> Successful execution of the script above will do the following: launch the Chrome browser in maximized mode and navigate to the Browserstack website.</p>
</li>
</ol>
<ol start="2">
<li><h1 id="heading-drag-and-drop-in-selenium"><strong>Drag and Drop in Selenium</strong></h1>
<h2 id="heading-what-is-drag-and-drop-action">What is Drag and Drop Action?</h2>
<p> This is an action performed with a <strong><em>mouse</em></strong> when a user moves (<em>drags</em>) a web element and then places (<em>drops</em>) it into an alternate area.</p>
<p> <em>E.g. This is a very common action used in Windows Explorer while moving any file from one folder to another. Here, the user selects any file in the folder, drags it to the desired folder and just drops it.</em></p>
<p> In Gmail, a file can be just dragged and dropped in new mail to send as an attachment like below:</p>
<p> <img src="https://toolsqa.com/gallery/selnium%20webdriver/1.Drag-and-Drop-Action.png" alt="Drag-and-Drop-Action" /></p>
<p> Once the file is moved to compose an email, you can see it as an attachment. At the bottom, it is displayed that the file we dragged from windows to Gmail, is now attached as an attachment.</p>
<p> <img src="https://toolsqa.com/gallery/selnium%20webdriver/2.Drag-and-Drop-in-selenium.png" alt="Drag-and-Drop-in-selenium" /></p>
<p> In automation test scripts at various instances, the same action needs to be emulated:</p>
<ul>
<li><em>Select some element on the web page, drag it and then place it on the alternate area.</em></li>
</ul>
</li>
</ol>
<p>    To perform the drag-drop action through a Selenium script, there is no direct drag-drop method available in <em>WebElement interface.</em> Unlike other commands like <em>click(), sendKeys()</em> there is nothing available for drag and drop. Here, we leverage the <a target="_blank" href="https://www.toolsqa.com/selenium-webdriver/actions-class-in-selenium/"><strong><em>Actions class</em></strong></a></p>
<ol start="3">
<li><p>which provides various methods of emulating such complex interactions.</p>
<p> So, here are the methods Actions class provides for Drag-Drop action:</p>
<ol>
<li><p><strong><em>dragAndDrop(WebElementsource*</em></strong>, WebElement target)*</p>
</li>
<li><p><strong><em>dragAndDropBy*</em></strong>(WebElementsource, int xOffset, int yOffset)*</p>
</li>
</ol>
</li>
</ol>
<h2 id="heading-drag-and-drop-in-selenium-1">Drag and Drop in Selenium</h2>
<p>    <strong><em>dragAndDrop(WebElement source, WebElement target):</em></strong> This method performs left click, hold the click to hold the source element, moves to the location of the target element and then releases the mouse click.</p>
<p>    Let’s see how to use Action class methods to perform drag-drop action:</p>
<p>    <strong><em>First, instantiate an Actions class:</em></strong></p>
<p>    <em>Actions actions = new Actions(driver);</em></p>
<p>    As you can see, the <em>dragAndDrop(WebElement source, WebElement target)</em> method has two arguments to pass. One is a source web element and another is target web element.  This source web element is any web element that needs to be dragged. Target web element is any web element on which dragged object needs to be placed or dropped. To find the source and target element use the below command:</p>
<p>    <em>WebElement source = driver.findElement(Any By strategy &amp; locator);</em></p>
<p>    <em>WebElement target = driver.findElement(Any By strategy &amp; locator);</em></p>
<p>    Here, you can use any By strategy to locate the WebElement like find element by its <em>id, name attribute, etc.</em> To know more about all By strategies.</p>
<p>    Now, when we have got the actions class object and the element as well, just invoke <strong><em>perform()</em></strong> method for the drag &amp; drop:</p>
<p>    <em>actions.dragAndDrop(source,target).perform();</em></p>
<p>    Let’s see what happens internally when invoke the <em>perform()</em> method above:</p>
<ul>
<li><p><strong><em>Click And Hold Action:</em></strong> <em>dragAndDrop() method first performs click-and-hold at the location of the source element</em></p>
</li>
<li><p><strong><em>Move Mouse Action:</em></strong> <em>Then source element gets moved to the location of the target element</em></p>
</li>
<li><p><strong><em>Button Release Action:</em></strong> <em>Finally, it releases the mouse</em></p>
</li>
<li><p><strong><em>Build:</em></strong> <em>build() method is used to generate a composite action containing all actions. But if you observe, we have not invoked it in our above command. The build is executed in the perform method internally</em></p>
</li>
<li><p><strong><em>Perform:</em></strong> <em>perform() method performs the actions we have specified. But before that, it internally invokes build() method first. After the build, the action is performed.</em></p>
<ol start="3">
<li><h3 id="heading-1-setup-mongodb"><strong>1. Setup MongoDB:</strong></h3>
<ul>
<li><p>Install <a target="_blank" href="https://www.guvi.in/blog/guide-to-data-modeling-in-mongodb/">MongoDB</a> on your system or use a cloud-based MongoDB service like <a target="_blank" href="https://www.mongodb.com/products/platform/atlas-database">MongoDB Atlas.</a></p>
</li>
<li><p>Make sure MongoDB is running and accessible.</p>
</li>
</ul>
</li>
</ol>
</li>
</ul>
<h3 id="heading-2-setup-backend-nodejs-with-expressjs"><strong>2. Setup Backend (Node.js with Express.js):</strong></h3>
<ul>
<li><p>Create a new directory for your backend (e.g., <code>backend</code>) and navigate into it.</p>
</li>
<li><p>Initialize a <a target="_blank" href="https://www.guvi.in/blog/guide-for-nodejs-as-backend/">Node.js</a> project using <code>npm init -y</code>.</p>
</li>
<li><p>Install necessary dependencies by running <code>npm install express mongoose bcryptjs jsonwebtoken cors</code>.</p>
</li>
<li><p>Create the project structure as described earlier.</p>
</li>
<li><p>Implement the backend code (<code>server.js</code>, <code>User.js</code>, <code>auth.js</code>) according to the provided code snippets.</p>
</li>
</ul>
<h3 id="heading-3-setup-frontend-reactjs"><strong>3. Setup Frontend (React.js):</strong></h3>
<ul>
<li><p>Create a new directory for your frontend (e.g., <code>frontend</code>) and navigate into it.</p>
</li>
<li><p>Initialize a <a target="_blank" href="https://www.guvi.in/blog/prerequisites-for-reactjs/">React.js</a> project using <code>npx create-react-app .</code> (assuming you’re already inside the <code>frontend</code> directory).</p>
</li>
<li><p>Install necessary dependencies by running <code>npm install axios react-router-dom</code>.</p>
</li>
<li><p>Create the project structure as described earlier.</p>
</li>
<li><p>Implement the frontend code (<code>Login.js</code>, <code>App.js</code>) according to the provided code snippets.</p>
</li>
</ul>
<p>            <em>You should also learn to</em> <a target="_blank" href="https://www.guvi.in/blog/build-a-search-filter-component-in-react/"><strong><em>Build a Search Component in React</em></strong></a><em>.</em></p>
<h3 id="heading-4-connect-backend-with-frontend"><strong>4. Connect Backend with Frontend:</strong></h3>
<ul>
<li><p>In <code>Login.js</code>, update the API URL in the Axios request to match your backend server URL (e.g., <code>http://localhost:5000/api/auth/login</code>).</p>
</li>
<li><p>Ensure that the backend server is running when you make requests from the front end.</p>
</li>
</ul>
<p>            <em>Also Explore:</em> <a target="_blank" href="https://www.guvi.in/blog/interaction-between-frontend-and-backend/"><strong><em>Interaction Between Frontend and Backend: Important Process That You Should Know</em></strong></a></p>
<p>            Now, let’s actually start implementing it and look at the coding part:</p>
<p>            <strong>For the Backend Part:</strong></p>
<p>            Let’s look at the coding part for the backend implementation:</p>
<p>            <strong>1. Setup Project Structure:</strong></p>
<pre><code class="lang-plaintext">            /backend 

              |- package.json  

              |- server.js 

              |- /models 

                |- User.js 

              |- /routes   

                |- auth.js
</code></pre>
<p>            <strong>2. Install Dependencies:</strong></p>
<p>            npm install express mongoose bcryptjs jsonwebtoken cors</p>
<p>            <strong>3. Create</strong> <code>server.js</code>:</p>
<pre><code class="lang-plaintext">            const express = require('express'); 

            const mongoose = require('mongoose'); 

            const cors = require('cors'); 

            const bodyParser = require('body-parser'); 

            const authRoutes = require('./routes/auth'); 

            const app = express(); 

            app.use(cors()); 

            app.use(bodyParser.json()); 

            mongoose.connect('mongodb://localhost:27017/mern_login', { 

                useNewUrlParser: true, 

                useUnifiedTopology: true, 

            }); 

            app.use('/api/auth', authRoutes); 

            const PORT = process.env.PORT || 5000; 

            app.listen(PORT, () =&gt; { 

                console.log(`Server is running on port ${PORT}`); 

            });
</code></pre>
<p>            <strong>4. Create</strong> <code>User.js</code> in <code>/models</code> directory:</p>
<pre><code class="lang-plaintext">            const mongoose = require('mongoose'); 

            const userSchema = new mongoose.Schema({ 

                username: { 

                    type: String, 

                    required: true, 

                    unique: true, 

                },  

                password: { 

                    type: String, 

                    required: true, 

                }, 

            }); 

            module.exports = mongoose.model('User', userSchema);
</code></pre>
<p>            <strong>5. Create</strong> <code>auth.js</code> in <code>/routes</code> directory:</p>
<pre><code class="lang-plaintext">            const express = require('express'); 

            const router = express.Router(); 

            const bcrypt = require('bcryptjs'); 

            const jwt = require('jsonwebtoken'); 

            const User = require('../models/User'); 

            router.post('/login', async (req, res) =&gt; { 

                const { username, password } = req.body; 

                try { 

                    const user = await User.findOne({ username }); 

                    if (!user) { 

                        return res.status(400).json({ message: 'Invalid username or password' }); 

                    } 

                const isMatch = await bcrypt.compare(password, user.password); 

                if (!isMatch) { 

                    return res.status(400).json({ message: 'Invalid username or password' }); 

                } 

                const token = jwt.sign({ id: user._id }, 'secretkey', { expiresIn: '1h' }); 

                res.json({ token }); 

                } catch (error) { 

                console.error(error); 

                res.status(500).send('Server Error'); 

                } 

            }); 

            module.exports = router;
</code></pre>
<p>            <strong>Also Read:</strong> <a target="_blank" href="https://www.guvi.in/blog/how-to-setup-react-router-v6-tutorial/"><strong>How to Setup React Router v6?</strong></a></p>
<p>            <strong>For the Frontend Part:</strong></p>
<p>            Let’s look at the coding part for the frontend implementation:</p>
<p>            <strong>1. Setup Project Structure:</strong></p>
<pre><code class="lang-plaintext">            /frontend 

                |- package.json 

                |- /src 

                    |- /components 

                        |- Login.js 

                    |- App.js 

                    |- index.js
</code></pre>
<p>            <strong>2. Install Dependencies:</strong></p>
<pre><code class="lang-plaintext">            npx create-react-app frontend 

            cd frontend

            npm install axios react-router-dom
</code></pre>
<p>            <strong>3. Create</strong> <code>Login.js</code> in <code>/src/components</code> directory:</p>
<pre><code class="lang-plaintext">            import React, { useState } from 'react'; 

            import axios from 'axios'; 

                const Login = ({ history }) =&gt; { 

                const [username, setUsername] = useState(''); 

                const [password, setPassword] = useState(''); const handleSubmit = async (e) =&gt; { 

                    e.preventDefault(); 

                    try { 

                        const response = await axios.post('http://localhost:5000/api/auth/login', { 

                            username, 

                            password, 

                    }); 

                    localStorage.setItem('token', response.data.token); 

                    history.push('/dashboard'); 

                } catch (error) { 

                  console.error(error); 

                } 

            }; 

            return ( 

                &lt;div&gt; 

                    &lt;h2&gt;Login&lt;/h2&gt; 

                    &lt;form onSubmit={handleSubmit}&gt; 

                        &lt;div&gt; 

                            &lt;label&gt;Username:&lt;/label&gt; 

                                &lt;input type="text" value={username} onChange={(e) =&gt; setUsername(e.target.value)} /&gt; 

                        &lt;/div&gt; 

                        &lt;div&gt; 

                            &lt;label&gt;Password:&lt;/label&gt; 

                            &lt;input type="password" value={password} onChange={(e) =&gt; setPassword(e.target.value)} /&gt; 

                        &lt;/div&gt; 

                        &lt;button type="submit"&gt;Login&lt;/button&gt; 

                     &lt;/form&gt; 

                 &lt;/div&gt; 

                ); 

            }; 

            export default Login;
</code></pre>
<p>            <strong>4. Modify</strong> <code>App.js</code> in <code>/src</code> directory:</p>
<pre><code class="lang-plaintext">            import React from 'react'; 

            import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 

            import Login from './components/Login'; 

            function App() { 

                return ( 

                    &lt;Router&gt; 

                        &lt;div className="App"&gt; 

                            &lt;Switch&gt; 

                                &lt;Route exact path="/" component={Login} /&gt; 

                             &lt;/Switch&gt; 

                        &lt;/div&gt; 

                    &lt;/Router&gt; 

                ); 

            }
</code></pre>
<h3 id="heading-5-run-the-application"><strong>5. Run the Application:</strong></h3>
<ul>
<li><p>Start MongoDB server.</p>
</li>
<li><p>Run the backend server: <code>node server.js</code> inside the <code>/backend</code> directory.</p>
</li>
<li><p>Run the frontend server: <code>npm start</code> inside the <code>/frontend</code> directory.</p>
</li>
<li><p>Open your web browser and navigate to <code>http://localhost:3000</code> to access the login page.</p>
</li>
<li><p>Test the login functionality by entering valid and invalid credentials.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[1. Write a Selenium script to automate  the following task:]]></title><description><![CDATA[How to Open Chrome Browser Using Selenium in Java?
Selenium is an open-source popular web-based automation tool. The major advantage of using selenium is, it supports all browsers like Google Chrome, Microsoft Edge, Mozilla Firefox, and Safari, works...]]></description><link>https://development-of-net-banking-application.hashnode.dev/1-write-a-selenium-script-to-automate-the-following-task</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/1-write-a-selenium-script-to-automate-the-following-task</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 17:11:11 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-how-to-open-chrome-browser-using-selenium-in-java">How to Open Chrome Browser Using Selenium in Java?</h1>
<p>Selenium is an open-source popular web-based automation tool. The major advantage of using selenium is, it supports all browsers like Google Chrome, Microsoft Edge, Mozilla Firefox, and Safari, works on all major OS, and its scripts are written in various languages i.e Java, Python, JavaScript, C#, etc. We will be working with Java. In this article, let us consider a test case in which we will try to automate the following scenarios in the Google Chrome browser.</p>
<ul>
<li><p>Launch Chrome browser.</p>
</li>
<li><p>Maximize the browser.</p>
</li>
<li><p>Open URL: <a target="_blank" href="https://www.geeksforgeeks.org/"><strong>https://www.geeksforgeeks.org/</strong></a></p>
</li>
</ul>
<p>For invoking the chrome browser, we need the Eclipse IDE, Selenium Grid(version 4), and Chrome web Driver.</p>
<h3 id="heading-installation">Installation</h3>
<ul>
<li><p><strong>Eclipse IDE:</strong> Before downloading also make sure that your device has Java JDK. If you don’t have, install Java refer to this: <a target="_blank" href="https://www.geeksforgeeks.org/how-to-download-and-install-java-for-64-bit-machine/"><strong>How to Download and Install Java for 64 bit machine?</strong></a>. And install Eclipse IDE by referring to this article <a target="_blank" href="https://www.geeksforgeeks.org/how-to-install-eclipse-ide-for-java/"><strong>Eclipse IDE for Java Developers.</strong></a> </p>
</li>
<li><p><strong>Selenium:</strong> Download the Selenium latest stable version <a target="_blank" href="https://github.com/SeleniumHQ/selenium/releases/download/selenium-4.1.0/selenium-server-4.1.2.jar"><strong>here</strong></a>. </p>
</li>
<li><p><strong>Web Driver:</strong> Web drivers is a package to interact with a web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. Download Chrome Driver according to your Chrome Version <a target="_blank" href="https://sites.google.com/chromium.org/driver/downloads"><strong>here</strong></a>. </p>
</li>
</ul>
<h3 id="heading-step-by-step-implementation">Step by Step Implementation</h3>
<p><strong>Step 1:</strong></p>
<p>Open the Eclipse IDE and create a new Java project. Right-click on the “src” folder and create a new Class File from New &gt; Class. Give the Class name and click on the “Finish” button.</p>
<p><strong>Step 2:</strong></p>
<p>Add Selenium JAR file into the Java Project. Right-click on Class name and Select “Build Path” and select &gt; configure build path</p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20220211142042/S2.png" alt /></p>
<p>Then select Libraries &gt; Classpath &gt; and Click “Add External JAR’s”, now add the Selenium Jar and click “Apply and Finish”</p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20220211135828/s1.png" alt /></p>
<h1 id="heading-seleniumhttpswwwgeeksforgeeksorgselenium-basics-components-features-uses-and-limitations-is-an-open-source-web-automation-tool-that-is-used-to-automate-web-browser-testing-the-major-advantage-of-using-selenium-is-that-it-supports-all-major-web-browsers-and-works-on-all-major-operating-systems-and-it-supports-writing-scripts-on-various-languages-such-as-java-javascript-c-and-python-etc-while-automating-a-webpage-we-are-required-to-fetch-and-check-all-the-available-links-present-on-the-webpage-in-this-article-we-will-learn-to-get-all-the-available-links-present-on-a-page-using-tagname"><a target="_blank" href="https://www.geeksforgeeks.org/selenium-basics-components-features-uses-and-limitations/"><strong>Selenium</strong></a> is an open-source Web-Automation tool that is used to automate web Browser Testing. The major advantage of using selenium is, that it supports all major web browsers and works on all major Operating Systems, and it supports writing scripts on various languages such as Java,  JavaScript, C# and Python, etc. While automating a webpage, we are required to fetch and check all the available links present on the webpage, In this article, we will learn to get all the available links present on a page using <strong>“TagName”</strong>.</h1>
<p>As we know all the links are of type <strong>anchor tag “a” in HTML</strong>. For Example,</p>
<blockquote>
<p><em>&lt;a href=”geeksforgeeks.org”&gt;geeksforgeeks&lt;/a&gt;</em></p>
</blockquote>
<p><strong>Table of Content</strong></p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/how-to-get-all-available-links-on-the-page-using-selenium-in-java/#how-to-fetch-all-the-links-on-a-webpage"><strong>How to fetch all the links on a webpage?</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/how-to-get-all-available-links-on-the-page-using-selenium-in-java/#sample-code-example-to-scrape-links"><strong>Sample Code Example to Scrape Links</strong></a></p>
</li>
</ul>
<h2 id="heading-how-to-fetch-all-the-links-on-a-webpage">How to fetch all the links on a webpage?</h2>
<ul>
<li><p>Navigate to the webpage.</p>
</li>
<li><p>Get the list of WebElements with the TagName “a”.</p>
</li>
<li><p>List&lt;WebElement&gt; links=driver.findElements(By.tagName(“a”));</p>
</li>
<li><p>Iterate through the List of WebElements.</p>
</li>
<li><p>Print the link text.</p>
</li>
</ul>
<h2 id="heading-sample-code-example-to-scrape-links">Sample Code Example to Scrape Links</h2>
<p>In this example, we are navigating to the URL “https://www.geeksforgeeks.org/” and print the link text of all available links on the page.</p>
<pre><code class="lang-plaintext">public class Geeks {

    WebDriverManager.chromedriver().setup();
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://www.geeksforgeeks.org/");

    // Get all the available Links
    List&lt;WebElement&gt; links
        = driver.findElements(By.tagName("a"));

    // Iterating through all the Links and printing link
    // text
    for (WebElement link : links) {
        System.out.println(link.getText());
    }

    driver.close();
}
</code></pre>
<h3 id="heading-output">Output:</h3>
<p>This program will get all the Links in the List of WebElements and print all the link texts.</p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20221219112200/Screenshot-2022-12-19-112054-768.png" alt /></p>
]]></content:encoded></item><item><title><![CDATA[Create a class called "Person"with attributes "Name"and "age"]]></title><description><![CDATA[Java: Create and print Person objects


Write a Java program to create a class called "Person" with a name and age attribute. Create two instances of the "Person" class, set their attributes using the constructor, and print their name and age.

Insta...]]></description><link>https://development-of-net-banking-application.hashnode.dev/create-a-class-called-personwith-attributes-nameand-age</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/create-a-class-called-personwith-attributes-nameand-age</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 16:47:36 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-java-create-and-print-person-objects"><strong>Java: Create and print Person objects</strong></h1>
<hr />
<ol>
<li>Write a Java program to create a class called "Person" with a name and age attribute. Create two instances of the "Person" class, set their attributes using the constructor, and print their name and age.</li>
</ol>
<p>Instance monitoring software</p>
<p><strong>Sample Solution:</strong></p>
<p><strong>Java Code:</strong></p>
<pre><code class="lang-java"> <span class="hljs-comment">// Define the Person class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-comment">// Declare a private variable to store the name of the person</span>
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-comment">// Declare a private variable to store the age of the person</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-comment">// Constructor for the Person class that initializes the name and age variables</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-comment">// Set the name variable to the provided name parameter</span>
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-comment">// Set the age variable to the provided age parameter</span>
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-comment">// Method to retrieve the name of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Return the value of the name variable</span>
        <span class="hljs-keyword">return</span> name;
    }

    <span class="hljs-comment">// Method to retrieve the age of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Return the value of the age variable</span>
        <span class="hljs-keyword">return</span> age;
    }

    <span class="hljs-comment">// Method to set the name of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-comment">// Set the name variable to the provided name parameter</span>
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-comment">// Method to set the age of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-comment">// Set the age variable to the provided age parameter</span>
        <span class="hljs-keyword">this</span>.age = age;
    }
}
</code></pre>
<p>The above class has two private attributes: name and age, and a constructor that initializes these attributes with the values passed as arguments. It also has a getter method to access the attributes.</p>
<p>Method documentation tool</p>
<pre><code class="lang-java"><span class="hljs-comment">// Define the Main class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-comment">// Define the main method which is the entry point of the program</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create an instance of the Person class with the name "Ean Craig" and age 11</span>
        Person person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Ean Craig"</span>, <span class="hljs-number">11</span>);
        <span class="hljs-comment">// Create another instance of the Person class with the name "Evan Ross" and age 12</span>
        Person person2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Evan Ross"</span>, <span class="hljs-number">12</span>);

        <span class="hljs-comment">// Print the name and age of person1 to the console</span>
        System.out.println(person1.getName() + <span class="hljs-string">" is "</span> + person1.getAge() + <span class="hljs-string">" years old."</span>);
        <span class="hljs-comment">// Print the name and age of person2 to the console</span>
        System.out.println(person2.getName() + <span class="hljs-string">" is "</span> + person2.getAge() + <span class="hljs-string">" years old.\n"</span>);

        <span class="hljs-comment">// Modify the age of person1 using the setter methods</span>
        person1.setAge(<span class="hljs-number">14</span>);
        <span class="hljs-comment">// Modify the name and age of person2 using the setter methods</span>
        person2.setName(<span class="hljs-string">"Lewis Jordan"</span>);
        person2.setAge(<span class="hljs-number">12</span>);
        System.out.println(<span class="hljs-string">"Set new age and name:"</span>);
        <span class="hljs-comment">// Print the updated name and age of person1 to the console</span>
        System.out.println(person1.getName() + <span class="hljs-string">" is now "</span> + person1.getAge() + <span class="hljs-string">" years old."</span>);
        <span class="hljs-comment">// Print the updated name and age of person2 to the console</span>
        System.out.println(person2.getName() + <span class="hljs-string">" is now "</span> + person2.getAge() + <span class="hljs-string">" years old."</span>);
    }
}
</code></pre>
<p>In the above example, we create two instances of the "Person" class, set their attributes with the constructor, and print their name and age using the getter methods. We also modify the attributes using the setter methods and print the updated values.</p>
<p>Instance monitoring software</p>
<p>Sample Output:</p>
<pre><code class="lang-plaintext">Ean Craig is 11 years old.
Evan Ross is 12 years old.

Set new age and name:
Ean Craig is now 14 years old.
Lewis Jordan is now 12 years old.
</code></pre>
<p><strong>Flowchart:</strong></p>
<p><img src="https://www.w3resource.com/w3r_images/java-oop-exercise-flowchart-1.png" alt="Flowchart: Java  OOP Exercises: Create and print Person objects." /></p>
<ol start="2">
<li><strong>Java employee details program</strong></li>
</ol>
<p>In <a target="_blank" href="https://www.javatpoint.com/java-tutorial">Java</a>, the most searching program is of employee details. An employee is an entity that can have several attributes like id, name, and department, etc. In order to create a java employee details program, we need to create a class for the employee entity and create properties of the employees.</p>
<p>We will create the getter and setter for getting and setting the values of the properties. In the main class, we will create the object of the Employee class, and by using its object, we will access the properties of the Employee class.</p>
<p>The code of the employee details program is very easy to understand. Let's implement the code of the above theory.</p>
<p><strong>EmployeeDetails.java</strong></p>
<ol>
<li><p><strong>package</strong> JavaTpoint.JavaObjectToJSON;  </p>
</li>
<li><p>//Creating Employee class  </p>
</li>
<li><p><strong>class</strong> EmployeeDetails {  </p>
</li>
<li><p>//Creating properties of Employee class  </p>
</li>
<li><p><strong>int</strong> emp_id, salary;  </p>
</li>
<li><p>String name, address, department, email;  </p>
</li>
</ol>
<ol start="8">
<li><p>//Getter and setters for getting and setting properties  </p>
</li>
<li><p><strong>public</strong> <strong>int</strong> getEmp_id() {  </p>
</li>
<li><p><strong>return</strong> emp_id;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>void</strong> setEmp_id(<strong>int</strong> emp_id) {  </p>
</li>
<li><p><strong>this</strong>.emp_id = emp_id;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>int</strong> getSalary() {  </p>
</li>
<li><p><strong>return</strong> salary;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>void</strong> setSalary(<strong>int</strong> salary) {  </p>
</li>
<li><p><strong>this</strong>.salary = salary;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> String getName() {  </p>
</li>
<li><p><strong>return</strong> name;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>void</strong> setName(String name) {  </p>
</li>
<li><p><strong>this</strong>.name = name;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> String getAddress() {  </p>
</li>
<li><p><strong>return</strong> address;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>void</strong> setAddress(String address) {  </p>
</li>
<li><p><strong>this</strong>.address = address;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> String getDepartment() {  </p>
</li>
<li><p><strong>return</strong> department;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>void</strong> setDepartment(String department) {  </p>
</li>
<li><p><strong>this</strong>.department = department;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> String getEmail() {  </p>
</li>
<li><p><strong>return</strong> email;  </p>
</li>
<li><p>}  </p>
</li>
<li><p><strong>public</strong> <strong>void</strong> setEmail(String email) {  </p>
</li>
<li><p><strong>this</strong>.email = email;  </p>
</li>
<li><p>}  </p>
</li>
</ol>
<ol start="46">
<li><p>//Overriding toString() method  </p>
</li>
<li><p>@Override  </p>
</li>
<li><p><strong>public</strong> String toString() {  </p>
</li>
<li><p><strong>return</strong> "Employee [emp_id = " + emp_id + ", salary = " + salary + ", name = " + name + ", address = " + address  </p>
</li>
<li><ul>
<li>", department = " + department + ", email = " + email + "]";  </li>
</ul>
</li>
<li><p>}  </p>
</li>
</ol>
<ol start="53">
<li><p>}  </p>
</li>
<li><p>//Creating main class  </p>
</li>
<li><p><strong>public</strong> <strong>class</strong> Employee{  </p>
</li>
<li><p>//main() method start  </p>
</li>
<li><p><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String args[]) {  </p>
</li>
</ol>
<ol start="59">
<li><p>//Creating object of EmployeeDetails class  </p>
</li>
<li><p>EmployeeDetails emp = <strong>new</strong> EmployeeDetails();  </p>
</li>
<li><p>//Setting values to the properties  </p>
</li>
<li><p>emp.setEmp_id(101);  </p>
</li>
<li><p>emp.setName("Emma Watson");  </p>
</li>
<li><p>emp.setDepartment("IT");  </p>
</li>
<li><p>emp.setSalary(15000);  </p>
</li>
<li><p>emp.setAddress("New Delhi");  </p>
</li>
<li><p>emp.setEmail("Emmawatson123@gmail.com");  </p>
</li>
</ol>
<ol start="69">
<li><p>//Showing Employee details  </p>
</li>
<li><p>System.out.println(emp);  </p>
</li>
</ol>
<ol start="72">
<li><p>//Getting salary using getter  </p>
</li>
<li><p><strong>int</strong> sal = emp.getSalary();  </p>
</li>
<li><p><strong>int</strong> increment = 0;  </p>
</li>
<li><p>//Incrementing salary based on condition  </p>
</li>
<li><p><strong>if</strong> ((sal &gt;=1000) &amp;&amp; (sal &lt;=1500))  </p>
</li>
<li><p>{  </p>
</li>
<li><p>//incrementing salary 2%  </p>
</li>
<li><p>increment += (sal * 2)/100;  </p>
</li>
<li><p>sal = sal+increment;  </p>
</li>
</ol>
<ol start="82">
<li><p>emp.setSalary(sal);  </p>
</li>
<li><p>System.out.println("\n Salary is incremented \n");  </p>
</li>
<li><p>System.out.println(emp);  </p>
</li>
</ol>
<ol start="86">
<li><p>}<strong>else</strong> <strong>if</strong> ((sal &gt;=1500) &amp;&amp; (sal &lt;=20000)){  </p>
</li>
<li><p>//incrementing salary 5%  </p>
</li>
<li><p>increment += (sal * 5)/100;  </p>
</li>
<li><p>sal = sal+increment;  </p>
</li>
</ol>
<ol start="91">
<li><p>emp.setSalary(sal);  </p>
</li>
<li><p>System.out.println("\n Salary is incremented \n");  </p>
</li>
<li><p>System.out.println(emp);  </p>
</li>
<li><p>}<strong>else</strong> {  </p>
</li>
<li><p>System.out.println("\n Salary is not incremented \n");  </p>
</li>
<li><p>System.out.println(emp);  </p>
</li>
<li><p>}         </p>
</li>
<li><p>}  </p>
</li>
<li><p>}  </p>
</li>
</ol>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">Employee [emp_id = 101, salary = 15000, name = Emma Watson, address = New Delhi, department = IT, email = Emmawatson123@gmail.com]
Salary is incremented
Employee [emp_id = 101, salary = 15750, name = Emma Watson, address = New Delhi, department = IT, email = Emmawatson123@gmail.com]
</code></pre>
<p>In the above program, we have created limited properties of the Employee class. You can create the number of properties for the Employee class. In the above code, we not only show the employee details but also access the property value using the setters. We update the value of a property based on the conditions too.</p>
<hr />
<ol start="3">
<li><h1 id="heading-create-a-circle-class-with-area-and-circumference-calculation"><strong>Create a Circle class with area and circumference calculation</strong></h1>
<hr />
<p> Write a Java program to create a class called "Circle" with a radius attribute. You can access and modify this attribute. Calculate the area and circumference of the circle.</p>
<p> <strong>Sample Solution:</strong></p>
<p> <strong>Java Code:</strong></p>
<pre><code class="lang-java"> <span class="hljs-comment">// Define the Circle class</span>
 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> </span>{
     <span class="hljs-comment">// Declare a private variable to store the radius of the circle</span>
     <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> radius;

     <span class="hljs-comment">// Constructor for the Circle class that initializes the radius variable</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Circle</span><span class="hljs-params">(<span class="hljs-keyword">double</span> radius)</span> </span>{
         <span class="hljs-comment">// Set the radius variable to the provided radius parameter</span>
         <span class="hljs-keyword">this</span>.radius = radius;
     }

     <span class="hljs-comment">// Method to retrieve the radius of the circle</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">getRadius</span><span class="hljs-params">()</span> </span>{
         <span class="hljs-comment">// Return the value of the radius variable</span>
         <span class="hljs-keyword">return</span> radius;
     }

     <span class="hljs-comment">// Method to set the radius of the circle</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setRadius</span><span class="hljs-params">(<span class="hljs-keyword">double</span> radius)</span> </span>{
         <span class="hljs-comment">// Set the radius variable to the provided radius parameter</span>
         <span class="hljs-keyword">this</span>.radius = radius;
     }

     <span class="hljs-comment">// Method to calculate and return the area of the circle</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">getArea</span><span class="hljs-params">()</span> </span>{
         <span class="hljs-comment">// Calculate the area using the formula π * radius^2 and return the result</span>
         <span class="hljs-keyword">return</span> Math.PI * radius * radius;
     }

     <span class="hljs-comment">// Method to calculate and return the circumference of the circle</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">getCircumference</span><span class="hljs-params">()</span> </span>{
         <span class="hljs-comment">// Calculate the circumference using the formula 2 * π * radius and return the result</span>
         <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> * Math.PI * radius;
     }
 }
</code></pre>
<p> Radius Measurement Tool</p>
<p> The above "Circle" class has a private attribute 'radius', a constructor that initializes this attribute with the value passed as an argument, and getter and setter methods to access and modify this attribute. It also calculates circle area and circumference using methods.</p>
<pre><code class="lang-java"> <span class="hljs-comment">// Define the Main class</span>
 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
     <span class="hljs-comment">// Define the main method which is the entry point of the program</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
         <span class="hljs-comment">// Declare an integer variable r and initialize it with the value 5</span>
         <span class="hljs-keyword">int</span> r = <span class="hljs-number">5</span>;
         <span class="hljs-comment">// Create an instance of the Circle class with the radius r</span>
         Circle circle = <span class="hljs-keyword">new</span> Circle(r);
         <span class="hljs-comment">// Print the radius of the circle to the console</span>
         System.out.println(<span class="hljs-string">"Radius of the circle is "</span> + r);
         <span class="hljs-comment">// Print the area of the circle to the console</span>
         System.out.println(<span class="hljs-string">"The area of the circle is "</span> + circle.getArea());
         <span class="hljs-comment">// Print the circumference of the circle to the console</span>
         System.out.println(<span class="hljs-string">"The circumference of the circle is "</span> + circle.getCircumference());
         <span class="hljs-comment">// Update the radius variable r to 8</span>
         r = <span class="hljs-number">8</span>;
         <span class="hljs-comment">// Set the radius of the circle to the new value of r</span>
         circle.setRadius(r);
         <span class="hljs-comment">// Print the updated radius of the circle to the console</span>
         System.out.println(<span class="hljs-string">"\nRadius of the circle is "</span> + r);
         <span class="hljs-comment">// Print the updated area of the circle to the console</span>
         System.out.println(<span class="hljs-string">"The area of the circle is now "</span> + circle.getArea());
         <span class="hljs-comment">// Print the updated circumference of the circle to the console</span>
         System.out.println(<span class="hljs-string">"The circumference of the circle is now "</span> + circle.getCircumference());
     }
 }
</code></pre>
<p> In the above main() function, we create an instance of the "Circle" class with a radius of 5, and call its methods to calculate the area and circumference. We then modify the radius using the setter method and print the updated area and circumference.</p>
<p> Sample Output:</p>
<pre><code class="lang-plaintext"> Radius of the circle is 5
 The area of the circle is 78.53981633974483
 The circumference of the circle is 31.41592653589793

 Radius of the circle is 8
 The area of the circle is now 201.06192982974676
 The circumference of the circle is now 50.26548245743669
</code></pre>
<p> <strong>Flowchart:</strong></p>
<p> <img src="https://www.w3resource.com/w3r_images/java-oop-exercise-flowchart-4.png" alt="Flowchart: Java  OOP Exercises: Create a Circle class with area and circumference calculation." /></p>
<p> 4. Write a Java program to create a class known as "BankAccount" with methods called deposit() and withdraw(). Create a subclass called SavingsAccount that overrides the withdraw() method to prevent withdrawals if the account balance falls below one hundred.</p>
<p> <strong>Sample Solution:</strong></p>
<p> <strong>Java Code:</strong></p>
<pre><code class="lang-java"> <span class="hljs-comment">// BankAccount.java</span>
 <span class="hljs-comment">// Parent class BankAccount</span>

 <span class="hljs-comment">// Declare the BankAccount class</span>
 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BankAccount</span> </span>{
     <span class="hljs-comment">// Private field to store the account number</span>
     <span class="hljs-keyword">private</span> String accountNumber;

     <span class="hljs-comment">// Private field to store the balance</span>
     <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> balance;

     <span class="hljs-comment">// Constructor to initialize account number and balance</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BankAccount</span><span class="hljs-params">(String accountNumber, <span class="hljs-keyword">double</span> balance)</span> </span>{
         <span class="hljs-keyword">this</span>.accountNumber = accountNumber;
         <span class="hljs-keyword">this</span>.balance = balance;
     }

     <span class="hljs-comment">// Method to deposit an amount into the account</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deposit</span><span class="hljs-params">(<span class="hljs-keyword">double</span> amount)</span> </span>{
         <span class="hljs-comment">// Increase the balance by the deposit amount</span>
         balance += amount;
     }

     <span class="hljs-comment">// Method to withdraw an amount from the account</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(<span class="hljs-keyword">double</span> amount)</span> </span>{
         <span class="hljs-comment">// Check if the balance is sufficient for the withdrawal</span>
         <span class="hljs-keyword">if</span> (balance &gt;= amount) {
             <span class="hljs-comment">// Decrease the balance by the withdrawal amount</span>
             balance -= amount;
         } <span class="hljs-keyword">else</span> {
             <span class="hljs-comment">// Print a message if the balance is insufficient</span>
             System.out.println(<span class="hljs-string">"Insufficient balance"</span>);
         }
     }

     <span class="hljs-comment">// Method to get the current balance</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">getBalance</span><span class="hljs-params">()</span> </span>{
         <span class="hljs-comment">// Return the current balance</span>
         <span class="hljs-keyword">return</span> balance;
     }
 }
</code></pre>
<pre><code class="lang-java"> <span class="hljs-comment">// SavingsAccount.java</span>
 <span class="hljs-comment">// Child class SavingsAccount</span>

 <span class="hljs-comment">// Declare the SavingsAccount class, inheriting from BankAccount</span>
 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SavingsAccount</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BankAccount</span> </span>{
     <span class="hljs-comment">// Constructor to initialize account number and balance</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SavingsAccount</span><span class="hljs-params">(String accountNumber, <span class="hljs-keyword">double</span> balance)</span> </span>{
         <span class="hljs-comment">// Call the parent class constructor</span>
         <span class="hljs-keyword">super</span>(accountNumber, balance);
     }

     <span class="hljs-comment">// Override the withdraw method from the parent class</span>
     <span class="hljs-meta">@Override</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(<span class="hljs-keyword">double</span> amount)</span> </span>{
         <span class="hljs-comment">// Check if the withdrawal would cause the balance to drop below $100</span>
         <span class="hljs-keyword">if</span> (getBalance() - amount &lt; <span class="hljs-number">100</span>) {
             <span class="hljs-comment">// Print a message if the minimum balance requirement is not met</span>
             System.out.println(<span class="hljs-string">"Minimum balance of $100 required!"</span>);
         } <span class="hljs-keyword">else</span> {
             <span class="hljs-comment">// Call the parent class withdraw method</span>
             <span class="hljs-keyword">super</span>.withdraw(amount);
         }
     }
 }
</code></pre>
<pre><code class="lang-java"> <span class="hljs-comment">// Main.java</span>
 <span class="hljs-comment">// Main class</span>

 <span class="hljs-comment">// Define the Main class</span>
 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
     <span class="hljs-comment">// Main method, entry point of the program</span>
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
         <span class="hljs-comment">// Print message to indicate creation of a BankAccount object</span>
         System.out.println(<span class="hljs-string">"Create a Bank Account object (A/c No. BA1234) with initial balance of $500:"</span>);
         <span class="hljs-comment">// Create a BankAccount object (A/c No. "BA1234") with initial balance of $500</span>
         BankAccount BA1234 = <span class="hljs-keyword">new</span> BankAccount(<span class="hljs-string">"BA1234"</span>, <span class="hljs-number">500</span>);

         <span class="hljs-comment">// Print message to indicate deposit action</span>
         System.out.println(<span class="hljs-string">"Deposit $1000 into account BA1234:"</span>);
         <span class="hljs-comment">// Deposit $1000 into account BA1234</span>
         BA1234.deposit(<span class="hljs-number">1000</span>);
         <span class="hljs-comment">// Print the new balance after deposit</span>
         System.out.println(<span class="hljs-string">"New balance after depositing $1000: $"</span> + BA1234.getBalance());

         <span class="hljs-comment">// Print message to indicate withdrawal action</span>
         System.out.println(<span class="hljs-string">"Withdraw $600 from account BA1234:"</span>);
         <span class="hljs-comment">// Withdraw $600 from account BA1234</span>
         BA1234.withdraw(<span class="hljs-number">600</span>);
         <span class="hljs-comment">// Print the new balance after withdrawal</span>
         System.out.println(<span class="hljs-string">"New balance after withdrawing $600: $"</span> + BA1234.getBalance());

         <span class="hljs-comment">// Print message to indicate creation of a SavingsAccount object</span>
         System.out.println(<span class="hljs-string">"\nCreate a SavingsAccount object (A/c No. SA1234) with initial balance of $450:"</span>);
         <span class="hljs-comment">// Create a SavingsAccount object (A/c No. "SA1234") with initial balance of $450</span>
         SavingsAccount SA1234 = <span class="hljs-keyword">new</span> SavingsAccount(<span class="hljs-string">"SA1234"</span>, <span class="hljs-number">450</span>);

         <span class="hljs-comment">// Withdraw $300 from SA1234</span>
         SA1234.withdraw(<span class="hljs-number">300</span>);
         <span class="hljs-comment">// Print the balance after attempting to withdraw $300</span>
         System.out.println(<span class="hljs-string">"Balance after trying to withdraw $300: $"</span> + SA1234.getBalance());

         <span class="hljs-comment">// Print message to indicate creation of another SavingsAccount object</span>
         System.out.println(<span class="hljs-string">"\nCreate a SavingsAccount object (A/c No. SA1000) with initial balance of $300:"</span>);
         <span class="hljs-comment">// Create a SavingsAccount object (A/c No. "SA1000") with initial balance of $300</span>
         SavingsAccount SA1000 = <span class="hljs-keyword">new</span> SavingsAccount(<span class="hljs-string">"SA1000"</span>, <span class="hljs-number">300</span>);

         <span class="hljs-comment">// Print message to indicate withdrawal action</span>
         System.out.println(<span class="hljs-string">"Try to withdraw $250 from SA1000!"</span>);
         <span class="hljs-comment">// Withdraw $250 from SA1000 (balance falls below $100)</span>
         SA1000.withdraw(<span class="hljs-number">250</span>);
         <span class="hljs-comment">// Print the balance after attempting to withdraw $250</span>
         System.out.println(<span class="hljs-string">"Balance after trying to withdraw $250: $"</span> + SA1000.getBalance());
     }
 }
</code></pre>
<p> Output:</p>
<pre><code class="lang-plaintext"> Create a Bank Account object (A/c No. BA1234) with initial balance of $500:
 Deposit $1000 into account BA1234:
 New balance after depositing $1000: $1500.0
 Withdraw $600 from account BA1234:
 New balance after withdrawing $600: $900.0

 Create a SavingsAccount object (A/c No. SA1234) with initial balance of $450:
 Balance after trying to withdraw $300: $150.0

 Create a SavingsAccount object (A/c No. SA1000) with initial balance of $300:
 Try to withdraw $250 from SA1000!
 Minimum balance of $100 required!
 Balance after trying to withdraw $250: $300.0
</code></pre>
<p> <strong>Explanation:</strong></p>
<p> The BankAccount class has a constructor that takes account number and balance as arguments. It also has methods to deposit and withdraw money, and to check the account balance.</p>
<p> The SavingsAccount class is a subclass of BankAccount and overrides the withdraw() method. It checks if the account balance falls below one hundred before allowing a withdrawal. The method prints an error message if the balance is below one hundred. If the balance is greater than or equal to one hundred, the method calls the withdraw() method of the superclass to withdraw.</p>
<p> In Main() method -</p>
<p> The main method begins by creating an instance of the BankAccount class with an account number of "BA1234" and an initial balance of $500. It then deposits $1000 into the account and displays the new balance. It then withdraws $600 from the account and displays the new balance.</p>
<p> Next, the method creates an instance of the SavingsAccount class with an account number of "SA1234" and an initial balance of $450. It then attempts to withdraw $300 from the account and displays the new balance. Since the balance remains above the minimum $150 balance required for the account, the withdrawal is successful.</p>
<p> Finally, the method creates another instance of the SavingsAccount class with an account number of "SA1000" and an initial balance of $300. It then attempts to withdraw $250 from the account, which would bring the balance below the minimum balance required for the account. The method displays the new balance after the attempted withdrawal, which should still be $300 since the withdrawal was unsuccessful.</p>
<p> <strong>Flowchart:</strong></p>
<p> <img src="https://www.w3resource.com/w3r_images/java-inheritance-exercise-5.png" alt="Flowchart: Parent class BankAccount." /></p>
</li>
</ol>
<p>    <img src="https://www.w3resource.com/w3r_images/java-inheritance-exercise-5-a.png" alt="Flowchart: Child class SavingsAccount." /></p>
<p>    <img src="https://www.w3resource.com/w3r_images/java-inheritance-exercise-5-b.png" alt="Flowchart: Main class." /></p>
]]></content:encoded></item><item><title><![CDATA[Java Program to Handle Divide By Zero and Multiple Exceptions]]></title><description><![CDATA[Java Program to Handle Divide By Zero and Multiple Exceptions
Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program.
Handling Multiple excepti...]]></description><link>https://development-of-net-banking-application.hashnode.dev/java-program-to-handle-divide-by-zero-and-multiple-exceptions</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/java-program-to-handle-divide-by-zero-and-multiple-exceptions</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 16:19:36 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-java-program-to-handle-divide-by-zero-and-multiple-exceptions">Java Program to Handle Divide By Zero and Multiple Exceptions</h1>
<p><strong>Exceptions</strong> These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program.</p>
<p><strong>Handling Multiple exceptions:</strong> There are two methods to handle multiple exceptions in java.</p>
<ol>
<li><p>Using a Single try-catch block try statement allows you to define a block of code to be tested for errors, and we can give exception objects to the catch blow because this all the exceptions inherited by the Exception class.</p>
</li>
<li><p>The second method is to create individual catch blocks for the different exception handler.</p>
</li>
</ol>
<p><strong>Hierarchy of the exceptions:</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20201020172955/ExceptionUntitledDiagram.png" alt /></p>
<p><strong>Divide by zero:</strong> This Program throw Arithmetic exception because of due any number divide by 0 is undefined in Mathematics. </p>
<table><tbody><tr><td><p><code>// Java Program to Handle Divide By Zero Exception</code></p></td></tr></tbody></table>

<p><strong>Output:</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20201027132930/divideByZeroError.jpg" alt="divideByZeroError" /></p>
<p><strong>Handling of Divide by zero exception:</strong> Using try-Catch Block </p>
<table><tbody><tr><td><p><code>// Java Program to Handle Divide By Zero Exception</code></p></td></tr></tbody></table>

<p><strong>Output:</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20201027133200/divideByZeroException.jpg" alt="Divide by zero exception handle" /></p>
<p><strong>Multiple Exceptions</strong> (ArithmeticException and IndexoutOfBound Exception)</p>
<ol>
<li><p>Combination of two Exception using the | operator is allowed in Java.</p>
</li>
<li><p>As soon as the first exception occurs it gets thrown at catch block.</p>
</li>
<li><p>Check of expression is done by precedence compiler check rule from right to left of the expression.</p>
</li>
</ol>
<table><tbody><tr><td><p><code>// Java Program to Handle multiple exception</code></p></td></tr></tbody></table>

<p><strong>Output:</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20201027134148/multipleException.jpg" alt /></p>
<p><strong>Explanation:</strong> Here combination of ArrayIndexOutOfBounds and Arithmetic exception occur, but only Arithmetic exception is thrown, Why?</p>
<p>According to the precedence compiler check <strong>number[10]=30/0</strong> from right to left. That’s why 30/0 to throw ArithmeticException object and the handler of this exception executes Zero cannot divide any number.</p>
<p><strong>Another Method of Multiple Exception:</strong> we can combine two Exception using the | operator and either one of them executes according to the exception occurs.</p>
<table><tbody><tr><td><p><code>// Java Program to Handle multiple exception</code></p></td></tr></tbody></table>

<p><strong>Output:</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20201027134734/multipleExceptionUsingOr.jpg" alt /></p>
<h1 id="heading-2write-the-code-array-index-out-of-bounds-exception-in-java">2.Write the code Array Index Out Of Bounds Exception in Java</h1>
<p>In Java, <strong>ArrayIndexOutOfBoundsException</strong> is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program. It occurs when we try to access the element out of the index we are allowed to, i.e<strong>. index &gt;= size of the array.</strong></p>
<p>Java supports the creation and manipulation of <a target="_blank" href="https://www.geeksforgeeks.org/data-structures/#Array"><strong>arrays</strong></a> as a data structure. The index of an array is an integer value that has a value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then Java throws an <strong>ArrayIndexOutOfBounds Exception</strong>. This is unlike C/C++, where no index of the bound check is done.</p>
<p><strong>Example 1:</strong> Here, we are <strong><em>trying to access the index which is greater than or equal to the array length</em></strong>.</p>
<p>1</p>
<pre><code class="lang-plaintext">// Java program to show ArrayIndexOutOfBoundsException
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// when the index is greater than or equal to array length
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">public class GFG {
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">    public static void main(String[] args)
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        // taking array of integers
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        int a[] = { 1, 2, 3, 4, 5 };
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        for (int i = 0; i &lt;= a.length; i++)
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">            System.out.println(a[i]);
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Runtime Error Throws an Exception:</strong> </p>
<blockquote>
<p><em>Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5<br />at GFG.main(GFG.java:11)</em></p>
</blockquote>
<p>Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum index value can be 4, but in our program, it is going till 5 and thus the exception.</p>
<p><strong>Example 2:</strong> Here, we are <strong><em>trying to access the index of array which is negative</em></strong>.</p>
<p>1</p>
<pre><code class="lang-plaintext">// Java program to show ArrayIndexOutOfBoundsException
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// when we access the negative index of array
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">public class GFG {
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">    public static void main(String[] args)
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        // taking array of integers
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        int a[] = { 1, 2, 3 };
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        // accessing the negative index of array
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">        System.out.println(a[-2]);
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Run-Time Exception:</strong></p>
<blockquote>
<p><em>Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index -2 out of bounds for length 3<br />at GFG.main(GFG.java:12)</em></p>
</blockquote>
<h2 id="heading-handling-arrayindexoutofboundsexception-in-java">Handling ArrayIndexOutOfBoundsException in Java</h2>
<p>To handle ArrayIndexOutOfBoundsException, make sure that index of array is within the valid range. You can also use the <a target="_blank" href="https://www.geeksforgeeks.org/for-each-loop-in-java/"><strong>enhanced for-loop</strong></a> to automatically handle this exception.</p>
<p><strong>Example 1:</strong> Here, we are checking whether the index is valid or not by taking array length with in the index range i.e. [0, n-1]</p>
<p>1</p>
<pre><code class="lang-plaintext">// Java program to handle ArrayIndexOutOfBoundsException
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// by taking array index within valid range
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">public class GFG {
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">    public static void main(String[] args)
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        // taking array of integers
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        int a[] = { 1, 2, 3, 4, 5 };
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        // here, we have remove equal to sign
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">        for (int i = 0; i &lt; a.length; i++)
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">            System.out.println(a[i]);
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">1
2
3
4
5
</code></pre>
<p><strong>Example 2:</strong> Here, we are <strong><em>using enhanced for loop</em></strong> that automatically handles the accessing of array’s index</p>
<p>1</p>
<pre><code class="lang-plaintext">// Java program to handle ArrayIndexOutOfBoundsException
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// by using enhanced for loop
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">public class GFG {
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">    public static void main(String[] args)
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        // taking array of integers
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        int a[] = { 1, 2, 3, 4, 5 };
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        // using enhanced for loop
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">        for (int e : a) {
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">            System.out.println(e);
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">1
2
3
4
5
</code></pre>
<p><strong>Example 3:</strong> Consider enclosing your code inside a <a target="_blank" href="https://www.geeksforgeeks.org/flow-control-in-try-catch-finally-in-java/"><strong>try-catch</strong></a> statement and manipulate the exception accordingly. As mentioned, Java won’t let you access an invalid index and will definitely throw an ArrayIndexOutOfBoundsException. However, we should be careful inside the block of the catch statement because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.</p>
<p>1</p>
<pre><code class="lang-plaintext">// Java program to handle ArrayIndexOutOfBoundsException
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// by using using try-catch block
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">public class GFG {
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">    public static void main(String[] args)
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        // taking array of integers
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        int a[] = { 1, 2, 3, 4, 5 };
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        // using try catch block
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">        try {
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">            for (int i = 0; i &lt;= a.length; i++)
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">                System.out.print(a[i] + " ");
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">        catch (Exception e) {
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">            System.out.println("\nException Caught");
</code></pre>
<p>18</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>19</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>20</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">1 2 3 4 5 
Exception Caught
</code></pre>
<ol start="3">
<li><p><strong>Create custom exceptions using the Exception in Java</strong></p>
<p> We have a series of predefined exceptions in Java. Many times, we need to create our own Exception for handling errors. We used the custom exception for customizing the exceptions as per the user need.</p>
<ol>
<li><p>Let's take some examples of the Exception class and understand how we can create our own Exception in Java.</p>
<p> <a target="_blank" href="http://CustomExceptionExample1.java"><strong>CustomExceptionExample1.java</strong></a></p>
<ol>
<li><p>// import required classes and packages  </p>
</li>
<li><p><strong>package</strong> javaTpoint.MicrosoftJava;  </p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<ol start="4">
<li><strong>import</strong> java.util.Scanner;  </li>
</ol>
<ol start="6">
<li><p>// create class InvalidAgeException by extending Exception class for create invalid age exception  </p>
</li>
<li><p>@SuppressWarnings("serial")  </p>
</li>
<li><p><strong>class</strong> InvalidAgeException  <strong>extends</strong> Exception    </p>
</li>
<li><p>{    </p>
</li>
<li><p>// parameterized constructor that accepts only detail message  </p>
</li>
<li><p><strong>public</strong> InvalidAgeException (String message)    </p>
</li>
<li><p>{    </p>
</li>
<li><p>// calling parent Exception class constructor    </p>
</li>
<li><p><strong>super</strong>(message);    </p>
</li>
<li><p>}    </p>
</li>
<li><p>}    </p>
</li>
</ol>
<ol start="18">
<li><p>// create CustomExceptionExample1 class that uses custom exception InvalidAgeException    </p>
</li>
<li><p><strong>public</strong> <strong>class</strong> CustomExceptionExample1    </p>
</li>
<li><p>{    </p>
</li>
</ol>
<ol start="22">
<li><p>// create method checkEligibility() to check whether the given is valid for exam or not  </p>
</li>
<li><p><strong>static</strong> <strong>void</strong> checkEligibility (<strong>int</strong> age) <strong>throws</strong> InvalidAgeException  </p>
</li>
<li><p>{      </p>
</li>
<li><p>// use conditional statement to check age  </p>
</li>
<li><p><strong>if</strong>(age &lt; 18){    </p>
</li>
<li><p>// we throw InvalidAgeException when the age is less than 18    </p>
</li>
<li><p><strong>throw</strong> <strong>new</strong> InvalidAgeException("You are not eligible for the exam.");   </p>
</li>
<li><p>}<strong>else</strong> {     </p>
</li>
<li><p>System.out.println("You are eligible for the exam.");     </p>
</li>
<li><p>}        </p>
</li>
<li><p>}      </p>
</li>
</ol>
<ol start="34">
<li><p>// main() method start    </p>
</li>
<li><p><strong>public</strong> <strong>static</strong> <strong>void</strong> main(String args[])    </p>
</li>
<li><p>{    </p>
</li>
<li><p>// create scanner class object to take input from user  </p>
</li>
<li><p>Scanner scan = <strong>new</strong> Scanner(<a target="_blank" href="http://System.in">System.in</a>);  </p>
</li>
</ol>
<ol start="40">
<li><p>// declare variable age to store the user input  </p>
</li>
<li><p><strong>int</strong> age;  </p>
</li>
</ol>
<ol start="43">
<li><p>// take input from the user  </p>
</li>
<li><p>System.out.println("Please enter your age:");  </p>
</li>
<li><p>age = scan.nextInt();  </p>
</li>
</ol>
<ol start="47">
<li>scan.close();  </li>
</ol>
<ol start="49">
<li><p><strong>try</strong>    </p>
</li>
<li><p>{    </p>
</li>
<li><p>// call method checkEligibility() to check whether the user is eligible for exam or not   </p>
</li>
<li><p>checkEligibility(age);    </p>
</li>
<li><p>}    </p>
</li>
<li><p><strong>catch</strong> (InvalidAgeException exception)    </p>
</li>
<li><p>{    </p>
</li>
<li><p>System.out.println("We found an excaption:");    </p>
</li>
</ol>
<ol start="58">
<li><p>// printing the message from InvalidAgeException object    </p>
</li>
<li><p>System.out.println(exception);  </p>
</li>
</ol>
<ol start="61">
<li><p>}         </p>
</li>
<li><p>}       </p>
</li>
<li><p>}    </p>
</li>
</ol>
<p>        <strong>Output:</strong></p>
<p>        <img src="https://images.javatpoint.com/core/images/exception-class-in-java.png" alt="Exception Class in Java" /></p>
<p>        <strong>Description:</strong></p>
<p>        In the above code, we create a custom exception, InvalidAgeException. We take input from the user for checking whether the user is eligible for the exam or not. We call the checkEligibility() method by passing the user input to it. The checkEligibility() method checks whether the given age is greater than 18 or not because a user having age 18+ is eligible for the exam. The method throws InvalidAgeException when it finds an age less than 18. The catch block in the main() method will handle this Exception and print the detailed message of the Exception.</p>
<ol start="4">
<li><p>Implement exception handling in a Java</p>
<h1 id="heading-javaiofilenotfoundexception-in-java">java.io.FileNotFoundException in Java</h1>
<p> <strong>java.io.FileNotFoundException</strong> which is a common exception which occurs while we try to access a file. FileNotFoundExcetion is thrown by constructors <a target="_blank" href="https://www.geeksforgeeks.org/java-io-randomaccessfile-class-method-set-1/"><strong>RandomAccessFile</strong></a>, <a target="_blank" href="https://www.geeksforgeeks.org/java-io-fileinputstream-class-java/"><strong>FileInputStream</strong></a>, and <a target="_blank" href="https://www.geeksforgeeks.org/creating-a-file-using-fileoutputstream/"><strong>FileOutputStream</strong></a>. FileNotFoundException occurs at runtime so it is a checked exception, we can handle this exception by java code, and we have to take care of the code so that this exception doesn’t occur. </p>
<p> <strong>Declaration :</strong> </p>
<pre><code class="lang-plaintext"> public class FileNotFoundException
   extends IOException
     implements ObjectInput, ObjectStreamConstants
</code></pre>
<p> <strong>Constructors :</strong> </p>
<ul>
<li><p><strong>FileNotFoundException() :</strong> It gives FileNotFoundException with null message.</p>
</li>
<li><p><strong>FileNotFoundException(String s) :</strong> It gives FileNotFoundException with detail message.</p>
</li>
</ul>
</li>
</ol>
<p>    It doesn’t have any methods. Now let’s understand the <strong>hierarchy</strong> of this class i.e FileNotFoundException extends IOException which further extends the Exception class which extends the <a target="_blank" href="https://www.geeksforgeeks.org/throwable-class-in-java-with-examples/"><strong>Throwable class</strong></a> and further the Object class. </p>
<p>    <strong>Hierarchy Diagram:</strong></p>
<p>    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20210113195040/hierarchyException-660x495.jpg" alt /></p>
<p>    <strong>Why this Exception occurs?</strong> </p>
<ol start="5">
<li><p>There are mainly <strong>2 scenarios</strong> when FileNotFoundException occurs. Now let’s see them with examples provided:</p>
<ol>
<li><p>If the given file is not available in the given location then this error will occur.</p>
</li>
<li><p>If the given file is <strong>inaccessible</strong>, for example, if it is read-only then you can read the file but not modify the file, if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.</p>
</li>
</ol>
</li>
</ol>
<p>    <strong>Scenario 1:</strong></p>
<p>    If the given file is not available in the given location then this error will occur.</p>
<p>    <strong>Example:</strong> </p>
    <table><tbody><tr><td><p><code>// Java program to illustrate </code></p></td></tr></tbody></table>

<h3 id="heading-output">Output</h3>
<pre><code class="lang-plaintext">    prog.java:14: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        FileReader reader = new FileReader("file.txt");
                            ^
    prog.java:25: error: unreported exception IOException; must be caught or declared to be thrown
        while ((data = br.readLine()) != null) 
                                  ^
    prog.java:31: error: unreported exception IOException; must be caught or declared to be thrown
        br.close();
                ^
    3 errors
</code></pre>
<p>    <strong>Scenario 2:</strong></p>
<p>    If the given file is inaccessible, for example, if it is read-only then you can read the file but not modify the file if we try to modify it, an error will occur or if the file that you are trying to access for the read/write operation is opened by another program then this error will occur.</p>
<p>    <strong>Example:</strong></p>
    <table><tbody><tr><td><p><code>// Java program to illustrate </code></p></td></tr></tbody></table>

<h3 id="heading-output-1">Output</h3>
<pre><code class="lang-plaintext">    java.security.AccessControlException: access denied ("java.io.FilePermission" "file.txt" "write")
        at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
        at java.base/java.security.AccessController.checkPermission(AccessController.java:897)
        at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322)
        at java.base/java.lang.SecurityManager.checkWrite(SecurityManager.java:752)
        at java.base/java.io.FileOutputStream.&lt;init&gt;(FileOutputStream.java:225)
        at java.base/java.io.FileOutputStream.&lt;init&gt;(FileOutputStream.java:187)
        at java.base/java.io.FileWriter.&lt;init&gt;(FileWriter.java:96)
        at Example2.main(File.java:19)
</code></pre>
<p>    <strong>Handling Exception:</strong></p>
<p>    Firstly we have to use the try-catch block if we know whether the error will occur. Inside try block all the lines should be there if there are chances of errors. There are other remedies to handle the exception:</p>
<ol>
<li><p>If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.</p>
</li>
<li><p>If the message of the exception tells us that access is denied then we have to check the permissions of the file (read, write, both read and write) and also check whether that file is in use by another program.</p>
</li>
<li><p>If the message of the exception tells us that the specified file is a directory then you must either delete the existing directory(if the directory not in use) or change the name of the file.</p>
</li>
</ol>
<ol start="5">
<li><h1 id="heading-remove-all-elements-from-the-arraylist-in-java">Remove all elements from the ArrayList in Java</h1>
</li>
</ol>
<p>    <strong>Prerequisite:</strong> <a target="_blank" href="https://www.geeksforgeeks.org/arraylist-in-java/"><strong>ArrayList in Java</strong></a></p>
<p>    Given an ArrayList, the task is to remove all elements of the ArrayList in Java.</p>
<p>    <strong>Examples:</strong></p>
<pre><code class="lang-plaintext">    Input: ArrayList = [1, 2, 3, 4] 
    Output: ArrayList = [] 

    Input: ArrayList = [12, 23, 34, 45, 57, 67, 89] 
    Output: ArrayList = []
</code></pre>
<ul>
<li><p><strong>Using clear() method:</strong></p>
<p>  <strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">  collection_name.clear();
</code></pre>
<p>  <strong>Code of clear() method:</strong></p>
<pre><code class="lang-plaintext">  public void clear() {
      for (int i = 0; i &lt; size; i++)
          list[i] = null;

      size = 0;
  }
</code></pre>
<p>  Below is the implementation of the above approach:</p>
  <table><tbody><tr><td><p><code>// Java Program for remove all elements ArrayList</code></p></td></tr></tbody></table>

<p>  <strong>Output:</strong></p>
<pre><code class="lang-plaintext">  ArrayList: [Geeks, for, Geeks, Gaurav]
  Size of ArrayList = 4

  After clear

  ArrayList: []
  Size of ArrayList = 0
</code></pre>
<p>  <strong>Time Complexity: O(N)</strong></p>
</li>
<li><p><strong>Using removeAll() method</strong></p>
<p>  <strong>Syntax:</strong></p>
<pre><code class="lang-plaintext">  collection_name.removeAll(collection_name);
</code></pre>
<p>  <strong>Code of removeAll() method:</strong></p>
<pre><code class="lang-plaintext">  public boolean removeAll(Collection list) {
      boolean isModi = false;
      Iterator ite= iterator();
      while (ite.hasNext()) {
          if (list.contains(ite.next())) {
              ite.remove();
              isModi = true;
          }
      }
      return isModi;
  }
</code></pre>
<p>  Below is the implementation of the above approach:</p>
  <table><tbody><tr><td><p><code>// Java Program for remove all elements ArrayList</code></p></td></tr></tbody></table>

<p>  <strong>Output:</strong></p>
<pre><code class="lang-plaintext">  ArrayList: [Geeks, for, Geeks, Gaurav]
  Size of ArrayList = 4

  After clear

  ArrayList: []
  Size of ArrayList = 0
</code></pre>
<p>  <strong>Time Complexity: O(N^2)</strong></p>
</li>
</ul>
<p>        6.</p>
<h1 id="heading-treemap-in-java">TreeMap in Java</h1>
<p>        Last Updated : 16 Jul, 2024</p>
<p>        Let us start with a simple Java code snippet that demonstrates how to create and use a TreeMap in Java.</p>
<p>        1</p>
<pre><code class="lang-plaintext">        import java.util.Map;
</code></pre>
<p>        2</p>
<pre><code class="lang-plaintext">        import java.util.TreeMap;
</code></pre>
<p>        3</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        4</p>
<pre><code class="lang-plaintext">        public class TreeMapCreation {
</code></pre>
<p>        5</p>
<pre><code class="lang-plaintext">            public static void main(String args[]) {
</code></pre>
<p>        6</p>
<p>        7</p>
<pre><code class="lang-plaintext">                // Create a TreeMap of Strings (keys) and Integers (values)
</code></pre>
<p>        8</p>
<pre><code class="lang-plaintext">                TreeMap&lt;String, Integer&gt; treeMap = new TreeMap&lt;&gt;();
</code></pre>
<p>        9</p>
<p>        10</p>
<pre><code class="lang-plaintext">                // Displaying the TreeMap
</code></pre>
<p>        11</p>
<pre><code class="lang-plaintext">                System.out.println("TreeMap elements: " + treeMap);
</code></pre>
<p>        12</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        13</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        <strong>Output</strong></p>
<pre><code class="lang-plaintext">        TreeMap elements: {}
</code></pre>
<p>        The <strong>TreeMap</strong> in Java is used to implement <a target="_blank" href="https://www.geeksforgeeks.org/map-interface-java-examples/">Map interface</a> and <a target="_blank" href="https://www.geeksforgeeks.org/navigablemap-interface-in-java-with-example/">NavigableMap</a> along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a <a target="_blank" href="https://www.geeksforgeeks.org/comparator-interface-java/">Comparator</a> provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs. The storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The treemap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally. </p>
<p>        The TreeMap in Java is a concrete implementation of the java.util.SortedMap interface. It provides an ordered collection of key-value pairs, where the keys are ordered based on their natural order or a custom Comparator passed to the constructor.</p>
<p>        A TreeMap is implemented using a Red-Black tree, which is a type of self-balancing binary search tree. This provides efficient performance for common operations such as adding, removing, and retrieving elements, with an average time complexity of O(log n).</p>
<h3 id="heading-heres-an-example-of-how-to-perform-different-operations-in-java-treemap">Here’s an example of how to perform different operations in Java TreeMap:</h3>
<p>        1</p>
<pre><code class="lang-plaintext">        import java.util.Map;
</code></pre>
<p>        2</p>
<pre><code class="lang-plaintext">        import java.util.TreeMap;
</code></pre>
<p>        3</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        4</p>
<pre><code class="lang-plaintext">        public class Main {
</code></pre>
<p>        5</p>
<pre><code class="lang-plaintext">            public static void main(String[] args)
</code></pre>
<p>        6</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        7</p>
<pre><code class="lang-plaintext">                Map&lt;String, Integer&gt; treeMap = new TreeMap&lt;&gt;();
</code></pre>
<p>        8</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        9</p>
<pre><code class="lang-plaintext">                // Adding elements to the tree map
</code></pre>
<p>        10</p>
<pre><code class="lang-plaintext">                treeMap.put("A", 1); // O(log n)
</code></pre>
<p>        11</p>
<pre><code class="lang-plaintext">                treeMap.put("C", 3); // O(log n)
</code></pre>
<p>        12</p>
<pre><code class="lang-plaintext">                treeMap.put("B", 2); // O(log n)
</code></pre>
<p>        13</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        14</p>
<pre><code class="lang-plaintext">                // Getting values from the tree map
</code></pre>
<p>        15</p>
<pre><code class="lang-plaintext">                int valueA = treeMap.get("A"); // O(log n)
</code></pre>
<p>        16</p>
<pre><code class="lang-plaintext">                System.out.println("Value of A: " + valueA);
</code></pre>
<p>        17</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        18</p>
<pre><code class="lang-plaintext">                // Removing elements from the tree map
</code></pre>
<p>        19</p>
<pre><code class="lang-plaintext">                treeMap.remove("B"); // O(log n)
</code></pre>
<p>        20</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        21</p>
<pre><code class="lang-plaintext">                // Iterating over the elements of the tree map
</code></pre>
<p>        22</p>
<pre><code class="lang-plaintext">                for (String key : treeMap.keySet()) { // O(n)
</code></pre>
<p>        23</p>
<pre><code class="lang-plaintext">                    System.out.println(
</code></pre>
<p>        24</p>
<pre><code class="lang-plaintext">                        "Key: " + key + ", Value: "
</code></pre>
<p>        25</p>
<pre><code class="lang-plaintext">                        + treeMap.get(key)); // O(log n) for each
</code></pre>
<p>        26</p>
<pre><code class="lang-plaintext">                                             // get operation
</code></pre>
<p>        27</p>
<pre><code class="lang-plaintext">                }
</code></pre>
<p>        28</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        29</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        <strong>Output</strong></p>
<pre><code class="lang-plaintext">        Value of A: 1
        Key: A, Value: 1
        Key: C, Value: 3
</code></pre>
<h4 id="heading-time-complexity">Time Complexity:</h4>
<ul>
<li>Overall, the time complexity of the code is O(n log n), where n is the number of elements in the TreeMap.</li>
</ul>
<p>        <strong>Space Complexity:</strong></p>
<ul>
<li>O(n) for storing the elements in the <code>TreeMap</code>.</li>
</ul>
<h3 id="heading-treemap-in-map-interface-hierarchy">TreeMap in Map Interface Hierarchy:</h3>
<p>        <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200807195934/SortedMap.png" alt="TreeMap in Map Interface" /></p>
<h3 id="heading-features-of-a-treemap">Features of a TreeMap</h3>
<p>        Some important features of the TreeMap are as follows: </p>
<ul>
<li><p>This class is a member of the <a target="_blank" href="https://www.geeksforgeeks.org/collections-in-java-2/">Java Collections</a> Framework.</p>
</li>
<li><p>The class implements <a target="_blank" href="https://www.geeksforgeeks.org/map-interface-java-examples/">Map interfaces</a> including <a target="_blank" href="https://www.geeksforgeeks.org/navigablemap-interface-in-java-with-example/">NavigableMap</a>, <a target="_blank" href="https://www.geeksforgeeks.org/sortedmap-java-examples/">SortedMap</a>, and extends AbstractMap class.</p>
</li>
<li><p>TreeMap in Java does not allow null keys (like Map) and thus a <a target="_blank" href="https://www.geeksforgeeks.org/null-pointer-exception-in-java/">NullPointerException</a> is thrown. However, multiple null values can be associated with different keys.</p>
</li>
<li><p>Entry pairs returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the <a target="_blank" href="https://www.geeksforgeeks.org/map-entry-interface-java-example/">Entry.setValue</a> method.</p>
</li>
</ul>
<p>        Now let us move forward and discuss Synchronized TreeMap. The implementation of a TreeMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the <a target="_blank" href="https://www.geeksforgeeks.org/collections-synchronizedsortedmap-method-in-java-with-examples/">Collections.synchronizedSortedMap</a> method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. This can be done as:</p>
<pre><code class="lang-plaintext">        SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
</code></pre>
<h2 id="heading-how-does-the-treemap-works-internally">How does the TreeMap Works Internally?</h2>
<p>        The methods in a TreeMap while getting keyset and values, return an Iterator that is fail-fast in nature. Thus, any concurrent modification will throw <a target="_blank" href="https://www.geeksforgeeks.org/concurrentmodificationexception-in-java-with-examples/">ConcurrentModificationException</a>. A TreeMap is based upon a red-black <a target="_blank" href="https://www.geeksforgeeks.org/red-black-tree-set-1-introduction-2/">tree</a> data structure. </p>
<p>        <strong>Each node in the tree has:</strong> </p>
<ul>
<li><p>3 Variables (<em>K key=Key, V value=Value, boolean color=Color</em>)</p>
</li>
<li><p>3 References (<em>Entry left = Left, Entry right = Right, Entry parent = Parent</em>)</p>
</li>
</ul>
<h2 id="heading-constructors-in-treemap">Constructors in TreeMap</h2>
<p>        In order to create a TreeMap, we need to create an object of the TreeMap class. The TreeMap class consists of various constructors that allow the possible creation of the TreeMap. The following are the constructors available in this class:</p>
<ol>
<li><p>TreeMap()</p>
</li>
<li><p>TreeMap(Comparator comp)</p>
</li>
<li><p>TreeMap(Map M)</p>
</li>
<li><p>TreeMap(SortedMap sm)</p>
</li>
</ol>
<p>        Let us discuss them individually alongside implementing every constructor as follows:</p>
<h3 id="heading-constructor-1-treemap"><strong>Constructor 1:</strong> TreeMap()</h3>
<p>        This constructor is used to build an empty TreeMap that will be sorted by using the natural order of its keys. </p>
<p>        <strong>Example:</strong></p>
<p>        1</p>
<pre><code class="lang-plaintext">        // Java Program to Demonstrate TreeMap
</code></pre>
<p>        2</p>
<pre><code class="lang-plaintext">        // using the Default Constructor
</code></pre>
<p>        3</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        4</p>
<pre><code class="lang-plaintext">        // Importing required classes
</code></pre>
<p>        5</p>
<pre><code class="lang-plaintext">        import java.util.*;
</code></pre>
<p>        6</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        7</p>
<pre><code class="lang-plaintext">        public class GFG {
</code></pre>
<p>        8</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        9</p>
<pre><code class="lang-plaintext">            // Method 1
</code></pre>
<p>        10</p>
<pre><code class="lang-plaintext">            // To show TreeMap constructor
</code></pre>
<p>        11</p>
<pre><code class="lang-plaintext">            static void Example1stConstructor()
</code></pre>
<p>        12</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        13</p>
<pre><code class="lang-plaintext">                // Creating an empty TreeMap
</code></pre>
<p>        14</p>
<pre><code class="lang-plaintext">                TreeMap&lt;Integer, String&gt; tree_map
</code></pre>
<p>        15</p>
<pre><code class="lang-plaintext">                    = new TreeMap&lt;Integer, String&gt;(); // O(1)
</code></pre>
<p>        16</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        17</p>
<pre><code class="lang-plaintext">                // Mapping string values to int keys using put()
</code></pre>
<p>        18</p>
<pre><code class="lang-plaintext">                // method
</code></pre>
<p>        19</p>
<pre><code class="lang-plaintext">                tree_map.put(10, "Geeks"); // O(log n)
</code></pre>
<p>        20</p>
<pre><code class="lang-plaintext">                tree_map.put(15, "4"); // O(log n)
</code></pre>
<p>        21</p>
<pre><code class="lang-plaintext">                tree_map.put(20, "Geeks"); // O(log n)
</code></pre>
<p>        22</p>
<pre><code class="lang-plaintext">                tree_map.put(25, "Welcomes"); // O(log n)
</code></pre>
<p>        23</p>
<pre><code class="lang-plaintext">                tree_map.put(30, "You"); // O(log n)
</code></pre>
<p>        24</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        25</p>
<pre><code class="lang-plaintext">                // Printing the elements of TreeMap
</code></pre>
<p>        26</p>
<pre><code class="lang-plaintext">                System.out.println("TreeMap: " + tree_map); // O(n)
</code></pre>
<p>        27</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        28</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        29</p>
<pre><code class="lang-plaintext">            // Method 2
</code></pre>
<p>        30</p>
<pre><code class="lang-plaintext">            // Main driver method
</code></pre>
<p>        31</p>
<pre><code class="lang-plaintext">            public static void main(String[] args)
</code></pre>
<p>        32</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        33</p>
<pre><code class="lang-plaintext">                System.out.println(
</code></pre>
<p>        34</p>
<pre><code class="lang-plaintext">                    "TreeMap using TreeMap() constructor:\n");
</code></pre>
<p>        35</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        36</p>
<pre><code class="lang-plaintext">                // Calling constructor
</code></pre>
<p>        37</p>
<pre><code class="lang-plaintext">                Example1stConstructor(); // O(n log n) for put and
</code></pre>
<p>        38</p>
<pre><code class="lang-plaintext">                                         // O(n) for printing
</code></pre>
<p>        39</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        40</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        <strong>Output</strong></p>
<pre><code class="lang-plaintext">        TreeMap using TreeMap() constructor:

        TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
</code></pre>
<p>        <strong>Time Complexity:</strong></p>
<ul>
<li><p>Overall time complexity of the provided code snippet is: O(nlog⁡n)</p>
</li>
<li><p>O(n), where n is the number of elements in the TreeMap.</p>
</li>
</ul>
<h3 id="heading-constructor-2-treemapcomparator-comp"><strong>Constructor 2:</strong> TreeMap(Comparator comp)</h3>
<p>        This constructor is used to build an empty TreeMap object in which the elements will need an external specification of the sorting order.</p>
<p>        <strong>Example:</strong></p>
<p>        1</p>
<pre><code class="lang-plaintext">        // Java Program to Demonstrate TreeMap
</code></pre>
<p>        2</p>
<pre><code class="lang-plaintext">        // using Comparator Constructor
</code></pre>
<p>        3</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        4</p>
<pre><code class="lang-plaintext">        // Importing required classes
</code></pre>
<p>        5</p>
<pre><code class="lang-plaintext">        import java.util.*;
</code></pre>
<p>        6</p>
<pre><code class="lang-plaintext">        import java.util.concurrent.*;
</code></pre>
<p>        7</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        8</p>
<pre><code class="lang-plaintext">        // Class 1
</code></pre>
<p>        9</p>
<pre><code class="lang-plaintext">        // Helper class representing Student
</code></pre>
<p>        10</p>
<pre><code class="lang-plaintext">        class Student {
</code></pre>
<p>        11</p>
<pre><code class="lang-plaintext">            int rollno;
</code></pre>
<p>        12</p>
<pre><code class="lang-plaintext">            String name, address;
</code></pre>
<p>        13</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        14</p>
<pre><code class="lang-plaintext">            public Student(int rollno, String name, String address)
</code></pre>
<p>        15</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        16</p>
<pre><code class="lang-plaintext">                this.rollno = rollno;
</code></pre>
<p>        17</p>
<pre><code class="lang-plaintext">                this.name = name;
</code></pre>
<p>        18</p>
<pre><code class="lang-plaintext">                this.address = address;
</code></pre>
<p>        19</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        20</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        21</p>
<pre><code class="lang-plaintext">            public String toString()
</code></pre>
<p>        22</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        23</p>
<pre><code class="lang-plaintext">                return this.rollno + " " + this.name + " "
</code></pre>
<p>        24</p>
<pre><code class="lang-plaintext">                    + this.address;
</code></pre>
<p>        25</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        26</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        27</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        28</p>
<pre><code class="lang-plaintext">        // Class 2
</code></pre>
<p>        29</p>
<pre><code class="lang-plaintext">        // Helper class - Comparator implementation
</code></pre>
<p>        30</p>
<pre><code class="lang-plaintext">        class Sortbyroll implements Comparator&lt;Student&gt; {
</code></pre>
<p>        31</p>
<pre><code class="lang-plaintext">            public int compare(Student a, Student b)
</code></pre>
<p>        32</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        33</p>
<pre><code class="lang-plaintext">                return a.rollno - b.rollno;
</code></pre>
<p>        34</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        35</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        36</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        37</p>
<pre><code class="lang-plaintext">        // Class 3
</code></pre>
<p>        38</p>
<pre><code class="lang-plaintext">        // Main class
</code></pre>
<p>        39</p>
<pre><code class="lang-plaintext">        public class GFG {
</code></pre>
<p>        40</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        41</p>
<pre><code class="lang-plaintext">            static void Example2ndConstructor()
</code></pre>
<p>        42</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        43</p>
<pre><code class="lang-plaintext">                TreeMap&lt;Student, Integer&gt; tree_map
</code></pre>
<p>        44</p>
<pre><code class="lang-plaintext">                    = new TreeMap&lt;Student, Integer&gt;(
</code></pre>
<p>        45</p>
<pre><code class="lang-plaintext">                        new Sortbyroll()); // O(1)
</code></pre>
<p>        46</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        47</p>
<pre><code class="lang-plaintext">                tree_map.put(new Student(111, "bbbb", "london"),
</code></pre>
<p>        48</p>
<pre><code class="lang-plaintext">                             2); // O(log n)
</code></pre>
<p>        49</p>
<pre><code class="lang-plaintext">                tree_map.put(new Student(131, "aaaa", "nyc"),
</code></pre>
<p>        50</p>
<pre><code class="lang-plaintext">                             3); // O(log n)
</code></pre>
<p>        51</p>
<pre><code class="lang-plaintext">                tree_map.put(new Student(121, "cccc", "jaipur"),
</code></pre>
<p>        52</p>
<pre><code class="lang-plaintext">                             1); // O(log n)
</code></pre>
<p>        53</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        54</p>
<pre><code class="lang-plaintext">                System.out.println("TreeMap: " + tree_map); // O(n)
</code></pre>
<p>        55</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        56</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        57</p>
<pre><code class="lang-plaintext">            public static void main(String[] args)
</code></pre>
<p>        58</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        59</p>
<pre><code class="lang-plaintext">                System.out.println(
</code></pre>
<p>        60</p>
<pre><code class="lang-plaintext">                    "TreeMap using TreeMap(Comparator) constructor:\n");
</code></pre>
<p>        61</p>
<pre><code class="lang-plaintext">                Example2ndConstructor(); // O(n log n) for put and
</code></pre>
<p>        62</p>
<pre><code class="lang-plaintext">                                         // O(n) for printing
</code></pre>
<p>        63</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        64</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        <strong>Output</strong></p>
<pre><code class="lang-plaintext">        TreeMap using TreeMap(Comparator) constructor:

        TreeMap: {111 bbbb london=2, 121 cccc jaipur=1, 131 aaaa nyc=3}
</code></pre>
<h4 id="heading-ia"> </h4>
<p>        Time Complexity:</p>
<ul>
<li><strong>Overall Time Complexity:</strong> O(nlog⁡n)</li>
</ul>
<p>        <strong>Space Complexity:</strong></p>
<ul>
<li><strong>Overall Space Complexity:</strong> O(n)</li>
</ul>
<h3 id="heading-constructor-3-treemapmap-m"><strong>Constructor 3:</strong> TreeMap(Map M)</h3>
<p>        This constructor is used to initialize a TreeMap with the entries from the given map M which will be sorted by using the natural order of the keys.</p>
<p>        <strong>Example:</strong></p>
<p>        1</p>
<pre><code class="lang-plaintext">        // Java Program to Demonstrate TreeMap
</code></pre>
<p>        2</p>
<pre><code class="lang-plaintext">        // using the Default Constructor
</code></pre>
<p>        3</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        4</p>
<pre><code class="lang-plaintext">        // Importing required classes
</code></pre>
<p>        5</p>
<pre><code class="lang-plaintext">        import java.util.*;
</code></pre>
<p>        6</p>
<pre><code class="lang-plaintext">        import java.util.concurrent.*;
</code></pre>
<p>        7</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        8</p>
<pre><code class="lang-plaintext">        // Main class
</code></pre>
<p>        9</p>
<pre><code class="lang-plaintext">        public class TreeMapImplementation {
</code></pre>
<p>        10</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        11</p>
<pre><code class="lang-plaintext">            // Method 1
</code></pre>
<p>        12</p>
<pre><code class="lang-plaintext">            // To illustrate constructor&lt;Map&gt;
</code></pre>
<p>        13</p>
<pre><code class="lang-plaintext">            static void Example3rdConstructor()
</code></pre>
<p>        14</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        15</p>
<pre><code class="lang-plaintext">                // Creating an empty HashMap
</code></pre>
<p>        16</p>
<pre><code class="lang-plaintext">                Map&lt;Integer, String&gt; hash_map
</code></pre>
<p>        17</p>
<pre><code class="lang-plaintext">                    = new HashMap&lt;Integer, String&gt;(); // O(1)
</code></pre>
<p>        18</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        19</p>
<pre><code class="lang-plaintext">                // Mapping string values to int keys using put()
</code></pre>
<p>        20</p>
<pre><code class="lang-plaintext">                // method
</code></pre>
<p>        21</p>
<pre><code class="lang-plaintext">                hash_map.put(10, "Geeks"); // O(1)
</code></pre>
<p>        22</p>
<pre><code class="lang-plaintext">                hash_map.put(15, "4"); // O(1)
</code></pre>
<p>        23</p>
<pre><code class="lang-plaintext">                hash_map.put(20, "Geeks"); // O(1)
</code></pre>
<p>        24</p>
<pre><code class="lang-plaintext">                hash_map.put(25, "Welcomes"); // O(1)
</code></pre>
<p>        25</p>
<pre><code class="lang-plaintext">                hash_map.put(30, "You"); // O(1)
</code></pre>
<p>        26</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        27</p>
<pre><code class="lang-plaintext">                // Creating the TreeMap using the Map
</code></pre>
<p>        28</p>
<pre><code class="lang-plaintext">                TreeMap&lt;Integer, String&gt; tree_map
</code></pre>
<p>        29</p>
<pre><code class="lang-plaintext">                    = new TreeMap&lt;Integer, String&gt;(
</code></pre>
<p>        30</p>
<pre><code class="lang-plaintext">                        hash_map); // O(n log n)
</code></pre>
<p>        31</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        32</p>
<pre><code class="lang-plaintext">                // Printing the elements of TreeMap
</code></pre>
<p>        33</p>
<pre><code class="lang-plaintext">                System.out.println("TreeMap: " + tree_map); // O(n)
</code></pre>
<p>        34</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        35</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        36</p>
<pre><code class="lang-plaintext">            // Method 2
</code></pre>
<p>        37</p>
<pre><code class="lang-plaintext">            // Main driver method
</code></pre>
<p>        38</p>
<pre><code class="lang-plaintext">            public static void main(String[] args)
</code></pre>
<p>        39</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        40</p>
<pre><code class="lang-plaintext">                System.out.println(
</code></pre>
<p>        41</p>
<pre><code class="lang-plaintext">                    "TreeMap using TreeMap(Map) constructor:\n");
</code></pre>
<p>        42</p>
<pre><code class="lang-plaintext">                Example3rdConstructor();
</code></pre>
<p>        43</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        44</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        <strong>Output</strong></p>
<pre><code class="lang-plaintext">        TreeMap using TreeMap(Map) constructor:

        TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
</code></pre>
<h4 id="heading-ia-1"> </h4>
<p>        Time Complexity:</p>
<ul>
<li><strong>Overall Time Complexity:</strong> O(nlog⁡n)</li>
</ul>
<h4 id="heading-space-complexity">Space Complexity:</h4>
<ul>
<li><strong>Overall Space Complexity:</strong> O(n)</li>
</ul>
<h4 id="heading-constructor-4-treemapsortedmap-sm"><strong>Constructor 4:</strong> TreeMap(SortedMap sm)</h4>
<p>        This constructor is used to initialize a TreeMap with the entries from the given <a target="_blank" href="https://www.geeksforgeeks.org/sortedmap-java-examples/">sorted map</a> which will be stored in the same order as the given sorted map.</p>
<p>        <strong>Example:</strong></p>
<p>        1</p>
<pre><code class="lang-plaintext">        // Java Program to Demonstrate TreeMap
</code></pre>
<p>        2</p>
<pre><code class="lang-plaintext">        // using the SortedMap Constructor
</code></pre>
<p>        3</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        4</p>
<pre><code class="lang-plaintext">        // Importing required classes
</code></pre>
<p>        5</p>
<pre><code class="lang-plaintext">        import java.util.*;
</code></pre>
<p>        6</p>
<pre><code class="lang-plaintext">        import java.util.concurrent.*;
</code></pre>
<p>        7</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        8</p>
<pre><code class="lang-plaintext">        // Main class
</code></pre>
<p>        9</p>
<pre><code class="lang-plaintext">        public class GFG {
</code></pre>
<p>        10</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        11</p>
<pre><code class="lang-plaintext">            // Method
</code></pre>
<p>        12</p>
<pre><code class="lang-plaintext">            // To show TreeMap(SortedMap) constructor
</code></pre>
<p>        13</p>
<pre><code class="lang-plaintext">            static void Example4thConstructor()
</code></pre>
<p>        14</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        15</p>
<pre><code class="lang-plaintext">                // Creating a SortedMap
</code></pre>
<p>        16</p>
<pre><code class="lang-plaintext">                SortedMap&lt;Integer, String&gt; sorted_map
</code></pre>
<p>        17</p>
<pre><code class="lang-plaintext">                    = new ConcurrentSkipListMap&lt;Integer,
</code></pre>
<p>        18</p>
<pre><code class="lang-plaintext">                                                String&gt;(); // O(1)
</code></pre>
<p>        19</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        20</p>
<pre><code class="lang-plaintext">                // Mapping string values to int keys using put()
</code></pre>
<p>        21</p>
<pre><code class="lang-plaintext">                // method
</code></pre>
<p>        22</p>
<pre><code class="lang-plaintext">                sorted_map.put(10, "Geeks"); // O(log n)
</code></pre>
<p>        23</p>
<pre><code class="lang-plaintext">                sorted_map.put(15, "4"); // O(log n)
</code></pre>
<p>        24</p>
<pre><code class="lang-plaintext">                sorted_map.put(20, "Geeks"); // O(log n)
</code></pre>
<p>        25</p>
<pre><code class="lang-plaintext">                sorted_map.put(25, "Welcomes"); // O(log n)
</code></pre>
<p>        26</p>
<pre><code class="lang-plaintext">                sorted_map.put(30, "You"); // O(log n)
</code></pre>
<p>        27</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        28</p>
<pre><code class="lang-plaintext">                // Creating the TreeMap using the SortedMap
</code></pre>
<p>        29</p>
<pre><code class="lang-plaintext">                TreeMap&lt;Integer, String&gt; tree_map
</code></pre>
<p>        30</p>
<pre><code class="lang-plaintext">                    = new TreeMap&lt;Integer, String&gt;(
</code></pre>
<p>        31</p>
<pre><code class="lang-plaintext">                        sorted_map); // O(n log n)
</code></pre>
<p>        32</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        33</p>
<pre><code class="lang-plaintext">                // Printing the elements of TreeMap
</code></pre>
<p>        34</p>
<pre><code class="lang-plaintext">                System.out.println("TreeMap: " + tree_map); // O(n)
</code></pre>
<p>        35</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        36</p>
<pre><code class="lang-plaintext">        ​
</code></pre>
<p>        37</p>
<pre><code class="lang-plaintext">            // Method 2
</code></pre>
<p>        38</p>
<pre><code class="lang-plaintext">            // Main driver method
</code></pre>
<p>        39</p>
<pre><code class="lang-plaintext">            public static void main(String[] args)
</code></pre>
<p>        40</p>
<pre><code class="lang-plaintext">            {
</code></pre>
<p>        41</p>
<pre><code class="lang-plaintext">                System.out.println(
</code></pre>
<p>        42</p>
<pre><code class="lang-plaintext">                    "TreeMap using TreeMap(SortedMap) constructor:\n");
</code></pre>
<p>        43</p>
<pre><code class="lang-plaintext">                Example4thConstructor(); // O(n log n) for put and
</code></pre>
<p>        44</p>
<pre><code class="lang-plaintext">                                         // O(n) for printing
</code></pre>
<p>        45</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>        46</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>        <strong>Output</strong></p>
<pre><code class="lang-plaintext">        TreeMap using TreeMap(SortedMap) constructor:

        TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
</code></pre>
<h4 id="heading-time-complexity-1">Time Complexity:</h4>
<ul>
<li><p><strong>Overall Time Complexity:</strong> O(nlog⁡n)</p>
</li>
<li><p><strong>Overall Space Complexity:</strong> O(n)</p>
<ul>
<li><ol start="7">
<li><h1 id="heading-convert-list-to-array-in-java">Convert List to Array in Java</h1>
</li>
</ol>
<p>The <a target="_blank" href="https://www.geeksforgeeks.org/list-interface-java-examples/"><strong>List interface</strong></a> provides a way to store the ordered collection. It is a child interface of <a target="_blank" href="https://www.geeksforgeeks.org/collections-in-java-2/"><strong>Collection</strong></a>. It is an ordered collection of objects where duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Now here we are given a <a target="_blank" href="https://www.geeksforgeeks.org/list-interface-java-examples/"><strong>List</strong></a> be it any <a target="_blank" href="https://www.geeksforgeeks.org/linked-list-in-java/"><strong>LinkedList</strong></a> or <a target="_blank" href="https://www.geeksforgeeks.org/arraylist-in-java/"><strong>ArrayList</strong></a> of strings, our motive is to convert this list to an array of strings in Java using different methods. </p>
<h3 id="heading-methods-to-convert-list-to-array-in-java"><strong>Methods to Convert List to Array in Java</strong></h3>
<ol>
<li><p>Using get() method</p>
</li>
<li><p>Using toArray() method</p>
</li>
<li><p>Using Stream introduced in Java 8</p>
</li>
</ol>
</li>
</ul>
</li>
</ul>
<h3 id="heading-method-1-using-get-method"><strong>Method 1:</strong> Using get() method</h3>
<p>            We can use the below list method to get all elements one by one and insert them into an array.</p>
<p>            <strong>Return Type:</strong> The element at the specified index in the list.</p>
<p>            <strong>Syntax:</strong> </p>
<pre><code class="lang-plaintext">            public E get(int index)
</code></pre>
<p>            <strong>Example:</strong></p>
<p>            1</p>
<pre><code class="lang-plaintext">            // Java program to Convert a List to an Array
</code></pre>
<p>            2</p>
<pre><code class="lang-plaintext">            // Using get() method in a loop
</code></pre>
<p>            3</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            4</p>
<pre><code class="lang-plaintext">            // Importing required classes
</code></pre>
<p>            5</p>
<pre><code class="lang-plaintext">            import java.io.*;
</code></pre>
<p>            6</p>
<pre><code class="lang-plaintext">            import java.util.LinkedList;
</code></pre>
<p>            7</p>
<pre><code class="lang-plaintext">            import java.util.List;
</code></pre>
<p>            8</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            9</p>
<pre><code class="lang-plaintext">            // Main class
</code></pre>
<p>            10</p>
<pre><code class="lang-plaintext">            class GFG {
</code></pre>
<p>            11</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            12</p>
<pre><code class="lang-plaintext">                // Main driver method
</code></pre>
<p>            13</p>
<pre><code class="lang-plaintext">                public static void main(String[] args)
</code></pre>
<p>            14</p>
<pre><code class="lang-plaintext">                {
</code></pre>
<p>            15</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            16</p>
<pre><code class="lang-plaintext">                    // Creating a LinkedList of string type by
</code></pre>
<p>            17</p>
<pre><code class="lang-plaintext">                    // declaring object of List
</code></pre>
<p>            18</p>
<pre><code class="lang-plaintext">                    List&lt;String&gt; list = new LinkedList&lt;String&gt;();
</code></pre>
<p>            19</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            20</p>
<pre><code class="lang-plaintext">                    // Adding custom element to LinkedList
</code></pre>
<p>            21</p>
<pre><code class="lang-plaintext">                    // using add() method
</code></pre>
<p>            22</p>
<pre><code class="lang-plaintext">                    list.add("Geeks");
</code></pre>
<p>            23</p>
<pre><code class="lang-plaintext">                    list.add("for");
</code></pre>
<p>            24</p>
<pre><code class="lang-plaintext">                    list.add("Geeks");
</code></pre>
<p>            25</p>
<pre><code class="lang-plaintext">                    list.add("Practice");
</code></pre>
<p>            26</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            27</p>
<pre><code class="lang-plaintext">                    // Storing it inside array of strings
</code></pre>
<p>            28</p>
<pre><code class="lang-plaintext">                    String[] arr = new String[list.size()];
</code></pre>
<p>            29</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            30</p>
<pre><code class="lang-plaintext">                    // Converting ArrayList to Array
</code></pre>
<p>            31</p>
<pre><code class="lang-plaintext">                    // using get() method
</code></pre>
<p>            32</p>
<pre><code class="lang-plaintext">                    for (int i = 0; i &lt; list.size(); i++)
</code></pre>
<p>            33</p>
<pre><code class="lang-plaintext">                        arr[i] = list.get(i);
</code></pre>
<p>            34</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            35</p>
<pre><code class="lang-plaintext">                    // Printing elements of array on console
</code></pre>
<p>            36</p>
<pre><code class="lang-plaintext">                    for (String x : arr)
</code></pre>
<p>            37</p>
<pre><code class="lang-plaintext">                        System.out.print(x + " ");
</code></pre>
<p>            38</p>
<pre><code class="lang-plaintext">                }
</code></pre>
<p>            39</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>            <strong>Output</strong></p>
<pre><code class="lang-plaintext">            Geeks for Geeks Practice
</code></pre>
<h4 id="heading-explanation-of-the-program">Explanation of the Program:</h4>
<ul>
<li><p>This Java program demonstrates how to convert a LinkedList of strings to an array using the <code>get()</code> method in a loop.</p>
</li>
<li><p>It creates a LinkedList, adds elements to it, then iterates through the list to copy each element into an array.</p>
</li>
<li><p>Finally, it prints the array elements to the console.</p>
</li>
</ul>
<h4 id="heading-time-and-space-complexities">Time and Space complexities:</h4>
<ul>
<li><p><strong>Time Complexity</strong>: O(n), where n is the size of the list.</p>
</li>
<li><p><strong>Space Complexity</strong>: O(n), where n is the size of the list.</p>
</li>
</ul>
<h3 id="heading-method-2-using-toarray-methodhttpswwwgeeksforgeeksorgarraylist-toarray-method-in-java-with-examples"><strong>Method 2:</strong> Using <a target="_blank" href="https://www.geeksforgeeks.org/arraylist-toarray-method-in-java-with-examples/"><strong><em>toArray() method</em></strong></a></h3>
<p>            The toArray() method without any arguments returns an array containing all of the elements in the list in the proper sequence . The runtime type of the returned array is Object[].</p>
<h4 id="heading-syntax"><strong>Syntax:</strong></h4>
<p>            Without Arguments:</p>
<blockquote>
<p><em>public Object[] toArray()</em></p>
</blockquote>
<p>            With Array Argument:</p>
<blockquote>
<p><em>public &lt;T&gt; T[] toArray(T[] a)</em></p>
</blockquote>
<p>            <strong>Example:</strong></p>
<p>            1</p>
<pre><code class="lang-plaintext">            // Java Program to Convert a List to an array
</code></pre>
<p>            2</p>
<pre><code class="lang-plaintext">            // using toArray() Within a loop
</code></pre>
<p>            3</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            4</p>
<pre><code class="lang-plaintext">            // Importing utility classes
</code></pre>
<p>            5</p>
<pre><code class="lang-plaintext">            import java.util.*;
</code></pre>
<p>            6</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            7</p>
<pre><code class="lang-plaintext">            // Main class
</code></pre>
<p>            8</p>
<pre><code class="lang-plaintext">            public class GFG {
</code></pre>
<p>            9</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            10</p>
<pre><code class="lang-plaintext">                // Main driver method
</code></pre>
<p>            11</p>
<pre><code class="lang-plaintext">                public static void main(String[] args)
</code></pre>
<p>            12</p>
<pre><code class="lang-plaintext">                {
</code></pre>
<p>            13</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            14</p>
<pre><code class="lang-plaintext">                    // Creating an empty LinkedList of string type
</code></pre>
<p>            15</p>
<pre><code class="lang-plaintext">                    // by declaring object of List
</code></pre>
<p>            16</p>
<pre><code class="lang-plaintext">                    List&lt;String&gt; list = new LinkedList&lt;String&gt;();
</code></pre>
<p>            17</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            18</p>
<pre><code class="lang-plaintext">                    // Adding elements to above LinkedList
</code></pre>
<p>            19</p>
<pre><code class="lang-plaintext">                    // using add() method
</code></pre>
<p>            20</p>
<pre><code class="lang-plaintext">                    list.add("Geeks");
</code></pre>
<p>            21</p>
<pre><code class="lang-plaintext">                    list.add("for");
</code></pre>
<p>            22</p>
<pre><code class="lang-plaintext">                    list.add("Geeks");
</code></pre>
<p>            23</p>
<pre><code class="lang-plaintext">                    list.add("Practice");
</code></pre>
<p>            24</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            25</p>
<pre><code class="lang-plaintext">                    // Converting List to array
</code></pre>
<p>            26</p>
<pre><code class="lang-plaintext">                    // using toArray() method
</code></pre>
<p>            27</p>
<pre><code class="lang-plaintext">                    String[] arr = list.toArray(new String[0]);
</code></pre>
<p>            28</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            29</p>
<pre><code class="lang-plaintext">                    // Printing elements of array
</code></pre>
<p>            30</p>
<pre><code class="lang-plaintext">                    // using for-each loop
</code></pre>
<p>            31</p>
<pre><code class="lang-plaintext">                    for (String x : arr)
</code></pre>
<p>            32</p>
<pre><code class="lang-plaintext">                        System.out.print(x + " ");
</code></pre>
<p>            33</p>
<pre><code class="lang-plaintext">                }
</code></pre>
<p>            34</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>            <strong>Output</strong></p>
<pre><code class="lang-plaintext">            Geeks for Geeks Practice
</code></pre>
<h4 id="heading-explanation-of-the-program-1">Explanation of the Program:</h4>
<ul>
<li><p>This Java program illustrates converting a LinkedList of strings to an array using the <code>toArray()</code> method.</p>
</li>
<li><p>It creates a LinkedList, adds elements to it, and then converts the list to an array with <code>toArray(new String[0])</code>.</p>
</li>
<li><p>Finally, it prints the array elements using a for-each loop.</p>
</li>
</ul>
<h4 id="heading-time-and-space-complexities-1">Time and Space complexities:</h4>
<ul>
<li><p><strong>Time Complexity</strong>: O(n), where n is the size of the list.</p>
</li>
<li><p><strong>Space Complexity</strong>: O(n), where n is the size of the list.</p>
</li>
</ul>
<h3 id="heading-method-3-using-stream-introduced-in-java8httpswwwgeeksforgeeksorgstream-in-java"><strong>Method 3:</strong> <a target="_blank" href="https://www.geeksforgeeks.org/stream-in-java/"><strong>Using Stream introduced in Java8</strong></a></h3>
<p>            The Streams allow functional-style operations on sequences of the elements. The toArray() method of the Stream interface can be used to convert the elements of the stream into an array. The Stream.toArray(IntFunction&lt;A[]&gt; generator) method returns an array containing the elements of this stream.</p>
<p>            <strong>Syntax:</strong></p>
<blockquote>
<p><em>public &lt;A&gt; A[] toArray(IntFunction&lt;A[]&gt; generator)</em></p>
</blockquote>
<p>            <strong>Example:</strong></p>
<p>            1</p>
<pre><code class="lang-plaintext">            // Java Program to Demonstrate conversion of List to Array
</code></pre>
<p>            2</p>
<pre><code class="lang-plaintext">            // Using stream
</code></pre>
<p>            3</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            4</p>
<pre><code class="lang-plaintext">            // Importing utility classes
</code></pre>
<p>            5</p>
<pre><code class="lang-plaintext">            import java.util.*;
</code></pre>
<p>            6</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            7</p>
<pre><code class="lang-plaintext">            // Main class
</code></pre>
<p>            8</p>
<pre><code class="lang-plaintext">            class GFG {
</code></pre>
<p>            9</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            10</p>
<pre><code class="lang-plaintext">                // Main driver method
</code></pre>
<p>            11</p>
<pre><code class="lang-plaintext">                public static void main(String[] args)
</code></pre>
<p>            12</p>
<pre><code class="lang-plaintext">                {
</code></pre>
<p>            13</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            14</p>
<pre><code class="lang-plaintext">                    // Creating an empty LinkedList of string type
</code></pre>
<p>            15</p>
<pre><code class="lang-plaintext">                    List&lt;String&gt; list = new LinkedList&lt;String&gt;();
</code></pre>
<p>            16</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            17</p>
<pre><code class="lang-plaintext">                    // Adding elements to above LinkedList
</code></pre>
<p>            18</p>
<pre><code class="lang-plaintext">                    // using add() method
</code></pre>
<p>            19</p>
<pre><code class="lang-plaintext">                    list.add("Geeks");
</code></pre>
<p>            20</p>
<pre><code class="lang-plaintext">                    list.add("for");
</code></pre>
<p>            21</p>
<pre><code class="lang-plaintext">                    list.add("Geeks");
</code></pre>
<p>            22</p>
<pre><code class="lang-plaintext">                    list.add("Practice");
</code></pre>
<p>            23</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            24</p>
<pre><code class="lang-plaintext">                    // Storing size of List
</code></pre>
<p>            25</p>
<pre><code class="lang-plaintext">                    int n = list.size();
</code></pre>
<p>            26</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            27</p>
<pre><code class="lang-plaintext">                    // Converting List to array via scope resolution
</code></pre>
<p>            28</p>
<pre><code class="lang-plaintext">                    // operator using streams
</code></pre>
<p>            29</p>
<pre><code class="lang-plaintext">                    String[] arr
</code></pre>
<p>            30</p>
<pre><code class="lang-plaintext">                        = list.stream().toArray(String[] ::new);
</code></pre>
<p>            31</p>
<pre><code class="lang-plaintext">            ​
</code></pre>
<p>            32</p>
<pre><code class="lang-plaintext">                    // Printing elements of array
</code></pre>
<p>            33</p>
<pre><code class="lang-plaintext">                    // using enhanced for loop
</code></pre>
<p>            34</p>
<pre><code class="lang-plaintext">                    for (String x : arr)
</code></pre>
<p>            35</p>
<pre><code class="lang-plaintext">                        System.out.print(x + " ");
</code></pre>
<p>            36</p>
<pre><code class="lang-plaintext">                }
</code></pre>
<p>            37</p>
<pre><code class="lang-plaintext">            }
</code></pre>
<p>            <strong>Output</strong></p>
<pre><code class="lang-plaintext">            Geeks for Geeks Practice
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Java Program to Check Palindrome]]></title><description><![CDATA[Java Program to Check Palindrome
To understand this example, you should have the knowledge of the following Java programming topics:

Java Strings

Java while and do...while Loop

Java for Loop

Java if...else Statement



A string is called a palind...]]></description><link>https://development-of-net-banking-application.hashnode.dev/java-program-to-check-palindrome</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/java-program-to-check-palindrome</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Fri, 31 Jan 2025 14:33:00 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-java-program-to-check-palindrome">Java Program to Check Palindrome</h1>
<p>To understand this example, you should have the knowledge of the following <a target="_blank" href="https://www.programiz.com/java-programming">Java programming</a> topics:</p>
<ul>
<li><p><a target="_blank" href="https://www.programiz.com/java-programming/string">Java Strings</a></p>
</li>
<li><p><a target="_blank" href="https://www.programiz.com/java-programming/do-while-loop">Java while and do...while Loop</a></p>
</li>
<li><p><a target="_blank" href="https://www.programiz.com/java-programming/for-loop">Java for Loop</a></p>
</li>
<li><p><a target="_blank" href="https://www.programiz.com/java-programming/if-else-statement">Java if...else Statement</a></p>
</li>
</ul>
<hr />
<p>A string is called a palindrome string if the reverse of that string is the same as the original string. For example, <code>radar</code>, <code>level</code>, etc.</p>
<p>Similarly, a number that is equal to the reverse of that same number is called a palindrome number. For example, <strong>3553</strong>, <strong>12321</strong>, etc.</p>
<p>To check a Palindrome in Java, we first reverse the string or number and compare the reversed string or number with the original value.</p>
<h2 id="heading-example-1-java-program-to-check-palindrome-string">Example 1: Java Program to Check Palindrome String</h2>
<pre><code class="lang-plaintext">class Main {
  public static void main(String[] args) {

    String str = "Radar", reverseStr = "";

    int strLength = str.length();

    for (int i = (strLength - 1); i &gt;=0; --i) {
      reverseStr = reverseStr + str.charAt(i);
    }

    if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
      System.out.println(str + " is a Palindrome String.");
    }
    else {
      System.out.println(str + " is not a Palindrome String.");
    }
  }
}
</code></pre>
<p><a target="_blank" href="https://www.programiz.com/java-programming/online-compiler">Run Code</a></p>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">Radar is a Palindrome String.
</code></pre>
<p>In the above example, we have a string <code>"Radar"</code> stored in str. Here, we have used the</p>
<p><strong>1. for loop to reverse the string</strong></p>
<ul>
<li><p>The loop runs from the end to the beginning of the string.</p>
</li>
<li><p>The <a target="_blank" href="https://www.programiz.com/java-programming/library/string/charat">charAt() method</a> accesses each character of the string.</p>
</li>
<li><p>Each character of the string is accessed in reverse order and stored in reverseStr.</p>
</li>
</ul>
<p><strong>2. if statement to compare str and reverseStr</strong></p>
<ul>
<li><p>The <a target="_blank" href="https://www.programiz.com/java-programming/library/string/tolowercase">toLowerCase() method</a> converts both str and reverseStr to lowercase. This is because Java is case sensitive and 'r' and 'R' are two different values.</p>
</li>
<li><p>The <a target="_blank" href="https://www.programiz.com/java-programming/library/string/equals">equals() method</a> checks if two strings are equal.</p>
</li>
</ul>
<hr />
<h2 id="heading-example-2-java-program-to-check-palindrome-number">Example 2: Java Program to Check Palindrome Number</h2>
<pre><code class="lang-plaintext">class Main {
  public static void main(String[] args) {

    int num = 3553, reversedNum = 0, remainder;

    // store the number to originalNum
    int originalNum = num;

    // get the reverse of originalNum
    // store it in variable
    while (num != 0) {
      remainder = num % 10;
      reversedNum = reversedNum * 10 + remainder;
      num /= 10;
    }

    // check if reversedNum and originalNum are equal
    if (originalNum == reversedNum) {
      System.out.println(originalNum + " is Palindrome.");
    }
    else {
      System.out.println(originalNum + " is not Palindrome.");
    }
  }
}
</code></pre>
<p><a target="_blank" href="https://www.programiz.com/java-programming/online-compiler">Run Code</a></p>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">3553 is Palindrome.
</code></pre>
<h1 id="heading-java-program-to-reverse-a-number">Java Program to Reverse a Number</h1>
<p>To understand this example, you should have the knowledge of the following <a target="_blank" href="https://www.programiz.com/java-programming">Java programming</a> topics:</p>
<ul>
<li><p><a target="_blank" href="https://www.programiz.com/java-programming/do-while-loop">Java while and do...while Loop</a></p>
</li>
<li><p><a target="_blank" href="https://www.programiz.com/java-programming/for-loop">Java for Loop</a></p>
</li>
</ul>
<hr />
<h2 id="heading-example-1-reverse-a-number-using-a-while-loop-in-java">Example 1: Reverse a Number using a while loop in Java</h2>
<pre><code class="lang-plaintext">class Main {
  public static void main(String[] args) {

    int num = 1234, reversed = 0;

    System.out.println("Original Number: " + num);

    // run loop until num becomes 0
    while(num != 0) {

      // get last digit from num
      int digit = num % 10;
      reversed = reversed * 10 + digit;

      // remove the last digit from num
      num /= 10;
    }

    System.out.println("Reversed Number: " + reversed);
  }
}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">Reversed Number: 4321
</code></pre>
<p>In this program, while loop is used to reverse a number as given in the following steps:</p>
<ul>
<li><p>First, the remainder of the num divided by 10 is stored in the variable digit. Now, the digit contains the last digit of num, i.e. 4.<br />  digit is then added to the variable reversed after multiplying it by 10. Multiplication by 10 adds a new place in the reversed number. One-th place multiplied by 10 gives you tenth place, tenth gives you hundredth, and so on. In this case, reversed contains 0 * 10 + 4 = 4.<br />  num is then divided by 10 so that now it only contains the first three digits: 123.</p>
</li>
<li><p>After second iteration, digit equals 3, reversed equals 4 * 10 + 3 = 43 and num = 12</p>
</li>
<li><p>After third iteration, digit equals 2, reversed equals 43 * 10 + 2 = 432 and num = 1</p>
</li>
<li><p>After fourth iteration, digit equals 1, reversed equals 432 * 10 + 1 = 4321 and num = 0</p>
</li>
<li><p>Now num = 0, so the test expression <code>num != 0</code> fails and while loop exits. reversed already contains the reversed number 4321.</p>
</li>
</ul>
<hr />
<h2 id="heading-example-2-reverse-a-number-using-a-for-loop-in-java">Example 2: Reverse a number using a for loop in Java</h2>
<pre><code class="lang-plaintext">class Main {
  public static void main(String[] args) {

    int num = 1234567, reversed = 0;

    for(;num != 0; num /= 10) {
      int digit = num % 10;
      reversed = reversed * 10 + digit;
    }

    System.out.println("Reversed Number: " + reversed);
  }
}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">Reversed Number: 7654321
</code></pre>
<p>In the above program, the while loop is replaced by a for loop where:</p>
<ul>
<li><p>no initialization expression is needed inside the loop since <code>num</code> is already initialized before the loop and we want to avoid resetting it with each iteration</p>
</li>
<li><p>test expression remains the same (<code>num != 0</code>)</p>
</li>
<li><p>update/increment expression contains <code>num /= 10</code>.</p>
</li>
</ul>
<p>So, after each iteration, the update expression runs which removes the last digit of num.</p>
<p>When the for loop exits, reversed will contain the reversed number.</p>
<ol start="3">
<li><p><strong><em>Write a program to print the given below pattern.</em></strong></p>
</li>
<li><p><strong><em>write a program to print the given below pattern.</em></strong></p>
<h1 id="heading-program-to-print-pattern">Program to print pattern</h1>
<p> Given the value of n, print the following pattern.<br /> <strong>Examples :</strong>   </p>
</li>
</ol>
<pre><code class="lang-plaintext">    Input : n = 4
    Output :
       1
       2 3
       4 5 6
       7 8 9 10

    Input : n = 5
    Output :
          1 2
          3 4
           5
          6 7
         8   9
</code></pre>
<p>    <strong><em>5.Anna University grading System</em></strong></p>
<p>    Anna University Grading System The newly appointed Vice-Chancellor of Anna University wanted to create an automated grading system for the students to check their grade. When a student enters a mark, the grading system displays the corresponding grade. Write a program to solve the given problem. The grades for marks 100 - S, 90-99 is A, 80-89 is B, 70-79 is C, 60-69 is D, 50-59 is E and less than 50 is F. Input format:</p>
<p>    The input consists of one integer which corresponds to the marks scored by the student</p>
<p>    Output format:</p>
<p>    If a student marks greater than 100, print "Invalid Input". Otherwise, print the grade.</p>
<p>    Sample Input:</p>
<p>    78</p>
<p>    Sample Output:</p>
<h1 id="heading-c">C</h1>
<p>    import java.util.Scanner; class Main { public static void main(String args[]) { Scanner z=new Scanner(<a target="_blank" href="http://System.in">System.in</a>); int a=z.nextInt(); if(a==100) System.out.println("S"); else if(a&gt;=90&amp;&amp;a&lt;=99) System.out.println("A"); else if(a&gt;=80&amp;&amp;a&lt;=89) System.out.println("B"); else if(a&gt;=70&amp;&amp;a&lt;=79) System.out.println("C"); else if(a&gt;=60&amp;&amp;a&lt;=69) System.out.println("D"); else if(a&gt;=50&amp;&amp;a&lt;=59) System.out.println("E"); else System.out.println("F"); } }</p>
<ol start="6">
<li><p><strong><em>Write a program to calculate the hotel tariff. The room rent is 20% high during peak seasons [April-June and November-December].</em></strong></p>
<p> Input Format</p>
<p> The first input integer denotes the count of the month. The second input integer denotes the room rent per day. The third input integer denotes the number of days stayed in the hotel.</p>
<p> Constraints</p>
<p> Output Format</p>
<p> Print the hotel tariff to be paid. (Note: if the month value entered is not ranging from 1-12, print as Invalid Input)</p>
<p> Sample Input 0</p>
<p> 3</p>
<p> 1500</p>
<p> 2</p>
</li>
<li><p>Sample Output:</p>
<p> 3000 .00  </p>
<p> ```plaintext
   #include
 void p(float);
 int main()
 {
   int month,n;
   float rent,t=0,r=0;
   scanf("%d\n",&amp;month);
   scanf("%f\n",&amp;rent);
   scanf("%d\n",&amp;n);
   t=rent<em>n;
   r=((rent+(rent</em>0.2))*n);</p>
<p>   switch(month)
   {
     case 1:
       p(t);
       break;
     case 2:
       p(t);
       break;
     case 3:
       p(t);
       break;
     case 4:
       p(r);
       break;
     case 5:
       p(r);
       break;
     case 6:
       p(r);
       break;
     case 7:
       p(t);
       break;
     case 8:
       p(t);
       break;
     case 9:
       p(t);
       break;
     case 10:
       p(t);
       break;
     case 11:
       p(r);
       break;
     case 12:
       p(r);
       break;</p>
</li>
</ol>
<p>        default: printf("Invalid Input");
        break;
      }
      return 0;
    }
      void p(float t)
      {
        printf("Hotel Tariff: Rs.%.2f",t);
      }</p>
<pre><code>
    <span class="hljs-number">7.</span> # Write a Program to Find the Largest <span class="hljs-built_in">Number</span> Among Three Numbers

        ---

        ## Example <span class="hljs-number">1</span>: Using <span class="hljs-keyword">if</span> Statement

        <span class="hljs-string">``</span><span class="hljs-string">`plaintext
        #include &lt;stdio.h&gt;

        int main() {

          double n1, n2, n3;

          printf("Enter three different numbers: ");
          scanf("%lf %lf %lf", &amp;n1, &amp;n2, &amp;n3);

          // if n1 is greater than both n2 and n3, n1 is the largest
          if (n1 &gt;= n2 &amp;&amp; n1 &gt;= n3)
            printf("%.2f is the largest number.", n1);

          // if n2 is greater than both n1 and n3, n2 is the largest
          if (n2 &gt;= n1 &amp;&amp; n2 &gt;= n3)
            printf("%.2f is the largest number.", n2);

          // if n3 is greater than both n1 and n2, n3 is the largest
          if (n3 &gt;= n1 &amp;&amp; n3 &gt;= n2)
            printf("%.2f is the largest number.", n3);

          return 0;
        }</span>
</code></pre><p>        <a target="_blank" href="https://www.programiz.com/c-programming/online-compiler">Run Code</a></p>
<p>        Here, we have used 3 different <code>if</code> statements. The first one checks whether n1 is the largest number.</p>
<p>        The second and third <code>if</code> statements check if n2 and n3 are the largest, respectively.</p>
<p>        The biggest drawback of this program is that all 3  <code>if</code> statements are executed, regardless of which number is the largest.</p>
<p>        However, we want to execute only one <code>if</code> statement. We can do this by using an <code>if...else</code> ladder.</p>
<hr />
<h2 id="heading-example-2-using-ifelse-ladder">Example 2: Using if...else Ladder</h2>
<pre><code class="lang-plaintext">        #include &lt;stdio.h&gt;

        int main() {

          double n1, n2, n3;

          printf("Enter three numbers: ");
          scanf("%lf %lf %lf", &amp;n1, &amp;n2, &amp;n3);

          // if n1 is greater than both n2 and n3, n1 is the largest
          if (n1 &gt;= n2 &amp;&amp; n1 &gt;= n3)
            printf("%.2lf is the largest number.", n1);

          // if n2 is greater than both n1 and n3, n2 is the largest
          else if (n2 &gt;= n1 &amp;&amp; n2 &gt;= n3)
            printf("%.2lf is the largest number.", n2);

          // if both above conditions are false, n3 is the largest
          else
            printf("%.2lf is the largest number.", n3);

          return 0;
        }
</code></pre>
<p>        <a target="_blank" href="https://www.programiz.com/c-programming/online-compiler">Run Code</a></p>
<p>        In this program, only the <code>if</code> statement is executed when n1 is the largest.</p>
<p>        Similarly, only the <code>else if</code> statement is executed when n2 is the largest, and so on.</p>
<hr />
<h2 id="heading-example-3-using-nested-ifelse">Example 3: Using Nested if...else</h2>
<pre><code class="lang-plaintext">        #include &lt;stdio.h&gt;

        int main() {

          double n1, n2, n3;

          printf("Enter three numbers: ");
          scanf("%lf %lf %lf", &amp;n1, &amp;n2, &amp;n3);

          // outer if statement
          if (n1 &gt;= n2) {

            // inner if...else
            if (n1 &gt;= n3)
              printf("%.2lf is the largest number.", n1);
            else
              printf("%.2lf is the largest number.", n3);
          }

          // outer else statement
          else {

            // inner if...else
            if (n2 &gt;= n3)
              printf("%.2lf is the largest number.", n2);
            else
              printf("%.2lf is the largest number.", n3);
          }

          return 0;
        }
</code></pre>
<p>        <a target="_blank" href="https://www.programiz.com/c-programming/online-compiler">Run Code</a></p>
<p>        In this program, we have used nested <code>if...else</code> statements to find the largest number. Let's see how they work in greater detail.</p>
<p>        <strong>1. Outer if Statement</strong></p>
<p>        First, notice the outer <code>if</code> statement and the inner if...else statement inside it:</p>
<pre><code class="lang-plaintext">        // outer if statement
        if (n1 &gt;= n2) {
          // inner if...else
          if (n1 &gt;= n3)
            printf("%.2lf is the largest number.", n1);
          else
            printf("%.2lf is the largest number.", n3);
        }
</code></pre>
<p>        Here, we are checking if n1 is greater than or equal to n2. If it is, the program control goes to the inner <code>if...else</code> statement.</p>
<p>        The inner <code>if</code> statement checks whether n1 is also greater than or equal to n3.</p>
<p>        If it is, then n1 is either equal to both n2 and n3, or it is now greater than both n2 and n3 i.e. <code>n1 &gt;= n2 &gt;= n3</code>. Hence, n1 is the largest number.</p>
<p>        Else, n1 is greater than or equal to n2 but it is less than n3 i.e. <code>n3 &gt; n1 &gt;= n2</code>. Hence, n3 is the largest number.</p>
<p>        <strong>2. Outer else Statement</strong></p>
<p>        The outer <code>else</code> statement is executed when <code>n2 &gt; n1</code>:</p>
<pre><code class="lang-plaintext">        // outer else statement
        else {
          // inner if...else
          if (n2 &gt;= n3)
            printf("%.2lf is the largest number.", n2);
          else
            printf("%.2lf is the largest number.", n3);
        }
</code></pre>
<p>        The inner <code>if...else</code> of this part of the program uses the same logic as the one before. The only difference here is that we're checking if n2 is greater than n3.</p>
<hr />
<p>        The output of all these programs above will be the same.</p>
<pre><code class="lang-plaintext">        Enter three numbers: -4.5
        3.9
        5.6
        5.60 is the largest number.
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Introduction To Java]]></title><description><![CDATA[The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise n...]]></description><link>https://development-of-net-banking-application.hashnode.dev/introduction-to-java</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/introduction-to-java</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 19:12:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735499552228/75985435-4221-43c9-9e5e-0d5cca0e3bb5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <strong>Java if statement</strong> is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not.</p>
<p><strong>Example:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">// Java program to illustrate If statement
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">class GfG {
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">    public static void main(String args[])
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">        int i = 10;
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">        // using if statement
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        if (i &lt; 15)
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">            System.out.println("10 is less than 15");
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        System.out.println("Outside if-block");
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">        // both statements will be printed
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">10 is less than 15
Outside if-block
</code></pre>
<p><strong>Dry-Running Above Example</strong></p>
<pre><code class="lang-plaintext">1. Program starts.
2. i is initialized to 10.
3. if-condition is checked. 10&lt;15, yields true.
       3.a) "10 is less than 15" gets printed.
4. "Outside if-block" is printed.
</code></pre>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20191118171408/If-statement-GeeksforGeeks1.jpg" alt /></p>
<p><strong>Syntax:</strong>  </p>
<pre><code class="lang-plaintext">if(condition) 
{
   // Statements to execute if
   // condition is true
}
</code></pre>
<p><strong>Working of if statement:</strong> </p>
<ol>
<li><p>Control falls into the if block.</p>
</li>
<li><p>The flow jumps to Condition.</p>
</li>
<li><p>Condition is tested.   </p>
<ol>
<li><p>If Condition yields true, goto Step 4.</p>
</li>
<li><p>If Condition yields false, goto Step 5.</p>
</li>
</ol>
</li>
<li><p>The if-block or the body inside the if is executed.</p>
</li>
<li><p>Flow steps out of the if block.</p>
</li>
</ol>
<p><strong>Flowchart if statement:</strong>  </p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20191108163721/java-if.png" alt /></p>
<p><strong>Operation:</strong> The condition after evaluation of if-statement will be either true or false. The if statement in Java accepts boolean values and if the value is true then it will execute the block of statements under it.</p>
<blockquote>
<p><strong><em>Note:</em></strong> <em>If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block.</em> </p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code class="lang-plaintext">if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block will consider the statement 
// under it, i.e statement1, and statement2 will not be considered in the if block, it will still be executed
// as it is not affected by any if condition.
</code></pre>
<p><strong>Example 1:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">// Java program to illustrate If statement
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">class GFG {
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">    public static void main(String args[])
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">        String str = "GeeksforGeeks";
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">        int i = 4;
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">        // if block
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        if (i == 4) {
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">            i++;
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">            System.out.println(str);
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">        // Executed by default
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">        System.out.println("i = " + i);
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">GeeksforGeeks
i = 5
</code></pre>
<p><strong>Example 2: Implementing if else for Boolean values</strong></p>
<pre><code class="lang-plaintext">Input:

 boolean a = true;
 boolean b = false;
</code></pre>
<p>Java1</p>
<pre><code class="lang-plaintext">// Java program to illustrate the if else statement
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">public class IfElseExample {
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">    public static void main(String[] args) {
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">        boolean a = true;
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">        boolean b = false;
</code></pre>
<p>6</p>
<p>7</p>
<pre><code class="lang-plaintext">        if (a) {
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">            System.out.println("a is true");
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        } else {
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">            System.out.println("a is false");
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>12</p>
<p>13</p>
<pre><code class="lang-plaintext">        if (b) {
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">            System.out.println("b is true");
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">        } else {
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">            System.out.println("b is false");
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>18</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>19</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">a is true
b is false
</code></pre>
<p><strong>Explanation:</strong></p>
<ul>
<li><p>The code starts with the declaration of two Boolean variables a and b, with a set to true and b set to false.</p>
</li>
<li><p>The first if-else statement checks the value of a. If the value of a is true, the code inside the first set of curly braces {} is executed and the message “a is true” is printed to the console. If the value of a is false, the code inside the second set of curly braces {} is executed and the message “a is false” is printed to the console.</p>
</li>
<li><p>The second if-else statement checks the value of b in the same way. If the value of b is true, the message “b is true” is printed to the console. If the value of b is false, the message “b is false” is printed to the console.</p>
</li>
<li><p>This code demonstrates how to use an if-else statement to make decisions based on Boolean values. By using an if-else statement, you can control the flow of your program and execute code only under certain conditions. The use of Boolean values in an if-else statement provides a simple and flexible way to make these decisions.</p>
</li>
</ul>
<h3 id="heading-advantages-of-if-else-statement">Advantages of If else statement</h3>
<ol>
<li><p><strong>Conditional execution:</strong> The if-else statement allows code to be executed conditionally based on the result of a Boolean expression. This provides a way to make decisions and control the flow of a program based on different inputs and conditions.</p>
</li>
<li><p><strong>Readability</strong>: The if-else statement makes code more readable by clearly indicating when a particular block of code should be executed. This makes it easier for others to understand and maintain the code.</p>
</li>
<li><p><strong>Reusability</strong>: By using if-else statements, developers can write code that can be reused in different parts of the program. This reduces the amount of code that needs to be written and maintained, making the development process more efficient.</p>
</li>
<li><p><strong>Debugging</strong>: The if-else statement can help simplify the debugging process by making it easier to trace problems in the code. By clearly indicating when a particular block of code should be executed, it becomes easier to determine why a particular piece of code is not working as expected.</p>
</li>
<li><p><strong>Flexibility</strong>: The if-else statement provides a flexible way to control the flow of a program. It allows developers to handle different scenarios and respond dynamically to changes in the program’s inputs.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Java Programming Question]]></title><description><![CDATA[def check_palin (str): for i in range (0, int (len (str)/2)): if str [i] != str [len (str) -i-1]: return False return True str_1 = input (“Enter a string.”) ans = check_palin (str_1) if (ans): print (“Yes, it is a palindrome.”) else: print (“No, it i...]]></description><link>https://development-of-net-banking-application.hashnode.dev/java-programming-question</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/java-programming-question</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 18:44:18 GMT</pubDate><content:encoded><![CDATA[<p>def check_palin (str): for i in range (0, int (len (str)/2)): if str [i] != str [len (str) -i-1]: return False return True str_1 = input (“Enter a string.”) ans = check_palin (str_1) if (ans): print (“Yes, it is a palindrome.”) else: print (“No, it is not a palindrome.”)</p>
<p>A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.</p>
<p><strong>Example</strong></p>
<blockquote>
<p><strong><em>Input*</em></strong>: str = “madam”<br /><strong><strong>Output</strong></strong>: “madam” is palindrome.<br /><strong><strong>Explanation</strong></strong>: The reverse of “madam” is “madam”. So, it is palindrome*</p>
<p><strong><em>Input*</em></strong>: str = “hello”<br /><strong><strong>Output</strong></strong>: “hello” is not palindrome.<br /><strong><strong>Explanation</strong></strong>: The reverse of “hello” is “olleh”. So, it is not palindrome*</p>
</blockquote>
<p><a target="_blank" href="https://www.geeksforgeeks.org/problems/palindrome-string0817/1?itm_source=geeksforgeeks&amp;itm_medium=article&amp;itm_campaign=practice_card"><strong>Try it on GfG Practice</strong></a></p>
<p><img src="https://media.geeksforgeeks.org/auth-dashboard-uploads/Group-arrow.svg" alt="redirect icon" /></p>
<p>In C, there are mainly two different ways to check whether the string is palindrome or not:</p>
<p><strong>Table of Content</strong></p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/c-program-check-given-string-palindrome/#using-another-temporary-string"><strong>By Reversing String</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/c-program-check-given-string-palindrome/#using-two-pointer-method"><strong>By Using Two Pointers</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/c-program-check-given-string-palindrome/#by-using-recursion"><strong>By Using Recursion</strong></a></p>
</li>
</ul>
<p>Checking for a palindrome in C is a great exercise for string manipulation. To further explore string operations and data structures, the <a target="_blank" href="https://gfgcdn.com/tu/T3f/"><strong>C Programming Course Online with Data Structures</strong></a> provides step-by-step guides on string handling and other common algorithms.</p>
<h2 id="heading-by-reversing-string">By Reversing String</h2>
<p>The idea is to <a target="_blank" href="https://www.geeksforgeeks.org/reverse-string-in-c/"><strong>reverse the given string</strong></a> and store it in a temporary array. Then compare both of them using <a target="_blank" href="https://www.geeksforgeeks.org/strcmp-in-c/"><strong>strcmp() function</strong></a>. If they are equal, then the string is palindrome, otherwise, it is not.</p>
<h3 id="heading-code-implementation">Code Implementation</h3>
<p>C1</p>
<pre><code class="lang-plaintext">// Program to check for a palindrome string by reversing
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// the string
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">#include &lt;string.h&gt;
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">#include &lt;stdbool.h&gt;
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">#include &lt;stdlib.h&gt;
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">char *strrev(char *str) {
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">    int len = strlen(str);
</code></pre>
<p>10</p>
<p>11</p>
<pre><code class="lang-plaintext">      // Temporary char array to store the
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">    // reversed string
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">    char *rev = (char *)malloc
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">      (sizeof(char) * (len + 1));
</code></pre>
<p>15</p>
<p>16</p>
<pre><code class="lang-plaintext">    // Reversing the string
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">    for (int i = 0; i &lt; len; i++) {
</code></pre>
<p>18</p>
<pre><code class="lang-plaintext">        rev[i] = str[len - i - 1];
</code></pre>
<p>19</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>20</p>
<pre><code class="lang-plaintext">    rev[len] = '\0';
</code></pre>
<p>21</p>
<pre><code class="lang-plaintext">    return rev;
</code></pre>
<p>22</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p>23</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>24</p>
<pre><code class="lang-plaintext">void isPalindrome(char *str) {
</code></pre>
<p>25</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>26</p>
<pre><code class="lang-plaintext">    // Reversing the string
</code></pre>
<p>27</p>
<pre><code class="lang-plaintext">    char *rev = strrev(str);
</code></pre>
<p>28</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>29</p>
<pre><code class="lang-plaintext">    // Check if the original and reversed
</code></pre>
<p>30</p>
<pre><code class="lang-plaintext">      // strings are equal
</code></pre>
<p>31</p>
<pre><code class="lang-plaintext">    if (strcmp(str, rev) == 0)
</code></pre>
<p>32</p>
<pre><code class="lang-plaintext">        printf("\"%s\" is palindrome.\n",
</code></pre>
<p>33</p>
<pre><code class="lang-plaintext">               str);
</code></pre>
<p>34</p>
<pre><code class="lang-plaintext">    else
</code></pre>
<p>35</p>
<pre><code class="lang-plaintext">        printf("\"%s\" is not palindrome.\n",
</code></pre>
<p>36</p>
<pre><code class="lang-plaintext">               str);
</code></pre>
<p>37</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p>38</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>39</p>
<pre><code class="lang-plaintext">int main() {
</code></pre>
<p>40</p>
<p>41</p>
<pre><code class="lang-plaintext">      // Cheking for palindrome strings
</code></pre>
<p>42</p>
<pre><code class="lang-plaintext">    isPalindrome("madam");
</code></pre>
<p>43</p>
<pre><code class="lang-plaintext">      isPalindrome("hello");
</code></pre>
<p>44</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>45</p>
<pre><code class="lang-plaintext">    return 0;
</code></pre>
<p>46</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">"madam" is palindrome.
"hello" is not palindrome.
</code></pre>
<p><strong>Time Complexity:</strong> O(n), where n is the length of the string.<br /><strong>Auxiliary Space:</strong> O(n), for storing the reversed string.</p>
<h2 id="heading-by-using-two-pointers"><strong>By Using Two Pointers</strong></h2>
<p>In this method, two index pointers are taken: one pointing to the first character and other pointing to the last character in the string. The idea is to traverse the string in forward and backward directions simultaneously while comparing characters at the same distance from start and end.</p>
<ul>
<li><p>If a pair of distinct characters is found, then the string is not palindrome.</p>
</li>
<li><p>If the two pointers meet at the middle of the string without any mismatched characters, then it is palindrome.</p>
</li>
</ul>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20240920165629/Check-for-Palindromic-String-2.webp" alt="Check-for-Palindromic-String-2.webp" /></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20240920165629/Check-for-Palindromic-String-2.webp" alt="Check-for-Palindromic-String-2.webp" /></p>
<p>2 / 4</p>
<p>C1</p>
<pre><code class="lang-plaintext">// Program to check for a palindrome string
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// using two pointers
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">#include &lt;string.h&gt;
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">#include &lt;stdbool.h&gt;
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">void isPalindrome(char *str) {
</code></pre>
<p>8</p>
<p>9</p>
<pre><code class="lang-plaintext">      // Index pointer to the start
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">    int left = 0;
</code></pre>
<p>11</p>
<p>12</p>
<pre><code class="lang-plaintext">    // Index pointer to the end
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">    int right = strlen(str) - 1;
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">    // Run the loop till both pointer
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">    // meet
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">    while (left &lt; right) {
</code></pre>
<p>18</p>
<p>19</p>
<pre><code class="lang-plaintext">        // If characters don't match,
</code></pre>
<p>20</p>
<pre><code class="lang-plaintext">        // string is not palindrome
</code></pre>
<p>21</p>
<pre><code class="lang-plaintext">        if (str[left] != str[right]) {
</code></pre>
<p>22</p>
<pre><code class="lang-plaintext">            printf("\"%s\" is not palindrome.\n",
</code></pre>
<p>23</p>
<pre><code class="lang-plaintext">               str);
</code></pre>
<p>24</p>
<pre><code class="lang-plaintext">            return;
</code></pre>
<p>25</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>26</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>27</p>
<pre><code class="lang-plaintext">        // Move both pointers towards
</code></pre>
<p>28</p>
<pre><code class="lang-plaintext">        // each other
</code></pre>
<p>29</p>
<pre><code class="lang-plaintext">        left++;
</code></pre>
<p>30</p>
<pre><code class="lang-plaintext">        right--;
</code></pre>
<p>31</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>32</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>33</p>
<pre><code class="lang-plaintext">    // If all characters match,
</code></pre>
<p>34</p>
<pre><code class="lang-plaintext">    // string is palindrome
</code></pre>
<p>35</p>
<pre><code class="lang-plaintext">    printf("\"%s\" is palindrome.\n",
</code></pre>
<p>36</p>
<pre><code class="lang-plaintext">               str);
</code></pre>
<p>37</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p>38</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>39</p>
<pre><code class="lang-plaintext">int main() {
</code></pre>
<p>40</p>
<p>41</p>
<pre><code class="lang-plaintext">      // Checking if given strings are palindrome
</code></pre>
<p>42</p>
<pre><code class="lang-plaintext">      isPalindrome("madam");
</code></pre>
<p>43</p>
<pre><code class="lang-plaintext">      isPalindrome("hello");
</code></pre>
<p>44</p>
<pre><code class="lang-plaintext">      return 0;
</code></pre>
<p>45</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">"madam" is palindrome.
"hello" is not palindrome.
</code></pre>
<p><strong>Time complexity:</strong> O(n), where n is the number of characters in the string.<br /><strong>Auxiliary Space:</strong> O(1)</p>
<h2 id="heading-by-using-recursion"><strong>By Using Recursion</strong></h2>
<p>Two-pointer approach can also be implement using recursion. The current first and last index pointers (representing the current first and last characters) can be passed to the function as arguments.</p>
<ul>
<li><p>If the characters at these pointers match, the function increments first pointer, decrements second pointer and then call itself again with updated pointers.</p>
</li>
<li><p>Otherwise, it returns false as the string is not palindrome.</p>
</li>
<li><p>If all the characters match till the first pointer is less than the last pointer, the string is palindrome so return true.</p>
</li>
</ul>
<h3 id="heading-code-implementation-1"><strong>Code Implementation</strong></h3>
<p>C1</p>
<pre><code class="lang-plaintext">// Program to check for a palindrome string
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// using a recursive approach
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">#include &lt;stdio.h&gt;
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">#include &lt;string.h&gt;
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">#include &lt;stdbool.h&gt;
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">// Recursive helper function to check if the string
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">// is palindrome
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">bool palinHelper(char *str, int left, int right) {
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">    // If the start and end pointers cross
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">    // each other, it means all characters
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">    // have matched
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">    if (left &gt;= right)
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">        return true;
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">    // If characters don't match,
</code></pre>
<p>18</p>
<pre><code class="lang-plaintext">    // string is not palindrome
</code></pre>
<p>19</p>
<pre><code class="lang-plaintext">    if (str[left] != str[right])
</code></pre>
<p>20</p>
<pre><code class="lang-plaintext">        return false;
</code></pre>
<p>21</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>22</p>
<pre><code class="lang-plaintext">    // Recursively check for the rest of
</code></pre>
<p>23</p>
<pre><code class="lang-plaintext">    // the string
</code></pre>
<p>24</p>
<pre><code class="lang-plaintext">    return palinHelper(str, left + 1, right - 1);
</code></pre>
<p>25</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p>26</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>27</p>
<pre><code class="lang-plaintext">void isPalindrome(char* str) {
</code></pre>
<p>28</p>
<p>29</p>
<pre><code class="lang-plaintext">      // Calling the recursive function to check
</code></pre>
<p>30</p>
<pre><code class="lang-plaintext">    // palindrome string
</code></pre>
<p>31</p>
<pre><code class="lang-plaintext">    if (palinHelper(str, 0, strlen(str) - 1))
</code></pre>
<p>32</p>
<pre><code class="lang-plaintext">        printf("\"%s\" is palindrome.\n", str);
</code></pre>
<p>33</p>
<pre><code class="lang-plaintext">    else
</code></pre>
<p>34</p>
<pre><code class="lang-plaintext">        printf("\"%s\" is not palindrome.\n", str);
</code></pre>
<p>35</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p>36</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>37</p>
<pre><code class="lang-plaintext">int main() {
</code></pre>
<p>38</p>
<p>39</p>
<pre><code class="lang-plaintext">    // Checking if the given strings are palindrome
</code></pre>
<p>40</p>
<pre><code class="lang-plaintext">    isPalindrome("madam");
</code></pre>
<p>41</p>
<pre><code class="lang-plaintext">    isPalindrome("hello");
</code></pre>
<p>42</p>
<pre><code class="lang-plaintext">    return 0;
</code></pre>
<p>43</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">"madam" is palindrome.
"hello" is not palindrome.
</code></pre>
<p><strong>Time complexity:</strong> O(n), where n is the number of characters in the string.<br /><strong>Auxiliary Space:</strong> O(n), due to recursive stack space.</p>
]]></content:encoded></item><item><title><![CDATA[Java Exceptions Error Handling]]></title><description><![CDATA[Exceptions in Java
Exception Handling in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundEx...]]></description><link>https://development-of-net-banking-application.hashnode.dev/java-exceptions-error-handling</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/java-exceptions-error-handling</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 18:31:21 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-exceptions-in-java">Exceptions in Java</h1>
<p><strong>Exception Handling</strong> in Java is one of the effective means to handle runtime errors so that the regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.</p>
<h2 id="heading-what-are-java-exceptions">What are Java Exceptions?</h2>
<p><strong>In Java, Exception</strong> is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program. When an exception occurs within a method, it creates an object. This object is called the exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.</p>
<h3 id="heading-major-reasons-why-an-exception-occurs"><strong>Major reasons why an exception Occurs</strong></h3>
<ul>
<li><p>Invalid user input</p>
</li>
<li><p>Device failure</p>
</li>
<li><p>Loss of network connection</p>
</li>
<li><p>Physical limitations (out-of-disk memory)</p>
</li>
<li><p>Code errors</p>
</li>
<li><p>Out of bound</p>
</li>
<li><p>Null reference</p>
</li>
<li><p>Type mismatch</p>
</li>
<li><p>Opening an unavailable file</p>
</li>
<li><p>Database errors</p>
</li>
<li><p>Arithmetic errors</p>
</li>
</ul>
<p><strong>Errors</strong> represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. Errors are usually beyond the control of the programmer, and we should not try to handle errors.</p>
<h3 id="heading-difference-between-error-and-exception">Difference between Error and Exception</h3>
<p>Let us discuss the most important part which is the <strong>differences between Error and Exception</strong> that is as follows: </p>
<ul>
<li><p><strong>Error:</strong> An Error indicates a serious problem that a reasonable application should not try to catch.</p>
</li>
<li><p><strong>Exception:</strong> Exception indicates conditions that a reasonable application might try to catch.</p>
</li>
</ul>
<h3 id="heading-exception-hierarchy">Exception Hierarchy</h3>
<p>All exception and error types are subclasses of the class <strong>Throwable</strong>, which is the base class of the hierarchy. One branch is headed by <strong>Exception</strong>. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, <strong>Error</strong> is used by the Java run-time system(<a target="_blank" href="https://www.geeksforgeeks.org/jvm-works-jvm-architecture/"><strong>JVM</strong></a>) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.</p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20230613122108/Exception-Handling-768.png" alt="Exception Hierarchy in Java" /></p>
<h2 id="heading-types-of-exceptions">Types of Exceptions</h2>
<p>Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.</p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20240730174225/Exceptions-in-Java-1-768.webp" alt="Types of Exceptions in Java" /></p>
<p><strong>Exceptions can be categorized in two ways:</strong></p>
<ol>
<li><p><strong>Built-in Exceptions</strong>  </p>
<ul>
<li><p>Checked Exception</p>
</li>
<li><p>Unchecked Exception </p>
</li>
</ul>
</li>
<li><p><strong>User-Defined Exceptions</strong></p>
</li>
</ol>
<p>Let us discuss the above-defined listed exception that is as follows:</p>
<h3 id="heading-1-built-in-exceptions"><strong>1. Built-in Exceptions</strong></h3>
<p>Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations.</p>
<ul>
<li><strong>Checked Exceptions:</strong> Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler.  </li>
</ul>
<ul>
<li><strong>Unchecked Exceptions:</strong> The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error.</li>
</ul>
<blockquote>
<p><strong><em>Note:</em></strong> <em>For checked vs unchecked exception, see</em> <a target="_blank" href="https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/"><strong><em>Checked vs Unchecked Exceptions</em></strong></a> </p>
</blockquote>
<p><a target="_blank" href="https://www.geeksforgeeks.org/problems/java-exception-handling/1?itm_source=geeksforgeeks&amp;itm_medium=article&amp;itm_campaign=practice_card"><strong>Try it on GfG Practice</strong></a></p>
<p><img src="https://media.geeksforgeeks.org/auth-dashboard-uploads/Group-arrow.svg" alt="redirect icon" /></p>
<h3 id="heading-2-user-defined-exceptions"><strong>2. User-Defined Exceptions:</strong></h3>
<p>Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called ‘user-defined Exceptions’. </p>
<p>The <strong><em>advantages of Exception Handling in Java</em></strong> are as follows:</p>
<ol>
<li><p>Provision to Complete Program Execution</p>
</li>
<li><p>Easy Identification of Program Code and Error-Handling Code</p>
</li>
<li><p>Propagation of Errors</p>
</li>
<li><p>Meaningful Error Reporting</p>
</li>
<li><p>Identifying Error Types</p>
</li>
</ol>
<p><strong>Methods to print the Exception information:</strong></p>
<h4 id="heading-1-printstacktrace"><strong>1. printStackTrace()</strong></h4>
<p>This method prints exception information in the format of the Name of the exception: description of the exception, stack trace.</p>
<p><strong>Example:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">//program to print the exception information using printStackTrace() method
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">import java.io.*;
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">class GFG {
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    public static void main (String[] args) {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">      int a=5;
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">      int b=0;
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        try{
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">          System.out.println(a/b);
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">      catch(ArithmeticException e){
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">        e.printStackTrace();
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">      }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
</code></pre>
<h4 id="heading-2-tostring"><strong>2. toString()</strong></h4>
<p>The toString() method prints exception information in the format of the Name of the exception: description of the exception.</p>
<p><strong>Example:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">//program to print the exception information using toString() method
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">import java.io.*;
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">class GFG1 {
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    public static void main (String[] args) {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">      int a=5;
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">      int b=0;
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        try{
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">          System.out.println(a/b);
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">      catch(ArithmeticException e){
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">        System.out.println(e.toString());
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">      }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">java.lang.ArithmeticException: / by zero
</code></pre>
<h4 id="heading-3-getmessage"><strong>3. getMessage()</strong></h4>
<p>The getMessage() method prints only the description of the exception.</p>
<p><strong>Example:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">//program to print the exception information using getMessage() method
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">import java.io.*;
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">class GFG1 {
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">    public static void main (String[] args) {
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">      int a=5;
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">      int b=0;
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">        try{
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">          System.out.println(a/b);
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">      catch(ArithmeticException e){
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">        System.out.println(e.getMessage());
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">      }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">/ by zero
</code></pre>
<blockquote>
<h2 id="heading-how-does-jvm-handle-an-exception">How Does JVM Handle an Exception?</h2>
</blockquote>
<p><strong>Default Exception Handling:</strong> Whenever inside a method, if an exception has occurred, the method creates an Object known as an Exception Object and hands it off to the run-time system(JVM). The exception object contains the name and description of the exception and the current state of the program where the exception has occurred. Creating the Exception Object and handling it in the run-time system is called throwing an Exception. There might be a list of the methods that had been called to get to the method where an exception occurred. This ordered list of methods is called <strong>Call Stack</strong>. Now the following procedure will happen. </p>
<ul>
<li><p>The run-time system searches the call stack to find the method that contains a block of code that can handle the occurred exception. The block of the code is called an <strong>Exception handler</strong>.</p>
</li>
<li><p>The run-time system starts searching from the method in which the exception occurred and proceeds through the call stack in the reverse order in which methods were called.</p>
</li>
<li><p>If it finds an appropriate handler, then it passes the occurred exception to it. An appropriate handler means the type of exception object thrown matches the type of exception object it can handle.</p>
</li>
<li><p>If the run-time system searches all the methods on the call stack and couldn’t have found the appropriate handler, then the run-time system handover the Exception Object to the <strong>default exception handler</strong>, which is part of the run-time system. This handler prints the exception information in the following format and terminates the program <strong>abnormally</strong>.</p>
</li>
</ul>
<pre><code class="lang-plaintext">Exception in thread "xxx" Name of Exception : Description
... ...... ..  // Call Stack
</code></pre>
<p>Look at the below diagram to understand the flow of the call stack. </p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20230714113633/Exceptions-in-Java2-768.png" alt="Flow of class stack for exceptions in Java" /></p>
<p><strong>Illustration:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">// Java Program to Demonstrate How Exception Is Thrown
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">// Class
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">// ThrowsExecp
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">class GFG {
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">    // Main driver method
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">    public static void main(String args[])
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">        // Taking an empty string
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        String str = null;
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">        // Getting length of a string
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">        System.out.println(str.length());
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20220413093747/Screenshot20220413at93720AM.png" alt="program output" /></p>
<p>Let us see an example that illustrates how a run-time system searches for appropriate exception handling code on the call stack.</p>
<p><strong>Example:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">// Java Program to Demonstrate Exception is Thrown
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// How the runTime System Searches Call-Stack
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">// to Find Appropriate Exception Handler
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">// Class
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">// ExceptionThrown
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">class GFG {
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">    // Method 1
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">    // It throws the Exception(ArithmeticException).
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">    // Appropriate Exception handler is not found
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">    // within this method.
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">    static int divideByZero(int a, int b)
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">        // this statement will cause ArithmeticException
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">        // (/by zero)
</code></pre>
<p>18</p>
<pre><code class="lang-plaintext">        int i = a / b;
</code></pre>
<p>19</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>20</p>
<pre><code class="lang-plaintext">        return i;
</code></pre>
<p>21</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>22</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>23</p>
<pre><code class="lang-plaintext">    // The runTime System searches the appropriate
</code></pre>
<p>24</p>
<pre><code class="lang-plaintext">    // Exception handler in method also but couldn't have
</code></pre>
<p>25</p>
<pre><code class="lang-plaintext">    // found. So looking forward on the call stack
</code></pre>
<p>26</p>
<pre><code class="lang-plaintext">    static int computeDivision(int a, int b)
</code></pre>
<p>27</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>28</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>29</p>
<pre><code class="lang-plaintext">        int res = 0;
</code></pre>
<p>30</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>31</p>
<pre><code class="lang-plaintext">        // Try block to check for exceptions
</code></pre>
<p>32</p>
<pre><code class="lang-plaintext">        try {
</code></pre>
<p>33</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>34</p>
<pre><code class="lang-plaintext">            res = divideByZero(a, b);
</code></pre>
<p>35</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>36</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>37</p>
<pre><code class="lang-plaintext">        // Catch block to handle NumberFormatException
</code></pre>
<p>38</p>
<pre><code class="lang-plaintext">        // exception Doesn't matches with
</code></pre>
<p>39</p>
<pre><code class="lang-plaintext">        // ArithmeticException
</code></pre>
<p>40</p>
<pre><code class="lang-plaintext">        catch (NumberFormatException ex) {
</code></pre>
<p>41</p>
<pre><code class="lang-plaintext">            // Display message when exception occurs
</code></pre>
<p>42</p>
<pre><code class="lang-plaintext">            System.out.println(
</code></pre>
<p>43</p>
<pre><code class="lang-plaintext">                "NumberFormatException is occurred");
</code></pre>
<p>44</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>45</p>
<pre><code class="lang-plaintext">        return res;
</code></pre>
<p>46</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>47</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>48</p>
<pre><code class="lang-plaintext">    // Method 2
</code></pre>
<p>49</p>
<pre><code class="lang-plaintext">    // Found appropriate Exception handler.
</code></pre>
<p>50</p>
<pre><code class="lang-plaintext">    // i.e. matching catch block.
</code></pre>
<p>51</p>
<pre><code class="lang-plaintext">    public static void main(String args[])
</code></pre>
<p>52</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>53</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>54</p>
<pre><code class="lang-plaintext">        int a = 1;
</code></pre>
<p>55</p>
<pre><code class="lang-plaintext">        int b = 0;
</code></pre>
<p>56</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>57</p>
<pre><code class="lang-plaintext">        // Try block to check for exceptions
</code></pre>
<p>58</p>
<pre><code class="lang-plaintext">        try {
</code></pre>
<p>59</p>
<pre><code class="lang-plaintext">            int i = computeDivision(a, b);
</code></pre>
<p>60</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>61</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>62</p>
<pre><code class="lang-plaintext">        // Catch block to handle ArithmeticException
</code></pre>
<p>63</p>
<pre><code class="lang-plaintext">        // exceptions
</code></pre>
<p>64</p>
<pre><code class="lang-plaintext">        catch (ArithmeticException ex) {
</code></pre>
<p>65</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>66</p>
<pre><code class="lang-plaintext">            // getMessage() will print description
</code></pre>
<p>67</p>
<pre><code class="lang-plaintext">            // of exception(here / by zero)
</code></pre>
<p>68</p>
<pre><code class="lang-plaintext">            System.out.println(ex.getMessage());
</code></pre>
<p>69</p>
<pre><code class="lang-plaintext">        }
</code></pre>
<p>70</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>71</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<pre><code class="lang-plaintext">/ by zero
</code></pre>
<h2 id="heading-how-programmer-handle-an-exception">How Programmer Handle an Exception?</h2>
<p><strong>Customized Exception Handling:</strong> Java exception handling is managed via five keywords: <strong>try</strong>, <strong>catch</strong>, <a target="_blank" href="https://www.geeksforgeeks.org/throw-throws-java/"><strong>throw</strong></a>, <a target="_blank" href="https://www.geeksforgeeks.org/throw-throws-java/"><strong>throws</strong></a>, and <strong>finally</strong>. Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.</p>
<blockquote>
<p><strong><em>Tip:</em></strong> <em>One must go through</em> <a target="_blank" href="https://www.geeksforgeeks.org/flow-control-in-try-catch-finally-in-java/"><strong><em>control flow in try catch finally block for better understanding.</em></strong></a>  </p>
</blockquote>
<h3 id="heading-need-for-try-catch-clausecustomized-exception-handling">Need for try-catch clause(Customized Exception Handling)</h3>
<p>Consider the below program in order to get a better understanding of the try-catch clause.</p>
<p><strong>Example:</strong></p>
<p>Java1</p>
<pre><code class="lang-plaintext">// Java Program to Demonstrate
</code></pre>
<p>2</p>
<pre><code class="lang-plaintext">// Need of try-catch Clause
</code></pre>
<p>3</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>4</p>
<pre><code class="lang-plaintext">// Class
</code></pre>
<p>5</p>
<pre><code class="lang-plaintext">class GFG {
</code></pre>
<p>6</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>7</p>
<pre><code class="lang-plaintext">    // Main driver method
</code></pre>
<p>8</p>
<pre><code class="lang-plaintext">    public static void main(String[] args)
</code></pre>
<p>9</p>
<pre><code class="lang-plaintext">    {
</code></pre>
<p>10</p>
<pre><code class="lang-plaintext">        // Taking an array of size 4
</code></pre>
<p>11</p>
<pre><code class="lang-plaintext">        int[] arr = new int[4];
</code></pre>
<p>12</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>13</p>
<pre><code class="lang-plaintext">        // Now this statement will cause an exception
</code></pre>
<p>14</p>
<pre><code class="lang-plaintext">        int i = arr[4];
</code></pre>
<p>15</p>
<pre><code class="lang-plaintext">​
</code></pre>
<p>16</p>
<pre><code class="lang-plaintext">        // This statement will never execute
</code></pre>
<p>17</p>
<pre><code class="lang-plaintext">        // as above we caught with an exception
</code></pre>
<p>18</p>
<pre><code class="lang-plaintext">        System.out.println("Hi, I want to execute");
</code></pre>
<p>19</p>
<pre><code class="lang-plaintext">    }
</code></pre>
<p>20</p>
<pre><code class="lang-plaintext">}
</code></pre>
<p><strong>Output</strong></p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20220413095146/Screenshot20220413at95119AM.png" alt="program output" /></p>
<p><strong>Output explanation:</strong> In the above example, an array is defined with size i.e. you can access elements only from index 0 to 3. But you trying to access the elements at index 4(by mistake) that’s why it is throwing an exception. In this case, JVM terminates the program <strong>abnormally</strong>. The statement System.out.println(“Hi, I want to execute”); will never execute. To execute it, we must handle the exception using try-catch. Hence to continue the normal flow of the program, we need a try-catch clause. </p>
<h3 id="heading-how-to-use-the-try-catch-clause"><strong>How to Use the Try-catch Clause?</strong></h3>
<pre><code class="lang-plaintext">try {
    // block of code to monitor for errors
    // the code you think can raise an exception
} catch (ExceptionType1 exOb) {
    // exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
    // exception handler for ExceptionType2
}
// optional
finally {  // block of code to be executed after try block ends 
}
</code></pre>
<p>Certain key points need to be remembered that are as follows:   </p>
<ul>
<li><p>In a method, there can be more than one statement that might throw an exception, So put all these statements within their own <strong>try</strong> block and provide a separate exception handler within their own <strong>catch</strong> block for each of them.</p>
</li>
<li><p>If an exception occurs within the <strong>try</strong> block, that exception is handled by the exception handler associated with it. To associate the exception handler, we must put a <strong>catch</strong> block after it. There can be more than one exception handler. Each <strong>catch</strong> block is an exception handler that handles the exception to the type indicated by its argument. The argument, ExceptionType declares the type of exception that it can handle and must be the name of the class that inherits from the <strong>Throwable</strong> class.</p>
</li>
<li><p>For each try block, there can be zero or more catch blocks, but <strong>only one</strong> final block.</p>
</li>
<li><p>The finally block is optional. It always gets executed whether an exception occurred in try block or not. If an exception occurs, then it will be executed after <strong>try and catch blocks.</strong> And if an exception does not occur, then it will be executed after the <strong>try</strong> block. The finally block in Java is used to put important codes such as clean-up code e.g., closing the file or closing the connection.</p>
</li>
<li><p>If we write System.exit in the try block, then finally block will not be executed.</p>
</li>
</ul>
<p>The summary is depicted via visual aid below as follows: </p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20230714113728/Exceptions-in-Java-3-768.png" alt="Exceptions in Java" /></p>
<p><strong>Related Articles:</strong>  </p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/types-of-exception-in-java-with-examples/"><strong>Types of Exceptions in Java</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/"><strong>Checked vs Unchecked Exceptions</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/throw-throws-java/"><strong>Throw-Throws in Java</strong></a></p>
</li>
</ul>
<p>Want to be a master in <strong>Backend Development with Java</strong> for building robust and scalable applications? Enroll in <a target="_blank" href="https://gfgcdn.com/tu/Q8Q/"><strong>Java Backend and Development Live Course</strong></a> by GeeksforGeeks to get your hands dirty with Backend Programming. Master the key <strong>Java concepts, server-side programming, database integration</strong>, and more through hands-on experiences and <strong>live projects</strong>. Are you new to Backend development or want to be a Java Pro? This course equips you with all you need for building high-performance, heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the next level? Enroll now and take your development career to sky highs.</p>
]]></content:encoded></item><item><title><![CDATA[Java Oops]]></title><description><![CDATA[Write a Java program to create a class called "Person" with a name and age attribute. Create two instances of the "Person" class, set their attributes using the constructor, and print their name and age.
Solution:
Java Code:
 // Define the Person cla...]]></description><link>https://development-of-net-banking-application.hashnode.dev/java-oops</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/java-oops</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 18:20:59 GMT</pubDate><content:encoded><![CDATA[<p>Write a Java program to create a class called "Person" with a name and age attribute. Create two instances of the "Person" class, set their attributes using the constructor, and print their name and age.</p>
<p><strong>Solution:</strong></p>
<p><strong>Java Code:</strong></p>
<pre><code class="lang-java"> <span class="hljs-comment">// Define the Person class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-comment">// Declare a private variable to store the name of the person</span>
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-comment">// Declare a private variable to store the age of the person</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-comment">// Constructor for the Person class that initializes the name and age variables</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-comment">// Set the name variable to the provided name parameter</span>
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-comment">// Set the age variable to the provided age parameter</span>
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-comment">// Method to retrieve the name of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Return the value of the name variable</span>
        <span class="hljs-keyword">return</span> name;
    }

    <span class="hljs-comment">// Method to retrieve the age of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Return the value of the age variable</span>
        <span class="hljs-keyword">return</span> age;
    }

    <span class="hljs-comment">// Method to set the name of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-comment">// Set the name variable to the provided name parameter</span>
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-comment">// Method to set the age of the person</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-comment">// Set the age variable to the provided age parameter</span>
        <span class="hljs-keyword">this</span>.age = age;
    }
}
</code></pre>
<p>The above class has two private attributes: name and age, and a constructor that initializes these attributes with the values passed as arguments. It also has a getter method to access the attributes.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Define the Main class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-comment">// Define the main method which is the entry point of the program</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create an instance of the Person class with the name "Ean Craig" and age 11</span>
        Person person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Ean Craig"</span>, <span class="hljs-number">11</span>);
        <span class="hljs-comment">// Create another instance of the Person class with the name "Evan Ross" and age 12</span>
        Person person2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Evan Ross"</span>, <span class="hljs-number">12</span>);

        <span class="hljs-comment">// Print the name and age of person1 to the console</span>
        System.out.println(person1.getName() + <span class="hljs-string">" is "</span> + person1.getAge() + <span class="hljs-string">" years old."</span>);
        <span class="hljs-comment">// Print the name and age of person2 to the console</span>
        System.out.println(person2.getName() + <span class="hljs-string">" is "</span> + person2.getAge() + <span class="hljs-string">" years old.\n"</span>);

        <span class="hljs-comment">// Modify the age of person1 using the setter methods</span>
        person1.setAge(<span class="hljs-number">14</span>);
        <span class="hljs-comment">// Modify the name and age of person2 using the setter methods</span>
        person2.setName(<span class="hljs-string">"Lewis Jordan"</span>);
        person2.setAge(<span class="hljs-number">12</span>);
        System.out.println(<span class="hljs-string">"Set new age and name:"</span>);
        <span class="hljs-comment">// Print the updated name and age of person1 to the console</span>
        System.out.println(person1.getName() + <span class="hljs-string">" is now "</span> + person1.getAge() + <span class="hljs-string">" years old."</span>);
        <span class="hljs-comment">// Print the updated name and age of person2 to the console</span>
        System.out.println(person2.getName() + <span class="hljs-string">" is now "</span> + person2.getAge() + <span class="hljs-string">" years old."</span>);
    }
}
</code></pre>
<p>In the above example, we create two instances of the "Person" class, set their attributes with the constructor, and print their name and age using the getter methods. We also modify the attributes using the setter methods and print the updated values.</p>
<p>Sample Output:</p>
<pre><code class="lang-plaintext">Ean Craig is 11 years old.
Evan Ross is 12 years old.

Set new age and name:
Ean Craig is now 14 years old.
Lewis Jordan is now 12 years old.
</code></pre>
<p><strong>Flowchart:</strong></p>
<p><img src="https://www.w3resource.com/w3r_images/java-oop-exercise-flowchart-1.png" alt="Flowchart: Java  OOP Exercises: Create and print Person objects." /></p>
<p><strong>Java Code Editor:</strong></p>
<iframe src="https://trinket.io/embed/java/b021d3a641" width="100%" height="500" style="vertical-align:middle;display:block;width:1082.8px;border:3px solid silver;color:rgba(0, 0, 0, 0.87);font-family:Helvetica, Arial, sans-serif;font-size:16px;font-style:normal;font-variant-ligatures:normal;font-variant-caps:normal;font-weight:400;letter-spacing:normal;orphans:2;text-align:start;text-indent:0px;text-transform:none;widows:2;word-spacing:0px;-webkit-text-stroke-width:0px;white-space:normal;background-color:rgb(255, 255, 255);text-decoration-thickness:initial;text-decoration-style:initial;text-decoration-color:initial"></iframe>]]></content:encoded></item><item><title><![CDATA[Selenium Locators 

How to run Selenium tests on Chrome using ChromeDriver?]]></title><description><![CDATA[import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Max {

public static void main(String args[]) throws InterruptedException
{

System.setProperty("<Path of the ChromeDriver>");

ChromeOptions options ...]]></description><link>https://development-of-net-banking-application.hashnode.dev/selenium-locators-how-to-run-selenium-tests-on-chrome-using-chromedriver</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/selenium-locators-how-to-run-selenium-tests-on-chrome-using-chromedriver</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 18:05:13 GMT</pubDate><content:encoded><![CDATA[<pre><code class="lang-plaintext">import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Max {

public static void main(String args[]) throws InterruptedException
{

System.setProperty("&lt;Path of the ChromeDriver&gt;");

ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");

WebDriver driver = new ChromeDriver(options);

// Navigate to a website
driver.get("https://www.browserstack.com/")

//Close the browser
driver.quit();
} 
}
</code></pre>
<p><strong>Code:</strong></p>
<pre><code class="lang-plaintext">import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Max {

public static void main(String args[]) throws InterruptedException
{
System.setProperty("&lt;Path of the ChromeDriver&gt;");
WebDriver driver = new ChromeDriver();

// Navigate to a website
driver.get("https://www.browserstack.com/");

//Mazimize current window
driver.manage().window().maximize();

//Delay execution for 5 seconds to view the maximize operation
Thread.sleep(5000);

//Close the browser
driver.quit();
} 
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Window and frames]]></title><description><![CDATA[How to Write Automated Test Scripts Using Selenium
What is Selenium?
Selenium is a tool for testing web applications. Selenium tests run directly on browsers. Supported browsers include IE (7, 8, 9, 10, 11), Mozilla, Firefox, Safari, Google Chrome, o...]]></description><link>https://development-of-net-banking-application.hashnode.dev/window-and-frames</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/window-and-frames</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 17:14:27 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.prod.website-files.com/619e15d781b21202de206fb5/6267a1eeb5de188bb281bc88_How-to-Write-an-Automated-Test-Script-Using-Selenium-1280x720%20(2)%20(1).jpg" alt="Writing Automated Test Scripts Using Selenium" /></p>
<h1 id="heading-how-to-write-automated-test-scripts-using-selenium"><strong>How to Write Automated Test Scripts Using Selenium</strong></h1>
<h2 id="heading-what-is-selenium"><strong>What is Selenium?</strong></h2>
<p>Selenium is a tool for testing web applications. Selenium tests run directly on browsers. Supported browsers include IE (7, 8, 9, 10, 11), Mozilla, Firefox, Safari, Google Chrome, opera, edge, etc. The main functions of this tool include: testing compatibility with browsers - and testing applications to see if they can work well on different browsers and operating systems. Test system functions -create regression tests to verify software functions and user requirements. Support automatic action recording and automatic generation of Net, Java, Perl and other test scripts in different languages.</p>
<h2 id="heading-what-is-a-selenium-script"><strong>What is a Selenium Script</strong></h2>
<p>A Selenium script is instructions written to automate interactions with a web browser. It simulates user actions such as clicking links, entering text, and navigating between pages. These scripts are essential for testing web applications and ensuring they function correctly across different browsers and platforms.</p>
<p>Selenium, an open-source framework, provides tools like WebDriver to facilitate browser automation. Developers and testers can write Selenium scripts in various programming languages, including Java, Python, C#, Ruby, and JavaScript, allowing flexibility based on the project's requirements. By executing these scripts, teams can perform repetitive testing tasks efficiently, identify bugs, and verify that web applications meet specified requirements.</p>
<p>For example, a Selenium script can automate logging into a website by locating the username and password fields, entering credentials, and clicking the login button.</p>
<h2 id="heading-what-are-the-advantages-of-making-selenium-so-widely-used"><strong>What are the advantages of making Selenium so widely used?</strong></h2>
<p>JavaScript is used by the bottom layer of the framework to simulate real users to operate the browser. The browser will automatically click, input, open, verify and perform other operations according to the script code when the test script is executed. Like what real users do, test the application from the end-user's perspective, enabling automation of <a target="_blank" href="https://www.headspin.io/blog/best-practices-cross-browser-compatibility">browser compatibility testing</a>, although there are subtle differences between different browsers.</p>
<p>Easy to use, you can use Java, Python, and other languages to write use case scripts.</p>
<ul>
<li><p>Selenium is completely an open-source framework and has no restrictions on commercial users. It supports distribution and has mature community and learning documents</p>
</li>
<li><h1 id="heading-writing-automated-tests-using-selenium-and-java">Writing Automated Tests Using Selenium and Java</h1>
<p>  Testing with Java and Selenium helps software development teams save time, reduce errors, and become more efficient. Learn how to get started with both in this blog post.</p>
<p>  Documentation</p>
<p>  <a target="_blank" href="https://docs.saucelabs.com/web-apps/automated-testing/selenium/">Using Selenium with Sauce Labs</a></p>
<p>  <a target="_blank" href="https://docs.saucelabs.com/web-apps/automated-testing/selenium/quickstart/#selenium-webdriver-tests">Selenium WebDriver Tests</a></p>
<p>  In the world of fast-paced software delivery, <a target="_blank" href="https://saucelabs.com/resources/blog/getting-started-with-automated-testing">automated testing</a> is all but a necessity. Automated testing enables development teams to validate code changes in a fast and repeatable fashion, providing assurances of quality as new features and modifications are delivered to end users.</p>
<p>  Below, we will discuss the <a target="_blank" href="https://saucelabs.com/resources/blog/getting-started-with-selenium">Selenium test automation framework</a>. We will focus on what it is and how Selenium WebDriver is used in web application testing. Furthermore, we will discuss the Java programming language and demonstrate how to get started writing automated tests using <a target="_blank" href="https://saucelabs.com/resources/blog/what-is-a-selenium-webdriver">Selenium WebDriver</a> and Java.</p>
<h2 id="heading-what-is-selenium-1">What is Selenium?</h2>
<p>  <a target="_blank" href="https://www.selenium.dev/">Selenium</a> refers to several projects that help automate actions taken in a web browser. One such project is <a target="_blank" href="https://saucelabs.com/resources/blog/getting-started-with-webdriver-in-c-using-visual-studio">Selenium WebDriver</a>. WebDriver provides an object-oriented API and bindings for several popular programming languages. Thus, it enables developers to write UI test scripts for <a target="_blank" href="https://www.selenium.dev/documentation/webdriver/browsers/">the major browsers</a> in use today in programming languages with which they are familiar. Development teams can leverage WebDriver to build suites of these test scripts and run them in an automated fashion at various stages of the software development lifecycle.</p>
<p>  WebDriver enables development organizations to reap the benefits of <a target="_blank" href="https://saucelabs.com/resources/blog/test-automation-tutorial">test automation</a>. For instance, automated UI testing is faster than manually testing the UI. This saves time and allows important development and QA resources to focus on other initiatives, such as building more features that increase the value of the product or providing more time for exploratory testing.</p>
<p>  Furthermore, <a target="_blank" href="https://saucelabs.com/resources/blog/top-ui-testing-tools">automating UI tests</a> is a step toward increasing test coverage. Because manual testing takes longer and chews up more resources, teams are limited in how much they can actually test. By automating this process, more tests can be executed in less time, allowing for a greater percentage of functionality to be validated with each integration or release.</p>
<p>  Finally, automated UI testing eliminates the risk of human error (assuming the script is properly developed and maintained). Each automated test script will execute each step in exactly the same fashion each time. In manual testing, however, there is always a risk that the tester will take incorrect action at some point in the testing process, thereby invalidating the result. This could lead to the deployment of code that is not working as expected into production.</p>
<h2 id="heading-what-is-java">What is Java?</h2>
<p>  Java is a popular programming language and software platform. It is class-based and object-oriented, enabling experienced developers to build applications with concise, readable, and easily maintained codebases. Java is also portable, which allows Java applications to run on many different systems.</p>
<p>  Java can be leveraged for a variety of use cases including web development, machine learning, data processing, and more.</p>
<h3 id="heading-benefits-of-selenium-with-java-for-developers">Benefits of Selenium with Java for developers</h3>
<p>  Owing in part to its popularity, Java offers the following benefits for developers <a target="_blank" href="https://docs.saucelabs.com/web-apps/automated-testing/selenium/">writing Selenium test scripts</a>:</p>
<ul>
<li><p>Java has been around for a long time and is used by many organizations. Therefore, it can be easier to find developers with Java experience.</p>
</li>
<li><p>Additionally, Java has excellent community support. When a developer runs into difficulty doing something in Java, help is often easy to find. Java’s longevity and popularity mean that countless developers have likely encountered the same problem, leading to a plethora of online resources available for troubleshooting.</p>
</li>
</ul>
</li>
</ul>
<p>    Combining the above with the fact that Selenium WebDriver itself is <a target="_blank" href="https://www.selenium.dev/documentation/webdriver/">well-documented</a> and has excellent <a target="_blank" href="https://www.selenium.dev/support/">community support</a>, development teams may find that it’s easier to start writing automated UI test scripts with Selenium and Java than they thought.</p>
<h2 id="heading-getting-started-with-selenium-in-java">Getting Started with Selenium in Java</h2>
<p>    Now that we’ve covered the basics of what Selenium and Java are and how automated UI testing can benefit your organization, it’s time to dive into the tutorial portion of this article. Below, we will walk you through the following:</p>
<ul>
<li><p>Setting up Java on your local machine</p>
</li>
<li><p>Installing and configuring the Eclipse IDE</p>
</li>
<li><p>Creating your Java project</p>
</li>
<li><p>Importing Selenium and JUnit dependencies</p>
</li>
<li><p>Writing a simple UI test script using Java and Selenium WebDriver</p>
</li>
</ul>
<h3 id="heading-1-set-up-java-on-your-local-machine">1. Set up Java on your local machine</h3>
<p>    Our first step in getting our local environment configured will be to install the Java Development Kit (or JDK). For our purposes, JDK 17 is appropriate and can be downloaded <a target="_blank" href="https://www.oracle.com/java/technologies/downloads/#java17">here</a>.</p>
<p>    Choose the appropriate option for the OS on which you are working, then download and install it. For Windows 10 users, the x64 Installer will suffice. After downloading, the installer allows you to set the location where the JDK will be installed. The default installation location in this instance is C:\Program Files\Java\jdk-17\.</p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/4QP9q70J3zIKckGuAVBBmG/3e017beeb0ec8476a67412e14919996a/java-installer.png" alt /></p>
<p>    After completing the installation, verify it by opening a command prompt and running the following command:</p>
<p>    <code>java -version</code></p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/1QAuuMzYx5hPRD0Bf1LOL5/ccb885856be2b2abac996a45d6a57bba/command-prompt.png" alt /></p>
<h3 id="heading-2-install-and-configure-the-eclipse-ide">2. Install and configure the Eclipse IDE</h3>
<p>    With Java installed, we will need an IDE in which we’ll write our code. The Eclipse IDE is a popular option that will suit our purposes just fine. Eclipse can be downloaded <a target="_blank" href="https://www.eclipse.org/downloads/">here</a>.</p>
<p>    Choose <strong>Eclipse IDE for Java Developers</strong> and select the download that will work with your operating system. Proceed with the installation, installing to the directory of your choice.</p>
<p>    After installing and opening Eclipse, we can ensure that it uses the JDK we installed in the previous step. In the navbar at the top of Eclipse, click <strong>Window</strong> followed by <strong>Preferences</strong>.</p>
<p>    In the <strong>Preferences</strong> modal, expand <strong>Java</strong> and select <strong>Installed JREs</strong>. From within the <em>I**</em>nstalled JREs<strong> window, click </strong>Add<strong> and select </strong>Standard VM**.</p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/1DLgtsBzolkgsc0ZGkmBrE/577869f2558bf13600035a88c9103eba/installed-jres.png" alt /></p>
<p>    Click <strong>Next</strong> and set <strong>JRE home</strong> to the location of the newly installed JDK. Click <strong>Finish</strong> and check the box next to the JRE entry that you just configured.</p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/3UlAbyMwrWlN4CtY11k1M/a094c4a476472905b834a50c0e0b33da/installed-jres.png" alt /></p>
<h3 id="heading-3-create-your-java-project">3. Create your Java project</h3>
<p>    Now, let’s create a very simple Maven project that we can use to import Selenium and JUnit dependencies and write our sample test script.</p>
<p>    Open Eclipse to a clean workspace location. I’ll be using the following location on my machine:</p>
<p>    <code>C:\development\workspace</code></p>
<p>    To create your project in Eclipse, go to <strong>File</strong>, then <strong>New</strong>, and then click Maven Project. Check the box <strong>Create a simple project (skip archetype selection)</strong> and leave <strong>Use default Workspace location</strong> checked. Click <strong>Next</strong> to proceed.</p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/41EYPVyXRiV98JhqsmulaR/ac8e336967bfce78a06d3661ae91999c/new-maven-project.png" alt /></p>
<p>    On the next screen, enter <code>samples</code> as the <strong>Group Id</strong> and <code>selenium-with-java</code> as the <strong>Artifact Id</strong>. Then click <strong>Finish</strong>.</p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/1P9duVaua1v8BgeOdPrK0h/835f6c650f69ac1d2d413b5075795023/new-maven-project-finish.png" alt /></p>
<p>    With that, the project has been created and we can get to work. It should now show in the <em>Package Explorer</em> view within your Eclipse IDE.</p>
<h3 id="heading-4-import-the-selenium-and-junit-dependencies">4. Import the Selenium and JUnit dependencies</h3>
<p>    The next step is to bring in the dependencies required to write our sample test script. For the purposes of this demonstration, we’ll need the Selenium WebDriver language bindings for Java as well as the JUnit Jupiter API.</p>
<p>    To pull in version 4.10.0 of the Selenium libraries for Java, add the following to the dependencies portion of your POM file:</p>
<p>    <code>&lt;dependency&gt;</code></p>
<p>    <code>&lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;</code></p>
<p>    <code>&lt;artifactId&gt;selenium-java&lt;/artifactId&gt;</code></p>
<p>    <code>&lt;version&gt;4.10.0&lt;/version&gt;</code></p>
<p>    <code>&lt;/dependency&gt;</code></p>
<p>    More information on this can be found in the <a target="_blank" href="https://www.selenium.dev/documentation/webdriver/getting_started/install_library/">Selenium WebDriver installation documentation</a>.</p>
<p>    Similarly, to pull in version 5.9.3 of the JUnit Jupiter API, add the following to the dependencies portion of your POM file:</p>
<p>    <code>&lt;dependency&gt;</code></p>
<p>    <code>&lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;</code></p>
<p>    <code>&lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;</code></p>
<p>    <code>&lt;version&gt;5.9.3&lt;/version&gt;</code></p>
<p>    <code>&lt;/dependency&gt;</code></p>
<p>    Right-click on your project, navigate to <strong>Maven</strong>, then <strong>Update Project</strong>, and select the sample project to update. Clicking <strong>OK</strong> should ensure that the above dependencies are pulled in and can now be utilized within your code.</p>
<h3 id="heading-5-write-a-simple-ui-test-script-using-java-and-selenium-webdriver">5. Write a simple UI Test script using Java and Selenium WebDriver</h3>
<p>    With our new Java project created and our dependencies pulled in, we can now proceed with developing a test script.</p>
<p>    For this example, we’ll navigate to the Sauce Labs <a target="_blank" href="https://saucelabs.com/request-demo">Request a Demo page</a> in Google Chrome and ensure that the first name field, last name field, and company field are present on the page.</p>
<p>    The first step is to create a Java class within our project. To do so in Eclipse, go to <strong>File</strong>, then <strong>New</strong>, and select <strong>Class</strong>. Enter the package in which you wish to create your class as well as the class name. Let’s store this class in a package called selenium and name the class <strong>SauceTest</strong>.</p>
<p>    Click <strong>Finish</strong> to create the file <code>SauceTest.java</code>.</p>
<p>    The next step is to create our <code>setUp</code> and <code>tearDown</code> methods. We will annotate these with <code>@BeforeEach</code> and <code>@AfterEach</code>, respectively, so that they run before and after each method annotated with <code>@Test</code>. The <code>setUp</code> method will be responsible for configuring our class variable <code>webDriver</code> as a <code>ChromeDriver</code>, while <code>tearDown</code> will be responsible for calling <code>quit</code> on <code>webDriver</code> and closing all associated Chrome windows. Here’s what those two methods will look like:</p>
<p>    <code>@BeforeEach</code></p>
<p>    <code>public void setUp() {</code></p>
<p>    <code>System.out.println("*** set up ***");</code></p>
<p>    <code>System.setProperty("webdriver.chrome.driver", "C://development//chromedriver//chromedriver.exe");</code></p>
<p>    <code>webDriver = new ChromeDriver();</code></p>
<p>    <code>}</code></p>
<p>    <code>@AfterEach</code></p>
<p>    <code>public void tearDown() {</code></p>
<p>    <code>System.out.println("*** tear down ***");</code></p>
<p>    <code>webDriver.quit();</code></p>
<p>    <code>}</code></p>
<p>    Next, we’ll build our <code>demoFormTest</code> method annotated with <code>@Test</code>. This method will use the Selenium dependencies that we’ve pulled into our project to accomplish the following:</p>
<ul>
<li><p>Open a Chrome window</p>
</li>
<li><p>Navigate to <a target="_blank" href="https://saucelabs.com/request-demo">https://saucelabs.com/request-demo</a></p>
</li>
<li><p>Check for the existence of the first name, last name, and company fields</p>
</li>
</ul>
<p>    The test will pass if all three fields are present. If any of the three fields are not present, the test will fail. Please see the full <code>SauceTest</code> class below:</p>
<p>    <code>package selenium;</code></p>
<p>    <code>import static org.junit.jupiter.api.Assertions.assertTrue;</code></p>
<p>    <code>import org.junit.jupiter.api.AfterEach;</code></p>
<p>    <code>import org.junit.jupiter.api.BeforeEach;</code></p>
<p>    <code>import org.junit.jupiter.api.Test;</code></p>
<p>    <code>import org.openqa.selenium.By;</code></p>
<p>    <code>import org.openqa.selenium.NoSuchElementException;</code></p>
<p>    <code>import org.openqa.selenium.WebDriver;</code></p>
<p>    <code>import org.openqa.selenium.chrome.ChromeDriver;</code></p>
<p>    <code>public class SauceTest {</code></p>
<p>    <code>private WebDriver webDriver;</code></p>
<p>    <code>@BeforeEach</code></p>
<p>    <code>public void setUp() {</code></p>
<p>    <code>System.out.println("*** set up ***");</code></p>
<p>    <code>System.setProperty("webdriver.chrome.driver", "C://development//chromedriver//chromedriver.exe");</code></p>
<p>    <code>webDriver = new ChromeDriver();</code></p>
<p>    <code>}</code></p>
<p>    <code>@Test</code></p>
<p>    <code>public void demoFormTest() {</code></p>
<p>    <code>System.out.println("*** test ***");</code></p>
<p>    <code>webDriver.get("</code><a target="_blank" href="https://saucelabs.com/request-demo"><code>https://saucelabs.com/request-demo</code></a><code>");</code></p>
<p>    <code>boolean expectedFieldsExist;</code></p>
<p>    <code>try {</code></p>
<p>            <code>webDriver.findElement(By.id("FirstName"));</code></p>
<p>    <code>webDriver.findElement(By.id("LastName"));</code></p>
<p>    <code>webDriver.findElement(By.id("Company"));</code></p>
<p>    <code>expectedFieldsExist = true;</code></p>
<p>    <code>} catch (NoSuchElementException e) {</code></p>
<p>    <code>expectedFieldsExist = false;</code></p>
<p>    <code>}</code></p>
<p>    <code>assertTrue(expectedFieldsExist);</code></p>
<p>    <code>}</code></p>
<p>    <code>@AfterEach</code></p>
<p>    <code>public void tearDown() {</code></p>
<p>    <code>System.out.println("*** tear down ***");</code></p>
<p>    <code>webDriver.quit();</code></p>
<p>    <code>}</code></p>
<p>    <code>}</code></p>
<p>    After executing the test, you can check the Console and JUnit views in Eclipse for information regarding the output. The images below show what can be expected:</p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/GIJKWOYSCHh10b8ed2VEd/b6dc10a83e0643dbc35b287bf6eb9ab2/Eclipse_Console_view.png" alt /></p>
<p>    <img src="https://images.ctfassets.net/vrc8wif0t20g/4807snuGHPZeDptEwtkGJ0/0f97c48a66262df556c2a1503830dfc2/Eclipse_JUnit_view.png" alt /></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>    Both Java and Selenium are well documented and supported, and they provide great value to many software development teams. As such, they are an excellent match when used in conjunction with one another.</p>
<p>    Considering the often rapid pace at which software is developed and modified, it’s important to test your code base as it evolves. When done manually, this can be a time-consuming and error-prone process. When accomplished with the help of automated testing tools such as Selenium, it is efficient and consistent.</p>
]]></content:encoded></item><item><title><![CDATA[Selenium Web Component]]></title><description><![CDATA[Selenium components
Building a test suite using WebDriver will require you to understand and effectively use several components. As with everything in software, different people use different terms for the same idea. Below is a breakdown of how terms...]]></description><link>https://development-of-net-banking-application.hashnode.dev/selenium-web-component</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/selenium-web-component</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 16:32:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735489888209/e097b5bc-f797-4e4c-a7d3-f81d409af6d0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-selenium-components"><strong>Selenium components</strong></h1>
<p>Building a test suite using WebDriver will require you to understand and effectively use several components. As with everything in software, different people use different terms for the same idea. Below is a breakdown of how terms are used in this description.</p>
<h3 id="heading-terminology"><strong>Terminology</strong></h3>
<ul>
<li><p><strong>API:</strong> Application Programming Interface. This is the set of “commands” you use to manipulate WebDriver.</p>
</li>
<li><p><strong>Library:</strong> A code module that contains the APIs and the code necessary to implement them. Libraries are specific to each language binding, eg .jar files for Java, .dll files for .NET, etc.</p>
</li>
<li><p><strong>Driver:</strong> Responsible for controlling the actual browser. Most drivers are created by the browser vendors themselves. Drivers are generally executable modules that run on the system with the browser itself, not the system executing the test suite. (Although those may be the same system.) NOTE: <em>Some people refer to the drivers as proxies.</em></p>
</li>
<li><p><strong>Framework:</strong> An additional library that is used as a support for WebDriver suites. These frameworks may be test frameworks such as JUnit or NUnit. They may also be frameworks supporting natural language features such as Cucumber or Robotium. Frameworks may also be written and used for tasks such as manipulating or configuring the system under test, data creation, test oracles, etc.</p>
</li>
</ul>
<h3 id="heading-the-parts-and-pieces"><strong>The Parts and Pieces</strong></h3>
<p>At its minimum, WebDriver talks to a browser through a driver. Communication is two-way: WebDriver passes commands to the browser through the driver, and receives information back via the same route.</p>
<p><img src="https://www.selenium.dev/images/documentation/webdriver/basic_comms.png" alt="Basic Communication" /></p>
<p>The driver is specific to the browser, such as ChromeDriver for Google’s Chrome/Chromium, GeckoDriver for Mozilla’s Firefox, etc. The driver runs on the same system as the browser. This may or may not be the same system where the tests themselves are executed.</p>
<p>This simple example above is <em>direct</em> communication. Communication to the browser may also be <em>remote</em> communication through Selenium Server or RemoteWebDriver. RemoteWebDriver runs on the same system as the driver and the browser.</p>
<p><img src="https://www.selenium.dev/images/documentation/webdriver/remote_comms.png" alt="Remote Communication" /></p>
<p>Remote communication can also take place using Selenium Server or Selenium Grid, both of which in turn talk to the driver on the host system</p>
<p><img src="https://www.selenium.dev/images/documentation/webdriver/remote_comms_server.png" alt="Remote Communication with Grid" /></p>
<h2 id="heading-where-frameworks-fit-in"><strong>Where Frameworks fit in</strong></h2>
<p>WebDriver has one job and one job only: communicate with the browser via any of the methods above. WebDriver does not know a thing about testing: it does not know how to compare things, assert pass or fail, and it certainly does not know a thing about reporting or Given/When/Then grammar.</p>
<p>This is where various frameworks come into play. At a minimum, you will need a test framework that matches the language bindings, e.g., NUnit for .NET, JUnit for Java, RSpec for Ruby, etc.</p>
<p>The test framework is responsible for running and executing your WebDriver and related steps in your tests. As such, you can think of it looking akin to the following image.</p>
<p><img src="https://www.selenium.dev/images/documentation/webdriver/test_framework.png" alt="Test Framework" /></p>
<p>Natural language frameworks/tools such as Cucumber may exist as part of that Test Framework box in the figure above, or they may wrap the Test Framework entirely in their custom implementation.</p>
<h3 id="heading-1-use-the-maximize-method-from-webdriverwindow-interface">1. Use the maximize() method from WebDriver.Window Interface</h3>
<p>The code snippet below implements four basic scenarios:</p>
<ol>
<li><p>Launching the Chrome browser</p>
</li>
<li><p>Navigating to the desired URL</p>
</li>
<li><p>Maximizing the Chrome Window</p>
</li>
<li><p>Terminating the browser</p>
</li>
</ol>
<p><a target="_blank" href="https://www.browserstack.com/guide/maximize-chrome-window-in-selenium#"><img src="https://browserstack.wpenginepowered.com/wp-content/uploads/2024/05/BrowserStack-Automate-Banner-8.png" alt="BrowserStack Automate Banner 8" /></a></p>
<p><strong>Code:</strong></p>
<pre><code class="lang-plaintext">import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Max {

public static void main(String args[]) throws InterruptedException
{
System.setProperty("&lt;Path of the ChromeDriver&gt;");
WebDriver driver = new ChromeDriver();

// Navigate to a website
driver.get("https://www.browserstack.com/");

//Mazimize current window
driver.manage().window().maximize();

//Delay execution for 5 seconds to view the maximize operation
Thread.sleep(5000);

//Close the browser
driver.quit();
} 
}
</code></pre>
<p>Successful execution of the selenium script above will do the following: launch the Chrome browser, navigate to the <a target="_blank" href="https://www.browserstack.com/">BrowserStack website</a>, maximize the Chrome Window, and wait for five seconds.</p>
<p><a target="_blank" href="https://www.browserstack.com/users/sign_up?ref=guide-maximize-chrome-window-in-selenium-mid&amp;product=automate">Try Selenium Testing on Real Device Cloud for Free</a></p>
<h3 id="heading-2-use-the-chromeoptions-class">2. Use the ChromeOptions class</h3>
<p>An alternate method that can maximize the Chrome window is to use the ChromeOptions class. This method informs the Chrome browser explicitly to launch in maximized mode.</p>
<p><strong>Code:</strong></p>
<pre><code class="lang-plaintext">import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Max {

public static void main(String args[]) throws InterruptedException
{

System.setProperty("&lt;Path of the ChromeDriver&gt;");

ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");

WebDriver driver = new ChromeDriver(options);

// Navigate to a website
driver.get("https://www.browserstack.com/")

//Close the browser
driver.quit();
} 
}
</code></pre>
<p>Successful execution of the script above will do the following: launch the Chrome browser in maximized mode and navigate to the Browserstack website.</p>
<p><a target="_blank" href="https://www.browserstack.com/guide/maximize-chrome-window-in-selenium#">Talk to an Expert</a></p>
<p><strong>Note:</strong> In the first method, the operation is performed after launching the Chrome browser. In the second method, the browser is, by default launched in maximized mode.</p>
<p><strong>Also read:</strong> <a target="_blank" href="https://www.browserstack.com/guide/run-selenium-tests-using-selenium-chromedriver">How to run Selenium tests on Chrome using ChromeDriver</a></p>
<p>Maximizing a browser window prior to the execution of test cases provides better visibility to the QA. Doing so also ensures that no elements are left unidentified when tests are being executed. Implementing either of the methods explained above will help <a target="_blank" href="https://www.browserstack.com/guide/reasons-for-automation-failure">QAs avoid test failure</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Reading and Writing Data to Excel File in Java using Apache POI]]></title><description><![CDATA[In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache PO...]]></description><link>https://development-of-net-banking-application.hashnode.dev/reading-and-writing-data-to-excel-file-in-java-using-apache-poi</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/reading-and-writing-data-to-excel-file-in-java-using-apache-poi</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 16:14:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735488869820/0b6d1c7c-cf77-4968-9645-04dd2b49a563.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. <a target="_blank" href="https://www.geeksforgeeks.org/apache-poi-introduction/"><strong>Apache POI</strong></a> is an open-source java library designed for reading and writing Microsoft documents in order to create and manipulate various file formats based on Microsoft Office. Using POI, one should be able to perform create, modify and display/read operations on the following file formats.<br /><strong>For Example</strong>, Java doesn’t provide built-in support for working with excel files, so we need to look for open-source APIs for the job. Apache POI provides Java API for manipulating various file formats based on the Office Open XML (OOXML) standard and OLE2 standard from Microsoft. Apache POI releases are available under the Apache License (V2.0). </p>
<h3 id="heading-writing-an-excel-file">Writing an Excel File</h3>
<p>Earlier we introduced Apache POI- a Java API useful for interacting with Microsoft Office documents. Now we’ll see how can we read and write to an excel file using the API.</p>
<p><strong>Procedure:</strong> Writing a file using POI is very simple and involve the following steps:</p>
<ol>
<li><p>Create a workbook</p>
</li>
<li><p>Create a sheet in the workbook</p>
</li>
<li><p>Create a row in the sheet</p>
</li>
<li><p>Add cells in the sheet</p>
</li>
<li><p>Repeat steps 3 and 4 to write more data.</p>
</li>
<li><p>Close the output stream.</p>
</li>
</ol>
<p><strong>Example:</strong></p>
<ul>
<li><p>Java</p>
<p>  <code>// Java Program to Illustrate Writing</code> </p>
<p>  <code>// Data to Excel File using Apache POI</code></p>
<p>  <code>// Import statements</code></p>
<p>  <code>import</code> <a target="_blank" href="http://java.io"><code>java.io</code></a><code>.FileOutputStream;</code></p>
<p>  <code>import</code> <a target="_blank" href="http://java.io"><code>java.io</code></a><code>.IOException;</code></p>
<p>  <code>import</code> <a target="_blank" href="http://org.apache.poi.ss"><code>org.apache.poi.ss</code></a><code>.usermodel.Cell;</code></p>
<p>  <code>import</code> <a target="_blank" href="http://org.apache.poi.ss"><code>org.apache.poi.ss</code></a><code>.usermodel.Row;</code></p>
<p>  <code>import</code> <code>org.apache.poi.xssf.usermodel.XSSFSheet;</code></p>
<p>  <code>import</code> <code>org.apache.poi.xssf.usermodel.XSSFWorkbook;</code></p>
<p>  <code>// Main class</code></p>
<p>  <code>public</code> <code>class</code> <code>GFG {</code></p>
<p>      <code>// Main driver method</code></p>
<p>      <code>public</code> <code>static</code> <code>void</code> <code>main(String[] args)</code></p>
<p>      <code>{</code></p>
<p>          <code>// Blank workbook</code></p>
<p>          <code>XSSFWorkbook workbook = new</code> <code>XSSFWorkbook();</code></p>
<p>          <code>// Creating a blank Excel sheet</code></p>
<p>          <code>XSSFSheet sheet</code></p>
<p>              <code>= workbook.createSheet("student Details");</code></p>
<p>          <code>// Creating an empty TreeMap of string and Object][]</code></p>
<p>          <code>// type</code></p>
<p>          <code>Map&lt;String, Object[]&gt; data</code></p>
<p>              <code>= new</code> <code>TreeMap&lt;String, Object[]&gt;();</code></p>
<p>          <code>// Writing data to Object[]</code></p>
<p>          <code>// using put() method</code></p>
<p>          <code>data.put("1",</code></p>
<p>                   <code>new</code> <code>Object[] { "ID", "NAME", "LASTNAME"</code> <code>});</code></p>
<p>          <code>data.put("2",</code></p>
<p>                   <code>new</code> <code>Object[] { 1, "Pankaj", "Kumar"</code> <code>});</code></p>
<p>          <code>data.put("3",</code></p>
<p>                   <code>new</code> <code>Object[] { 2, "Prakashni", "Yadav"</code> <code>});</code></p>
<p>          <code>data.put("4", new</code> <code>Object[] { 3, "Ayan", "Mondal"</code> <code>});</code></p>
<p>          <code>data.put("5", new</code> <code>Object[] { 4, "Virat", "kohli"</code> <code>});</code></p>
<p>          <code>// Iterating over data and writing it to sheet</code></p>
<p>          <code>Set&lt;String&gt; keyset = data.keySet();</code></p>
<p>          <code>int</code> <code>rownum = 0;</code></p>
<p>          <code>for</code> <code>(String key : keyset) {</code></p>
<p>              <code>// Creating a new row in the sheet</code></p>
<p>              <code>Row row = sheet.createRow(rownum++);</code></p>
<p>              <code>Object[] objArr = data.get(key);</code></p>
<p>              <code>int</code> <code>cellnum = 0;</code></p>
<p>              <code>for</code> <code>(Object obj : objArr) {</code></p>
<p>                  <code>// This line creates a cell in the next</code></p>
<p>                  <code>//  column of that row</code></p>
<p>                  <code>Cell cell = row.createCell(cellnum++);</code></p>
<p>                  <code>if</code> <code>(obj instanceof</code> <code>String)</code></p>
<p>                      <code>cell.setCellValue((String)obj);</code></p>
<p>                  <code>else</code> <code>if</code> <code>(obj instanceof</code> <code>Integer)</code></p>
<p>                      <code>cell.setCellValue((Integer)obj);</code></p>
<p>              <code>}</code></p>
<p>          <code>}</code></p>
<p>          <code>// Try block to check for exceptions</code></p>
<p>          <code>try</code> <code>{</code></p>
<p>              <code>// Writing the workbook</code></p>
<p>              <code>FileOutputStream out = new</code> <code>FileOutputStream(</code></p>
<p>                  <code>new</code> <code>File("gfgcontribute.xlsx"));</code></p>
<p>              <code>workbook.write(out);</code></p>
<p>              <code>// Closing file output connections</code></p>
<p>              <code>out.close();</code></p>
<p>              <code>// Console message for successful execution of</code></p>
<p>              <code>// program</code></p>
<p>              <code>System.out.println(</code></p>
<p>                  <code>"gfgcontribute.xlsx written successfully on disk.");</code></p>
<p>          <code>}</code></p>
<p>          <code>// Catch block to handle exceptions</code></p>
<p>          <code>catch</code> <code>(Exception e) {</code></p>
<p>              <code>// Display exceptions along with line number</code></p>
<p>              <code>// using printStackTrace() method</code></p>
<p>              <code>e.printStackTrace();</code></p>
<p>          <code>}</code></p>
<p>      <code>}</code></p>
<p>  <code>}</code></p>
</li>
<li><h3 id="heading-reading-an-excel-file">Reading an Excel file</h3>
<p>  <strong>Procedure:</strong> Reading an excel file is also very simple if we divide this into steps.</p>
</li>
<li><p>Create workbook instance from excel sheet</p>
</li>
<li><p>Get to the desired sheet</p>
</li>
<li><p>Increment row number</p>
</li>
<li><p>iterate over all cells in a row</p>
</li>
<li><p>repeat steps 3 and 4 until all data is read.</p>
</li>
<li><p>Close the output stream.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<ul>
<li>Java</li>
</ul>
<table><tbody><tr><td><p><code>// Java Program to Illustrate Reading</code></p></td></tr></tbody></table>

<p><strong>Output:</strong>   </p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/poigfg.png" alt="Output" /></p>
<blockquote>
<p><em>Geeks, now you must be wondering what if we need to read a file at a different location, so the below example explains it all.</em></p>
</blockquote>
<p><strong>Example 1-A:</strong></p>
<pre><code class="lang-plaintext">// Java Program to Read a File From Different Location

// Getting file from local directory
private static final String FILE_NAME
    = "C:\\Users\\pankaj\\Desktop\\projectOutput\\mobilitymodel.xlsx";

// Method
public static void write() throws IOException, InvalidFormatException 
{

    InputStream inp = new FileInputStream(FILE_NAME);
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);
    ........
}
</code></pre>
<p><strong>Example 1-B:</strong></p>
<p>// Reading and Writing data to excel file using Apache POI // Via Appending to the Existing File // Getting the path from the local directory private static final String FILE_NAME = "C:\\Users\\pankaj\\Desktop\\projectOutput\\blo.xlsx"; // Method public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue("xyz"); ..... .. // Now it will write the output to a file FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); // Closing the file connections fileOut.close(); }</p>
<table><tbody><tr><td><p></p></td></tr></tbody></table>]]></content:encoded></item><item><title><![CDATA[Mobile Banking]]></title><description><![CDATA[It was May 18, 1995, when American bank Wells Fargo offered internet banking to customers. That was the first attempt of a physical bank to shift online. 25 years passed, and 1.9 billion people worldwide actively use online banking services, and the ...]]></description><link>https://development-of-net-banking-application.hashnode.dev/mobile-banking</link><guid isPermaLink="true">https://development-of-net-banking-application.hashnode.dev/mobile-banking</guid><dc:creator><![CDATA[pooja Kanojia]]></dc:creator><pubDate>Sun, 29 Dec 2024 15:34:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735486717626/e0df2e4c-328a-4d38-baa9-46b6c58bccbd.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It was May 18, 1995, when American bank Wells Fargo offered internet banking to customers. That was the first attempt of a physical bank to shift online. 25 years passed, and <a target="_blank" href="https://www.statista.com/statistics/1228757/online-banking-users-worldwide/">1.9 billion</a> people worldwide actively use online banking services, and the number is going to reach 2.5 billion by 2024.</p>
<p>Seems like mobile banking development is something of a great need in the fintech industry. This demand, for sure, creates vast business opportunities. But how to create a mobile banking app? Where to start? And how to make it competitive?</p>
<p>In this article, I'll cover all these questions, and explain how to build a mobile banking app that keeps up with the highly competitive market.</p>
<h2 id="heading-what-is-mobile-banking"><strong>What is Mobile Banking?</strong></h2>
<p>As <a target="_blank" href="https://en.wikipedia.org/wiki/Mobile_banking">Wikipedia puts</a> it, "mobile banking is a service provided by a bank or other financial institution that allows its customers to conduct financial transactions remotely using a mobile device such as a smartphone or tablet." In other words, mobile banking is an application you can use for almost all the activities you'd do in a physical bank, but now you have it in your pocket. </p>
<p>As we figured out "what" mobile banking is, let's move to the "why." </p>
<h2 id="heading-mobile-banking-benefits"><strong>Mobile Banking Benefits</strong></h2>
<p>Working at banking mobile app development I always balance the advantages the product brings to users and business.</p>
<p>What do I mean here? </p>
<p>With a mobile banking app, users will satisfy their need for 24/7 bank access. From the business point of view, developing a mobile banking application gives a competitive advantage. Since <a target="_blank" href="https://topmobilebanks.com/usa-digital-banks/">top US banks provide online banking,</a> you need to have one to reach those standards and not to become an outsider. So the advantages differ, let’s take a closer look at them.</p>
<p><img src="https://cdn.prod.website-files.com/5e305a6cb7083222527a89cc/61c096dee52eb34e267f966c_Mobile%20Banking%20Benefits.jpeg" alt="mobile banking benefits" /></p>
<h3 id="heading-benefits-for-users"><strong>Benefits for Users</strong></h3>
<p>I have mentioned 24/7 bank access as the benefit for users, but there are many more others, check them out:  </p>
<ul>
<li><p>24/7 bank account access;</p>
</li>
<li><p>Fast money transfer;</p>
</li>
<li><p>Fast and secure access to the account (Face ID, Touch ID);</p>
</li>
<li><p>Notifications set up;</p>
</li>
<li><p>Broader functionality;</p>
</li>
<li><p>Cashback;</p>
</li>
<li><p>User-friendly UI design;</p>
</li>
<li><p>Spending tracker.</p>
</li>
</ul>
<h3 id="heading-benefits-for-business"><strong>Benefits for Business</strong></h3>
<p>If you're reading this article, chances are you know what benefits mobile banking app development brings to your business. But, in case you missed something, here are some more:</p>
<ul>
<li><p>Reach more users;</p>
</li>
<li><p>Faster and easier development;</p>
</li>
<li><p>Easier A/B testing; </p>
</li>
<li><p>More ways to reach out to users (notifications);</p>
</li>
<li><p>A better understanding of user behavior;</p>
</li>
<li><p>Higher customers attraction;</p>
</li>
<li><p>More careful customer analysis and opportunity to make the mobile banking software better.</p>
</li>
</ul>
<p>‍</p>
<h2 id="heading-how-to-develop-an-online-banking-application"><strong>How To Develop An Online Banking Application?</strong></h2>
<p>Developing a mobile banking application is more or less the same as developing any other product, except for the security stage that you need to focus on more. Below I described 7 steps of how to develop an online banking application. Check them out.</p>
<p><img src="https://cdn.prod.website-files.com/5e305a6cb7083222527a89cc/61c0971aa780a195770cedea_7%20Steps%20to%20Mobile%20Banking%20Development.jpeg" alt="mobile banking application development in steps" /></p>
<h3 id="heading-step-1-research"><strong>Step 1 – Research</strong></h3>
<p>At Uptech, we start digital banking app development with a market analysis, study the competitors and the market conditions we enter.</p>
<p>In mobile banking development, I advise paying serious attention to the cultural aspect, mentality, and user habits. For instance, when we built a banking application for the US market, we found that <a target="_blank" href="https://shiftprocessing.com/credit-card/">70% of Americans</a> have at least one credit card. So the question of whether we should include a credit option didn't even arise. Instead, it was a must-to-have feature. So, mind the cultural aspect of the market you're jumping into.</p>
<p>As the result of the research step, we get:</p>
<ul>
<li><p>User Persona profile;</p>
</li>
<li><p>Market analysis;</p>
</li>
<li><p>Market share;</p>
</li>
<li><p>Market habits;</p>
</li>
<li><p>Value proposition.</p>
</li>
</ul>
<h3 id="heading-step-2-prepare-the-security-base"><strong>Step 2 – Prepare the Security Base</strong></h3>
<p>This step is the one that differentiates mobile banking application development among others. When working on mobile banking software, you should understand that it's all about working with sensitive user data. </p>
<p>That's why here's the security base you should mind before developing a mobile banking application :</p>
<ul>
<li><p><strong>Secure password:</strong> all passwords must be hashed and only then stored in a database. </p>
</li>
<li><p><strong>Auto logout:</strong> if users aren't active in the app for more than 15 minutes, they should be automatically logged out from the system, both on the front-end and back-end. </p>
</li>
<li><p><strong>Data privacy:</strong> people who create a banking app should have limited access to users' tokens, passwords, and other sensitive information. All data must be stored in secure platforms like 1Password, Okta, etc.</p>
</li>
<li><p><strong>Security certificates:</strong> in the case of a web app, ensure you have an SSL Certificate, and if it's mobile – SSL Pinning. These docs ensure that all data passed between the Web server and browser remains private and secure. </p>
</li>
<li><p><strong>Secure authentication:</strong> Set up and use fingerprint security for Android devices and Apple KeyChain for iOS. </p>
</li>
<li><p><strong>Secure card info:</strong> implement VGS (Very Good Security) to display customers' card info.</p>
</li>
</ul>
<h3 id="heading-step-3-develop-amp-test-a-prototype"><strong>Step 3 – Develop &amp; Test a Prototype</strong></h3>
<p>Over my experience in banking application development I learned one thing: the product's success lies in the number of interactions. Building a prototype is one of them.</p>
<p>Think of the prototype as a simplified version of the final product. It should include:</p>
<ul>
<li><p>App logic;</p>
</li>
<li><p>App structure;</p>
</li>
<li><p>App design.</p>
</li>
</ul>
<p>However, the prototype is still a far cry from the final product in terms of functionality, stability, and aesthetics. It allows you to test your idea. You simply give it to real users, gather the feedback, understand what works and what's not, and implement changes accordingly.</p>
<p>If you'd ask me, what the best way to validate the usability, design, and functionality of your mobile banking app is. I'd say, without a shadow of a doubt: "build a prototype." </p>
<p><a target="_blank" href="https://www.uptech.team/blog/mvp-vs-poc-vs-prototype">  
</a>If you haven't been testing your ideas with a proof of concept or prototype, you could be charting your product for failure. We knew from first-hand experience that validating your ideas is the only essential way to ensure product-market fit. </p>
<p>Therefore, you ought to know how to leverage PoC, prototype, and even MVP during development. More importantly, you'll need to learn the differences and which should be deployed at various stages. </p>
<p>In general, you'll want to follow the PoC → Prototype → MVP order. In some cases, you can skip PoC if there isn't a need to run a feasibility test.</p>
<p>Let's dig deeper into each of the methods.</p>
]]></content:encoded></item></channel></rss>