$show=/label

String != java? - String Comparisons Does not work with !=?

SHARE:

A quick guide to compare strings using != and equals() method in java. Examples on string != java and string.equals("java").

1. Overview

In this article, You'll learn how to compare the string contents with == and does not compare with != operator.

How to fix != comparison in two ways. Read till end of this tutorial, you will get better understanding for sure.

string-does-not-equal-java


2. Java String !=

If you are new to programming, you might have written the code for string comparison as below and does not work properly.

we have added getValidationStatus() method that returns "Success" if the given age greater or equals to 18 else should return "Failure".

Let us see the output of this program.

package com.javaprogramto.strings.compare;

public class StringDoesnotEqual {

	public static void main(String[] args) {
		
		String status = getValidationStatus(10);
		System.out.println("status :  "+status);
		
		if (status != "Failure") {
			System.out.println("Valid age");
		} else {
			System.out.println("Invalid age");
		}

	}

	public static String getValidationStatus(int age) {

		if (age < 18) {
			return new String("Failure");
		}

		return new String ("Success");
	}
}
 

Output:

status :  Failure
Valid age
 

See the output. status value is returned "Failure" but it went inside the if condition and printed the valid age string.

But, actually execution should go inside the else block.

3. How to fix status != "Failure" and use the right string comparison

First, understand the issue with the above approach. There when we use != operator with String, it compares the memory address of these two string. In our case, both strings are having different addresses. So, the condition is becoming true and printing the irrelevant onto the console.

!= checks only the string address are different or not but not string contents.

To fix the string comparison issue, you should use the method which does the comparing the contents.

Correct method: equals()

Let us correct the above problematic example using equals() method.

if (!status.equals("Failure")) {
	System.out.println("Valid age");
} else {
	System.out.println("Invalid age");
}
 

Output:

Rerun the sample code and see the output.

status :  Failure
Invalid age
 

Now, !status.equals("Failure") compares the contents using equals() method  and returns a boolean value. Next, negation ! operator is applied on boolean result.

So, status value is "Failure" and condition becomes false. Hence, it has executed the else block of if condition.

4. How fix String != java? in another way using != operator

As compared to the above method using equals() method, there is another approach to resolve the issue.

Manu of the developers do not know the deep understanding of String. If you want to surprise them, you must try out this way.

Instead of equals() method use the intern() method on status string along with the !=.

When intern() method is called it checks the same value is present in the string constant pool. If present, it fetches the address ref from there and use it for comparison.

Make the change on the string.intern() method.

if (status.intern() != "Failure") {
	System.out.println("Valid age");
} else {
	System.out.println("Invalid age");
}
 

Output:

status :  Failure
Invalid age
 

This solution works amazingly and impress your team fellow programmers.

5. Conclusion

In this tutorial, you've seen how to compare strings using != operator. If this != does not work, how to compare the contents using equals() and intern() methods.

GitHub

Read Next:

What is the difference between == and equals() method with String Objects comparison?

String equals() method examples

String intern() method examples

Stackoverflow ref

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,17,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,29,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,14,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,111,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,105,Java Spark,1,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,28,String,59,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: String != java? - String Comparisons Does not work with !=?
String != java? - String Comparisons Does not work with !=?
A quick guide to compare strings using != and equals() method in java. Examples on string != java and string.equals("java").
https://1.bp.blogspot.com/-IDnoMESRvK8/X7vHK-beXiI/AAAAAAAADEo/gFf6AZOIDtoKKnj_F5DpY4Oe627mB7iWACLcBGAsYHQ/w640-h468/string-does-not-equal-java.png
https://1.bp.blogspot.com/-IDnoMESRvK8/X7vHK-beXiI/AAAAAAAADEo/gFf6AZOIDtoKKnj_F5DpY4Oe627mB7iWACLcBGAsYHQ/s72-w640-c-h468/string-does-not-equal-java.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/string-does-not-equal-java.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/string-does-not-equal-java.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content