Planet Jaspersoft

May 20, 2020


XPath
  • XPath = XML Path
  • It is a type of query language to identify any element on the web page. 
  • Syntax
    //tagname[@attribute='value']
  • Writing XPath for complex applications sometimes cumbersome task.
  • There are plenty of plug-ins available for chrome to find Xpaths and one such tool is  "Chropath" pulg-in. 
  • Take a look at the below image to find relative XPath for "Email or Phone" text input.
    Tap on the image to get better visibility of  content
    Let's understand with an example, Identify gmail's  "Email or phone" text input with xpath
    Tap on the image to get better visibility:

    HTML
    <input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="username" spellcheck="false" tabindex="0" aria-label="Email or phone" name="identifier" value="" autocapitalize="none" id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="">

    from the above HTML,  tagname is input  | type is an attribute  | value is email

    Xpath to locate the "Email or phone" is
    //input[@type='email']

    Java-selenium identifies the element with the following xpath locator
    driver.findElement(By.xpath("//input[@id='identifierId']"))

    Watch this ~4 min video tutorial example for automating gmail login process in which use xpath locators for "Email or Phone" or "Password"  or "Next" buttons. 


    java-selenium code to identify gmail login using xpath locators
    xpathLocatorGmailLoginDemo.java
    //x-path locator example

    package selenium.locators.examples;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class xpathLocatorGmailLoginDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput", "true");

    driver
    = new ChromeDriver();
    driver
    .manage().window().maximize();

    driver
    .navigate().to("https://mail.google.com/");

    //locate "Email or Phone" text box input using "xpath" and enter email
    driver
    .findElement(By.xpath("//input[@id='identifierId']")).sendKeys("java.selenium2021@gmail.com");

    // locate "Next" button and click
    driver
    .findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

    driver
    .manage().timeouts().implicitlyWait(3000, TimeUnit.SECONDS);

    //locate "Enter your password" text box input using "xpath" and enter password
    WebElement elePassword
    =driver.findElement(By.xpath("//input[@name='password']"));
    elePassword
    .sendKeys("JavaSelenium2021");

    elePassword
    .sendKeys(Keys.TAB);
    elePassword
    .sendKeys(Keys.TAB);

    // locate "Next" button and click
    driver
    .findElement(By.xpath("//span[contains(text(),'Next')]")).click();

    //driver.close();
    }
    }

    May 20, 2020

    Hi , In this post - I'm writing my learning experiences on various methods of "WebElement" interface.
    Test site courtesy : 

    Watch the below ~1 min video for end-to-end execution 
    getText()
    • getText() method gets you the visible text or inner text of an element. 
    • That is it fetches text between the opening and closing tags. 
    • For instance, the following text between bold tags can be fetched using getText() method.
      <b xpath="1">This is sample text.</b>
    • Store the locator in a Weblement variable and then use getText()
      //getText() example --> locate text "This is sample text." on page and display the text
      WebElement ThisIsSimpleText
      = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
      String displayThisIsSimpleText
      = ThisIsSimpleText.getText();
      System
      .out.println(displayThisIsSimpleText);
    sendKeys()
    • This method allows users to enter data into editable elements such as text boxes or search boxes.
    • For instance, first name is a text box input and using sendKeys() method enter input value
      <input id="fname" type="text" name="firstName" xpath="1">
    • Code snippet
      //sendKeys("sadakar") example --> locate TextBox input and enter first name
      WebElement firstName
      = driver.findElement(By.xpath("//input[@id='fname']"));
      firstName
      .sendKeys("Sadakar");
    clear()
    • clear() method clears any text already entered or displayed in text box or search box inputs. 
    • Some applications may use default values in editable forms so clear them before entering new.
    • For instance, clear the already existing text in "first name" text box and enter new value
      //clear() --> clear TextBox input and re-enter first name
      firstName
      .clear();
      firstName
      .sendKeys("Hasini");
    getAttribute("<attribute>")
    • getAttribute() method returns the current value of a given attribute as a string.
      <input id="fname" type="text" name="firstName" xpath="1">
    • id, type, name , xpath and vlaue(not given above statement) are attributes of first name element HTML 
    • For instance, the following snippet for firstname text field fetches the value displayed on the form then the values of the corresponding attributes
      //getAttribute("<attribute>") --> <input id="fname" type="text" name="firstName">
      firstName
      .getAttribute("value");
      System
      .out.println("<input id=\"fname\" type=\"text\" name=\"firstName\">");
      System
      .out.println("Value of value attribute="+firstName.getAttribute("value"));
      System
      .out.println("Value of id attribute="+firstName.getAttribute("id"));
      System
      .out.println("Value of type attribute="+firstName.getAttribute("type"));
      System
      .out.println("Value of name attribute="+firstName.getAttribute("name"));
    Handling radio buttons and check boxes using - click() method
    • Toggling(select or deselect) on/off are the actions performed for radio buttons or check boxes. 
    • Using click() method toggling can be done. 
    • For instance, take a look at the following code snippet - "male" radio button and check boxes for testings labels are selected.
      //radio button click example --> locate "male" radio button and select it
      WebElement male
      = driver.findElement(By.xpath("//input[@id='male']"));
      male
      .click();

      //check box click example - locate "Automation Testing" check box and tick it
      WebElement automationTesting
      = driver.findElement(By.xpath("//input[@class='Automation']"));
      automationTesting
      .click();

      //check box click example - locate "Performance Testing" check box and tick it
      WebElement performanceTesting
      = driver.findElement(By.xpath("//input[@class='Performance']"));
      performanceTesting
      .click();

    Complete java class for above examples: WebElementInterfaceMethodsDemo.java
    package selenium.webelement.methods;

    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.PageLoadStrategy;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeDriverService;
    import org.openqa.selenium.chrome.ChromeOptions;

    public class WebElementInterfaceMethodsDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    //loading Chrome driver from physical drive
    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");

    System
    .setProperty("webdriver.chrome.silentOutput", "true");
    //System.setProperty(ChromeDriverService.CHROME_DRIVER_SILENT_OUTPUT_PROPERTY, "true");

    //launch the browser
    driver
    = new ChromeDriver();

    //navigate to site
    driver
    .navigate().to("https://www.testandquiz.com/selenium/testing.html");

    //maximize the browser
    driver
    .manage().window().maximize();

    //getText() example --> locate text "This is sample text." on page and display the text
    WebElement ThisIsSimpleText
    = driver.findElement(By.xpath("//b[contains(text(),'This is sample text.')]"));
    String displayThisIsSimpleText
    = ThisIsSimpleText.getText();
    System
    .out.println(displayThisIsSimpleText);

    //sendKeys("sadakar") example --> locate TextBox input and enter first name
    WebElement firstName
    = driver.findElement(By.xpath("//input[@id='fname']"));
    firstName
    .sendKeys("Sadakar");

    //clear() --> clear TextBox input and re-enter first name
    firstName
    .clear();
    firstName
    .sendKeys("Hasini");

    //getAttribute("<attribute>") --> <input id="fname" type="text" name="firstName">
    firstName
    .getAttribute("value");
    System
    .out.println("<input id=\"fname\" type=\"text\" name=\"firstName\">");
    System
    .out.println("Value of value attribute="+firstName.getAttribute("value"));
    System
    .out.println("Value of id attribute="+firstName.getAttribute("id"));
    System
    .out.println("Value of type attribute="+firstName.getAttribute("type"));
    System
    .out.println("Value of name attribute="+firstName.getAttribute("name"));

    //radio button click example --> locate "male" radio button and select it
    WebElement male
    = driver.findElement(By.xpath("//input[@id='male']"));
    male
    .click();

    //check box click example - locate "Automation Testing" check box and tick it
    WebElement automationTesting
    = driver.findElement(By.xpath("//input[@class='Automation']"));
    automationTesting
    .click();

    WebElement performanceTesting
    = driver.findElement(By.xpath("//input[@class='Performance']"));
    performanceTesting
    .click();

    //close the browser
    driver
    .close();

    //close all the browsers opened by WebDriver during execution and quit the session
    driver
    .quit();
    }
    }

    May 20, 2020

    Hi,

    In this post, you will see demonstration of "tagName" locator usage. 

    "tagName"  is one of the 8 locators supported by selenium.

    For instance, display all the anchors "a" or "images" alternative texts on amazaon india page   @ https://www.amazon.in/

    selenium identifies the "a" and "image" tags with the following java statements.

    List<WebElement> links = driver.findElements(By.tagName("a"));
    List<WebElement> images = driver.findElements(By.tagName("img"));

    tagNameLocatorDemo.java
    package selenium.locators.examples;
    import java.util.List;

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

    public class tagNameLocatorDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput", "true");

    driver
    = new ChromeDriver();

    driver
    .navigate().to("https://www.amazon.in/");
    driver
    .manage().window().maximize();

    // storing anchor - a tags in links List<WebElement> variable
    List
    <WebElement> links = driver.findElements(By.tagName("a"));

    // printing the size of list
    System
    .out.println("Size of list="+links.size());

    // print the top 5 Text of anchors
    System
    .out.println("-- Printing top 5 anchors text--");
    for(int i=0;i<links.size();i++) {
    System
    .out.println(links.get(i).getText());
    if(i==4)
    break;
    }
    System
    .out.println("------------------------------------");

    // storing images - img tags in images List<WebElement> variable
    List
    <WebElement> images = driver.findElements(By.tagName("img"));

    // foreach loop with WebElements
    // if wants to break the loop on a particular index go with regular loop
    System
    .out.println("-- Printing images alternative texts --");
    for(WebElement w2 : images) {
    System
    .out.println(w2.getAttribute("alt"));
    }

    }
    }

    Watch this ~ 1.5 min video for end-to-end example execution



    May 20, 2020

    May 19, 2020

    Hi,

    In this post, you will see demonstration of "className" locator usage. 

    "classname" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action(s).

    For instance, Login to gmail  @ https://mail.google.com/
    Let's see how to identify the name locators of login elements for gmail web application.

    Email or Phone input text input HTML with "name" locator 
    <input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="username" spellcheck="false" tabindex="0" aria-label="Email or phone" name="identifier" value="" autocapitalize="none" id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="" badinput="false" aria-invalid="false" xpath="1">

    selenium identifies the above input element(Email or Phone) using "className" locator with the following java statement. 
    driver.findElement(By.className("whsOnd")).sendKeys("java.selenium2021@gmail.com");

    Tap on the image to get better visibility: 
    To avoid StaleElementReferenceException for other elements locators having the same class name ,  I am taking xpaths to find them, for instance , password has the same className i.e., class="whsOnd zHQkBf"  so instead of having className for password taking xpath //input[@name='password']


    classNameLocatorDemo.java
    package selenium.locators.examples;

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class classNameLocatorDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput","true" );

    driver
    = new ChromeDriver();

    driver
    .navigate().to("https://mail.google.com/");
    driver
    .manage().window().maximize();

    //finding "Email or Phone" input text by clasName locator and enter value
    driver
    .findElement(By.className("whsOnd")).sendKeys("java.selenium2021@gmail.com");

    // click on "Next" button - This is an xpath example that will be covered in later sessions
    driver
    .findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

    driver
    .manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    // locate "Enter your password" text input with xpath locator and enter password say --> JavaSelenium2021
    // If we take className for this input we will end up with
    // Exception in thread "main" org.openqa.selenium.StaleElementReferenceException:
    // stale element reference: element is not attached to the page document

    WebElement elePassword
    =driver.findElement(By.xpath("//input[@name='password']"));
    elePassword
    .sendKeys("JavaSelenium2021");

    elePassword
    .sendKeys(Keys.TAB);
    elePassword
    .sendKeys(Keys.TAB);

    // click on "Next" button - This is again an xpath example.
    driver
    .findElement(By.xpath("//span[contains(text(),'Next')]")).click();

    //close the driver
    //driver.close();
    }
    }


    May 19, 2020

    Hi,

    In this post, you will see the demonstration of "name" locator usage. 

    "name" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action(s).

    For instance, Login to gmail  @ https://mail.google.com/
    Let's see how to identify the name locators of login elements for gmail web application.

    Email or Phone input text input HTML with "name" locator 
    <input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" 
           autocomplete="username" spellcheck="false" tabindex="0" 
           aria-label="Email or phone" name="identifier" value="" autocapitalize="none" 
           id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="">

    Enter your password text input HTML with "name" locator
    <input type="password" class="whsOnd zHQkBf" jsname="YPqjbf" 
           autocomplete="current-password" spellcheck="false" tabindex="0" 
           aria-label="Enter your password" name="password" autocapitalize="off" 
           dir="ltr" data-initial-dir="ltr" data-initial-value="">

    Click on the image to get best view

    selenium identifies the above input elements(username and password for gmail) using "name" locator with the following java statements. 
    driver.findElement(By.name("identifier")).sendKeys("java.selenium2021@gmail.com");

    WebElement elePassword=driver.findElement(By.name("password"));
    elePassword
    .sendKeys("JavaSelenium2021");
    Take a look at the following example or watch this 1 min no voice video tutorial for end-to-end demo understanding and execution. 
    nameLocatorDemo.java
    //name locator demo
    package selenium.locators.examples;

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class nameLocatorDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput", "true");

    driver
    = new ChromeDriver();
    driver
    .navigate().to("https://mail.google.com/");

    driver
    .manage().window().maximize();

    // locate "Email or Phone" text input with "name" locator and enter email say --> java.selenium2021@gmail.com

    driver.findElement(By.name("identifier")).sendKeys("java.selenium2021@gmail.com");

    // click on "Next" button - This is an xpath example that will be covered in later sessions
    driver
    .findElement(By.xpath("//span[@class='RveJvd snByac']")).click();

    driver
    .manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    //locate "Enter your password" text input with "password" locator and enter password say --> JavaSelenium2021
    WebElement elePassword=driver.findElement(By.name("password"));
    elePassword.sendKeys("JavaSelenium2021");


    elePassword
    .sendKeys(Keys.TAB);
    elePassword
    .sendKeys(Keys.TAB);

    // click on "Next" button - This is again an xpath example.
    driver
    .findElement(By.xpath("//span[contains(text(),'Next')]")).click();

    //close the driver
    //driver.close();
    }
    }


    - Sadakar Pochampalli

    May 19, 2020

    Hi,

    In this post, you will see the demonstration of "id" locator usage. 

    "id" is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action.

    For instance, Login to facebook site @ http://www.facebook.com
    Let's see how to identify the ids of login elements for facebook web application.

    "Email or Phone" text input HTML
    <input type="email" class="inputtext login_form_input_box" name="email" id="email" data-testid="royal_email">

    "Password" text input HTML
    <input type="password" class="inputtext login_form_input_box" name="pass" id="pass" data-testid="royal_pass">

    "Log In" button HTML
    <input value="Log In" aria-label="Log In" data-testid="royal_login_button" type="submit" id="u_0_b">


    The following statements identifies the above 3 elements using id attribute on the page.
     driver.findElement(By.id("email")).sendKeys("test123@gmail.com");
     driver.findElement(By.id("pass")).sendKeys("testPassword");
      driver.findElement(By.id("u_0_b")).click();.
    Take a look at the following example or watch this ~2 min no voice video tutorial for end-to-end execution. 
    idDemo.java
    package selenium.locators.examples;

    import java.util.concurrent.TimeUnit;

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

    //id demo
    public class idDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput", "true");

    //chrome driver object
    driver
    =new ChromeDriver();

    driver
    .get("https://www.facebook.com");

    //maximizing the URL
    driver
    .manage().window().maximize();

    //finding email element by "id" locator and entering email
    driver
    .findElement(By.id("email")).sendKeys("test123@gmail.com");

    //finding pass element by "id" locator and entering password
    driver
    .findElement(By.id("pass")).sendKeys("testPassword");

    //finding "Login" element by "id" locator and performing click action
    driver
    .findElement(By.id("u_0_b")).click();

    //driver.manage().timeouts().implicitlyWait(20000, TimeUnit.SECONDS);

    //driver.quit();

    }
    }

    - Sadakar Pochampalli

    May 19, 2020

    May 18, 2020

    Hi,

    In this post, you will see the demonstration of "linkText" locator usage. For the purposes, I took my blog-site https://jasper-bi-suite.blogspot.com/.

    linkText is one of the 8 locators supported by selenium, using it one can navigate to target page by performing click action.

    For instance, navigate to "Services" page from the site.
    Let's see how to perform/navigate to Services page using "Services" text from the following HTML script.
    <a href="https://jasper-bi-suite.blogspot.com/p/contact-information.html">Services </a>

    The following statement identifies "Services" link on the page and does the click action.
     driver.findElement(By.linkText("Services")).click();

    Take a look at the complete java code at the bottom or watch below 1 min video tutorial for end-to-end execution.

    Screenshot: 

    Watch this 1 min video tutorial ( change quality to 720p)
    linkTextDemo.java
    package selenium.locators.examples;
    //linkText example
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class linkTextDemo {

    public static void main(String[] args) {

    WebDriver driver
    ;

    System
    .setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver.exe");
    System
    .setProperty("webdriver.chrome.silentOutput", "true");

    driver
    = new ChromeDriver();

    driver
    .navigate().to("https://jasper-bi-suite.blogspot.com/");
    driver
    .manage().window().maximize();

    driver
    .manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    //linkText
    driver.findElement(By.linkText("Services")).click();

    JavascriptExecutor js
    = (JavascriptExecutor) driver;
    js
    .executeScript("window.scrollBy(0,550)");

    //driver.close();

    }
    }


    - Sadakar Pochampalli 

    May 18, 2020

    Hi ,

    This tutorial is intended to written for beginners and in this example, we would see how to set-up and launch a website in chrome browser (for example: https://jasper-bi-suite.blogspot.com/) using java selenium.

    1. Download Eclipse zip from  https://www.eclipse.org/downloads/
    2. Install java 1.8 or later and set path & class path in windows os.
    3. Download suitable chromedriver.exe from https://chromedriver.chromium.org/downloads
          NOTE : This example is tested on : Version 81.0.4044.138 (Official Build) (64-bit)
    4. Download selenium jar files and configure in Eclipse Build Path as (Referenced Libraries)
          https://www.selenium.dev/downloads/
    5. Write FirstTestCase.java class with the code shown in below.
    6. Run as "Java Applicaiton".

    In the java class, ensure to have the following : 
    1)  System set property  -  using this call the chromedriver.exe
    2)  Declaring driver - driver declaration
    3)  navigate().to - method to navigate to a given site.
    4)     ChromeOptions options = new ChromeOptions();
             .......... Google Chrome Browser Options.............
            driver = new ChromeDriver(options);

    Watch this ~15 sec video for execution of this case.



    import java.util.concurrent.TimeUnit;
    /**
    * @author Sadakar Pochampalli
    */
    import org.openqa.selenium.PageLoadStrategy;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    public class FirstTestCase {

    public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver", "D:\\006_trainings\\chromedriver_win32\\chromedriver.exe");

    WebDriver driver ;

    ChromeOptions options = new ChromeOptions();

    //options.addArguments("--headless");
    options.addArguments("--disable-gpu");
    options.addArguments("start-maximized");
    options.setPageLoadStrategy(PageLoadStrategy.NONE);
    options.addArguments("--allow-insecure-localhost");
    options.addArguments("--allow-running-insecure-content");
    options.addArguments("--ignore-certificate-errors");
    options.addArguments("--no-sandbox");
    options.addArguments("--window-size=1280,1000");
    options.setCapability("acceptSslCerts", true);
    options.setCapability("acceptInsecureCerts", true);
      driver = new ChromeDriver(options);

    driver.navigate().to("https://jasper-bi-suite.blogspot.com/");
    driver.manage().window().maximize();

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //driver.close();

    }
    }

    May 18, 2020

    May 11, 2020

    In C#, if you try to print a non-static variable from static method, you will see the reference error message.


    Severity Code Description Project File Line Suppression State
    Error CS0120 An object reference is required for the non-static field, method, or property 'Car.color' ConsoleApp3 C:\Users\sadakar\source\repos\ConsoleApp3\ConsoleApp3\Oops\ClassesAnbObjects\Car.cs 15 N/A


    I wanted to check this example both in C# and Core Java and so if you are wondering how the similar behavior appears in core  java , take a look at this example@


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp3.Oops.ClassesAnbObjects
    {
    class Car
    {
    string color = "red";
    static void Main(string[] args)
    {
    Car myObj =
    new Car();
    Console.WriteLine(
    color);

    Console.ReadLine();
    }
    }
    }

    Solution:
    1) Create an Object
    2) Call/print the non static variable using object.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp3.Oops.ClassesAnbObjects
    {
    class Car
    {
    string color = "red";
    static void Main(string[] args)
    {
    Car myObj = new Car();
    Console.WriteLine(
    myObj.color);

    Console.ReadLine();
    }
    }
    }




    References: 
    https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop

    May 11, 2020

    If you try to  access an instance variable or say non-static variable in a static method, you would end up with static reference error message.

    For instance, in the following example, variable "a" is class variable/non-static instance variable and if accessed directly in the static method, say in this case it is main method, it would throw the reference exception.

    NonStaticDataMemberInStaticMethod.java
    package static1.method;

    public class NonStaticDataMemberInStaticMethod {

    int a=10 ;// non static variable
    public static void main(String args[]) {
    System
    .out.println(a);
    }

    }


    Error Message:
    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Cannot make a static reference to the non-static field a

    at static1.method.NonStaticDataMemberInStaticMethod.main(NonStaticDataMemberInStaticMethod.java:7)

    Solution:
    1) Create an Object
    2) Call/print the non static variable using object.

    package static1.Variable;

    public class NonStaticDataMemberInStaticMethod {

    int a =10;//non static variable
    public static void main(String args[]) {

    NonStaticDataMemberInStaticMethod myObj=new NonStaticDataMemberInStaticMethod();
    System
    .out.println(myObj.a);
    }

    }




    - Sadakar Pochampalli 

    May 11, 2020

    Pages

    Feedback