Eric Oudin Eric Oudin - 1 month ago 8
Java Question

Boolean not returning as expected in String.Contains()?

I have this sample from my project and I need to know why the result is what it is.

public class Main
{
public static void main(String[] args)
{
//url: https://classicpartyrentals.com/products/24681-gothic-silver-coffee-cup, websiteList: http://classicpartyrentals.com/, URL Contains Returns bool: false
String url = "https://classicpartyrentals.com/products/24681-gothic-silver-coffee-cup";
String contains = "http://classicpartyrentals.com/";
System.out.println("Returns bool: " + url.contains(contains));
}

}


Output:

Returns bool: false

Answer

Code is always doing what you ask it to do:

 String url = "https://classicpartyrentals.com/products/24681-gothic-

but

 String contains = "http://classicpartyrentals.com/";

https versus http!

So the real answer is: especially when you are a beginner, chances that your code uncovered "some Java bug" is relatively small (very close to zero in reality!)

There is a much higher chance that your assumptions are wrong. You either don't fully understand the methods you are calling, or there is a subtle flaw in your input data.

Finally: also work on your naming. contains isn't a very good name here; you better call it expectedUrl, or something alike!