19762

Substrings and if statements in Java [duplicate]

Question:

This question already has an answer here:

<ul><li> <a href="/questions/6178585/equal-strings-arent-equal-in-java" dir="ltr" rel="nofollow">Equal strings aren't equal (==) in Java? [duplicate]</a> <span class="question-originals-answer-count"> 3 answers </span> </li> </ul>

I'm a pretty new programmer and as part of a few projects I'm doing I'm using substrings. In all of these I've run across a problem with if statements. Say I have two variable, one that is a substring of some other string, and another that should be the equivalent to that first substring. If I try to check if they are equal in an if statement (which they should be) it returns false for and == check. Here's a bit of code to demonstrate.

public class Substringproblem{ static void method(){ String random="somestring"; String randomsubstring=random.substring(0,3); String should_be_randomsubstring="som"; if(randomsubstring==should_be_randomsubstring){ System.out.println("Success"); }else{ System.out.println("Failure"); System.out.println(randomsubstring); } } public static void main(String[] args) { method(); } }

I get the feeling I'm missing something really obvious but I've been looking for a bit and haven't spotted anything that is like this. Help would be really appreciated.

Answer1:

randomsubstring.equals(should_be_randomsubstring)

or

randomsubstring.equalsIgnoreCase(should_be_randomsubstring)(If you want to ignore cae use this)

instead of

randomsubstring==should_be_randomsubstring)

whenever you are comparing string use .equals() or .equalsIgnoreClas()

Answer2:

randomsubstring.equals(should_be_randomsubstring)

You are comparing String object references.

Answer3:

Use the String.equals(String anotherString) function to compare strings, not the == operator. The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.

public class SubstringProblem { public static void main(String[] args) { method(); } static void method() { String random = "somestring"; String randomsubstring = random.substring(0,3); String should_be_randomsubstring = "som"; if (randomsubstring.equals(should_be_randomsubstring)) { System.out.println("Success"); } else { System.out.println("Failure"); System.out.println(randomsubstring); } } }

Answer4:

in java for comparing two Strings always use equals() method. your code should look like :

if(randomsubstring.equals(should_be_randomsubstring)){ System.out.println("Success"); }else{ System.out.println("Failure"); System.out.println(randomsubstring); <ul><li>‘==’ operator <strong>does not compare the content</strong> of the text present in the String objects. It only compares the references the 2 Strings are pointing to i.e. the Object references. hence in your case it will return false.</li> <li>The equals() method is used when you need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content. </li> </ul>

Answer5:

You should use <strong>equals</strong> to compare String object.

According to your mean code change:

if(should_be_randomsubstring.equals(randomsubstring)){ System.out.println("Failure") }else{ System.out.println("Success"); }

Answer6:

Consider you have single String object in heap memory then you can have multiple reference variable pointing to same object.

Ex. String ref1 = "Test"; String ref2 = ref1; String ref3 = ref1;

So String ref1, ref2 and ref3 are pointing to same String "Test". So to check whether those references equals or not, we have to use == operator. which will return corresponding value.<br />(equals will also return true but its purpose is different)

Equals method of the String checks actual contents of the String object. so in above case if I create

String ref4= new String("Test");

ref1 is not equal to ref, == operator will return false, because both objects having different existence in heap memory.

and if I compare both object by equals method then it will return true because contents are true.

Imp Note for memory leak in substring

Also dig down into substring method which cause memory leak if we don't use it judiciously. String's substring method uses old string's value[] array object to store substring.<br /> Ex. You have a String say, 1 GB, and if make a substring of it with 500 MB then it will return 500 MB character set with 1 GB value[] array object. It means still you have 1 GB value[] array object which contains 500 MB of data. So cause memory leak.<br /> How to avoid?

String some1 = new String(some2.substring(5)); // use such call String someStr = some2.substring(5); //don't use this way

Recommend

  • AsyncTask and Thread won't run twice in java / android application
  • Which MySQL collation compares e.g. é and e as equal?
  • Numpy - Finding matches across multiple co-ordinates
  • import XML to HTML
  • Creating a Countdown Watch with a slider in Xcode
  • getting cpu usage of one process using c++ (win32)
  • LocateRegistry.createRegistry
  • ElasticSearch and Apache HttpAsyncClient
  • Convert Scala Unit to Java Void
  • Read File Content Line by Line from byte[] in Groovy
  • Java: Parent Methods accessing Subclasses' static variables?
  • Java - Clipboard copied content disappear after program exits
  • Spark doesn't read/write information from s3 (ResponseCode=400, ResponseMessage=Bad Request)
  • Failed to execute goal net.alchim31.maven:scala-maven-plugin:3.2.2
  • java.io.EOFException when sending serialized data to a servlet
  • Different results when setting/getting System properties with GStrings in Groovy
  • passing parameter to server in ExtJs
  • Why would a Scala Worksheet using Scala-IDE give this as an error?
  • Java, will (low + high) >>> 1 overflow?
  • Is the Go HTTP handler goroutine expected to exit immediately in this case?
  • twisted.internet.error.ConnectError when run scrapy spider
  • Extjs, handling success or failure when doing a standard submit in a form
  • How to implement simple validation in Scala
  • Better file search algorithm than creating a list of files
  • Smack 4.1.0 android Roster not displaying
  • If statement skipping right to else after being called once?
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Reading a file into a multidimensional array
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • App restarts from wrong activity
  • Jetty Server not starting: Unable to establish loopback connection
  • Get data from AJAX - How to
  • Bug in WPF DataGrid
  • Validaiting emails with Net.Mail MailAddress
  • sending/ receiving email in Java
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • How does Linux kernel interrupt the application?