devxlogo

Comparing Strings Properly in Java

Comparing Strings Properly in Java

The semantics of ==, with regards to string comparison in Java and C#, are totally different from each other. Suppose you have two strings?s1 and s2?and the following statment:

// valid Java and C# codeif (s1 == s2) {   // A}else {   // B}

In Java, you would not always reach point A when the strings are identical. This is because the comparison here is of references; == checks if the strings have the same memory location?not whether they contain the same characters in the same order.

In C#, == does check for the same characters in the same order. In order to compare strings this way in Java, you must use the equals method:

// valid Java onlyif (s1.equals(s2)) {   // A}else {   // B}

Note: C# also has an equals method which can be used to compare strings in the same way that Java’s equals methods compares them and C#’s == compares them.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist