I noticed a difference in the behaviour of the String.replace(CharSequence, CharSequence) between java 12 and 13.
java 12 and earlier:
System.out.println("String"=="String".replace("g","g")); //false
java 13 and later:
System.out.println("String"=="String".replace("g","g")); //true
Found that this is probably due to:
Optimize String.replace(CharSequence, CharSequence) for common cases
Is this unexpected behaviour?
Yes, I'm aware of the equals method.
The API specification makes no guarantees of whether String.replace returns a new String object or if it reuses the original when possible. The result of the comparison is "unspecified". That means it may change from one version to the next, just like you've discovered.
Use the .equals method to compare strings for equality.
Related
I searched and got clear that == is not used to compare the content of string variables but equals().
However, AS reports that equals() is only available on API 19 (Android 4.4) and up and I targetted API 18 (my only phone is Android 4.3)
So right now, I'm doing if (var1.contains(var2)) or if (array[i].contains(var)) to compare strings and it works but it doesn't seem correct to me.
What would be the correct way to achieve this on API < 19?
Thanks.
Edit: for clarification (I don't know how to put inline images)
With ==
With equals()
Comparison fails with equals().
The equals function of the Object class was added in Java JDK 1.0.
This version was released on January 23, 1996. It was called 'Oak' back then, so technically it predates even Java itself. (source).
In contrast, Android API 1 was released on September 23, 2008. At this time it would be made with Java JDK 1.5 (latest version was Java SE 5 Update 16).
So in conclusion, equals is available on API level 18, there must be some other error.
After seeing the posted code, you are using Objects.equals(), which is a utility method that checks equals() in a null-safe manner.
In many cases, like yours, you don't need the extra null check because you know at least one of the objects is not null and you can just call equals directly:
if("una".equals(hourNames[realHour]))
Your hourNames array will probably not contain null elements so you should turn it around to the more readable order:
if(hourNames[realHour].equals("una"))
use hourNames[realHour].equals("una")
yeah, that is a bug on android studio (or maybe from intellij idea).
Since if (var1.contains(var2)) works for you why don't you post the exact strings ? In case you don't have debug capability, I would suggest using these to debug the point in difference in the strings:-
boolean contentEquals(CharSequence cs)
public int compareTo(String anotherString)
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)
Also you could use the simulator env and run this small test:-
String s1 = "Test";
String s2 = "Test";
if (s1.equals(s2))
System.out.println("Equal");
else
System.out.println("Not Equal");
This question already has answers here:
Interview : Java Equals
(7 answers)
Closed 8 years ago.
Is there a performance impact, assuming str is a java.lang.String, of using "String".equals(str) vs str.equals("String")? My gut says, "No, the JVM / compiler will optimize the literal string in either case", but I see the first style crop up enough in various codebases and it just looks so unnatural (at least to me), so I figured there must be a reason besides style.
The only reason for using "String".equals(str) (which I find ugly) is laziness, as it saves you the need to check that str != null prior to calling str.equals("String").
Performance-wise there shouldn't be any difference. You are comparing two String instances either way.
"String".equals(str)
Does not yield the same result as
str.equals("String")
if str == null.
In the first case, it returns false, in the second, it throws a NullPointerException.
"String".equals(str)
Is in fact equivalent to
str != null && str.equals("String")
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i recently started to do some encryption with Apache DigestUtils. I simply want to use md5 hashes for authorization, but i'm an absolute beginner in this topic and in general not really experienced in Java. The API of this library provided me the methods md5, md5hex.
If i'm not mistaken the result of these just differs in the output as a hexString (i'm not even sure whats this means) and regular bytes.
String b1 = DigestUtils.md5hex("Some String");
String b2 = DigestUtils.md5hex("Some String");
The result is 83beb8c4fa4596c8f7b565d390f494e2 & 83beb8c4fa4596c8f7b565d390f494e2
But a comparison with == results in false
if (b1 == b2){
System.out.println("Matching")
}
I'm pretty confused and i can't find a source for an introduction around this topic(for java!)
Because == is not how Strings are compared in Java, use .equals
For example...
if (b1.equals(b2)) {...
"==" means to compare with the values.
If you compare two object-type objects(such as String, Date), the compared value is their unique reference address in the jvm. That means you want to know if they are the same object
If you compare two primitive types(such as int, float, double...), the compared value is their real values.
So if we want to compare two objects, we usually use equals() function instead of "==", because we just want to know if they they have the same attribute values.
Further more, If you define you own class, you should override the equals() function to compare objects of the class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
If statement using == gives unexpected result
Hi I'm using this code to add elements to my ComboBox, and I do not want to add empty elements, here's the code:
public void elrendezesBetoltes(ArrayList<Elrendezes> ElrLista){
int i;
Elrendezes tmp;
model.removeAllElements();
model = new DefaultComboBoxModel(comboBoxItems);
for(i=0; i<ElrLista.size(); i++){
tmp = ElrLista.get(i);
if(tmp.getName()!="")comboBoxItems.add(tmp.getName()); //not working
addButton2(tmp.getSeatnum(),tmp.getCoord(),tmp.getFoglalt());
}
}
My problem is that the if statement is not working, it still adds empty names to my combobox. What am I doing wrong?
Always use equals method to compare Strings: -
if (tmp.getName()!="")
should be: -
if (!tmp.getName().equals(""))
or simply use this, if you want to check for empty string: -
if (!tmp.getName().isEmpty()) {
comboBoxItems.add(tmp.getName());
}
Use equals method to compare string. By using != operator, you are comparing the string instances, which is always going the be true as they(tmp.getName() and "") are not same string instances.
Change
tmp.getName()!=""
to
!"".equals(tmp.getName())
Putting "" as first string in comparison will take care of your null scenario as well i.e. it will not break if tmp.getName() is null.
Use equals():
if (!tmp.getName().equals(""))
Using == or != compares string references, not string contents. This is almost never what you want.
you have to compare Strings with "equals", then it will work
if(!tmp.getName().equals(""))comboBoxItems.add(tmp.getName())
you are comparing for identity (==, !=) but each String instance has its own identity, even when they are equal.
So you need to do !tmp.getName().equals("").
Generally it is considered best practice to start with the constant string first, because it will never be null: !"".equals(tmp.getName())
However, I would recommend to use apache commons lang StringUtils. It has a notEmpty() and notBlank() method that take care of null handling and also trimming.
PS: sometimes identity will work for Strings. but it should not be relied upon as it is caused by compiler or jvm optimization due to String immutability.
Use String#isEmpty()
if(!tmp.getName().isEmpty())
OR:
if(!tmp.getName().equals(""))
Always, check String equality with equals method. == operator only checks if two references point to the same String object.
Another alternative if not on Java 6 and isEmpty is unavailable is this:
if (tmp.getName.length()>0)
Checking for the length is supposed to be quicker than using .equals although tbh the potential gain is so small its not worth worrying too much about.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!