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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS