What are the differences between equals and contains in java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

What are the differences between equals and contains in java?

lets say my code is: //please help import.java.util.*; class Test { public static void Testing(String[ ] args){ Scanner in = new Scanner(System.in); String user = "play", pass="java"; s.o.p("Username: ") user = in.next(); s.o.p("Password"); pass = in.next(); if (user.equals("play") &&pass.equals("java")) { s.o.p("Equals"); } else if (user.contains("play") &&pass.contains("java")) { s.o.p("Contains"); { } }

10th Mar 2018, 10:29 AM
The iPlay Android Team
The iPlay Android Team - avatar
3 Answers
+ 2
Equals checks if a string is equal to the specified object. Contains check if your specified string is part the string you referenced to. You use equals to check the string values of one object from another if they are pointing to different instances, say this code for example: str1 = "Hello World!"; str2 = str1; if (str1 == str2) { return true; } else { return false; } This will return true, however: String str1 = "Hello World!"; String str2 = "Hello World!"; if (str1 == str2) { return true; } else { return false; } ... would return false, for these strings may be the same, but they have different instances. To counter this, we use the equals method: str1 = "Hello World!"; str2 = "Hello World!"; if (str1.equals(str2)) { return true; } else { return false; } This would return true again! Finally, contains checks if a specified string is part of the string you compared it to, something like this: String str1 = "Hello World!" String str2 = "Hello World" String comp = "!" boolean compare1 = str1.contains(comp); boolean compare2 = str2.contains(comp); Compare1 would return true, since there is an exclamation point in str1! And compare2 would return false, since there is no exclamation point in the string. The exclamation point is referenced by the comp variable.
10th Mar 2018, 12:15 PM
apex137
apex137 - avatar
+ 1
equals method will return true only if the objects compared are the same (same==same) but contains method returns true if the second string is contained in the first one : char y ="yellow"; y.contains(low); // that will return true.
10th Mar 2018, 12:16 PM
Pau Bartolí
Pau Bartolí - avatar
0
Thank you so much guys. I appreciated your replies. Now, things was more clearer. I was confused that's why. Btw, thanks again :)
10th Mar 2018, 12:41 PM
The iPlay Android Team
The iPlay Android Team - avatar