0

I tried to validate the title of URL, the code have mentioned below show no error but gave wrong output. Please see my code below:

public static void main(String[] args) 
{
WebDriver driver=new FirefoxDriver();
driver.get("https://www.google.com");
String c;
c = driver.getTitle();
if (c!="Google")
System.out.println("True");
driver.close();
}

why output is True. however Title of the URL is Google

iamsankalp89
  • 4,607
  • 2
  • 15
  • 36

4 Answers4

0

https://stackoverflow.com/a/513839/366348

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

so correct code is if (!c.equals("Google"))

Naktibalda
  • 13,705
  • 5
  • 35
  • 51
0

Your code is looking correct but why it show incorrect result unable to understand. Try this, it works correctly for me.

driver.get("https://www.google.com");
String c;
c = driver.getTitle();
System.out.println(c);
if (!c.equals("Google"))
{
System.out.println("True");
}
driver.close();
}
iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
0

Apparently, your code was pretty good enough to retrieve the title as Google. However, this discussion points us to a couple of simple facts about String literals in Java as follows:

  1. == tests should be used for reference equality (if they are the same object).
  2. .equals() tests should be used for value equality (if they are literally equal).

Hence changing if (c!="Google") to if (!c.equals("Google")) should have solved your purpose.

Getting Granular:

As we are comparing string literals, my take will be to get more granular and use if (!c.contentEquals("Google")) instead of if (!c.equals("Google")).

Solution:

Hence a proper solution to your problem will be to define the if() as follows:

    public class GooglePageTitle 
    {
        public static void main(String[] args) 
        {
            System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
            WebDriver driver=new FirefoxDriver();
            driver.get("https://www.google.com");
            String c;
            c = driver.getTitle();
            if (!c.contentEquals("Google"))
            System.out.println("True");
            driver.close();
        }
    }
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

here it's. you can't verify string data type with != operator. you should stick with manipulation functions.

 if (!c.contentEquals("Google"))