Notification texts go here Contact Us Buy Now!

Processing - Weird behavior in IF statement

In Java, comparing Strings using == operator checks if the references of the String objects are the same, not the actual content of the Strings.

To compare the content of Strings, you should use the .equals() method. Let's see an example to clarify the difference:

String inStr = "heartbeat"; String heartbeat = "heartbeat"; if (inStr == heartbeat) { System.out.println("Strings are equal using =="); } if (inStr.equals(heartbeat)) { System.out.println("Strings are equal using .equals()"); }

The output of this code will be:

Strings are equal using =
Strings are equal using .equals()

In this example, the == operator returns true because both inStr and heartbeat references the same String object in memory. On the other hand, .equals() method returns true because they both have the same content.

Therefore, to check if two Strings are equal in Java, always use the .equals() method. The == operator should only be used when comparing references, not the content of objects.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.