This question already has answers here:
String.equals() argument ordering
(10 answers)
Closed 3 years ago.
In part of the code for check empty string the programmer use equals() like this:
if ("".equals(name)) {
// some logic
}
Why is it executed from a string value directly? What is the difference from this;
if (name.equals("")) {
// some logic
}
Both of them have the same result, but what is the idea behind doing the first one?
The idea behind using;
"".equals(name)
is that "" can never be null, whereas name can be. equals() accepts null as a parameter, but trying to execute a method from a null variable will result in a NullPointerException.
So this is a shorthand way to evade such possible exceptions. Same goes for any such constant object.
e.g.
final Integer CONSTANT_RATE = 123456;
....
if (CONSTANT_RATE.equals(someVariable)) { .. }
rather than doing;
if (someVariable != null && someVariable.equals(CONSTANT_RATE)) { .. }
Related
This question already has answers here:
Why does String.valueOf(null) throw a NullPointerException?
(4 answers)
Closed 5 years ago.
Today I found a bug in legacy code, which led me to a shocking discovery:
String s = null + ""; //results in "null" string
s = String.valueOf(null); // NullPointerException is thrown
Integer i = null;
s = String.valueOf(i); //results in "null" string
First question is: Why such an unexpected behavior happens?
It mean that a convenient code like this:
String age = person.getAge() + "";
is being totally unexpected.
Second question: What is the best (most elegant) way to get a null instead of "null"
String.valueOf(null) calls public static String valueOf(char data[]) due to method overloading resolution rules (char[] is more specific than Object). That method throws NullPointException for a null argument.
String.valueOf(i) calls public static String valueOf(Object obj), which returns the String "null" for a null argument.
To avoid this exception, either don't call s = String.valueOf(null); (you can always assign s = "null"; directly, or cast the null value to some type other than char[] (for example s = String.valueOf((String)null);).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have this
public void otis() {
println("What is Otis?");
String otis = readLine(">");
println("You said " + otis);
println(otis);
println(otis);
if (otis == "dog"){
println("you got it right!");
}
else {
println("try it again!");
otis();
}
}
But for some reason even when I respond "dog" it doesn't find a match. I can print the "otis" variable and it says "dog" but apparently that's not equivalent to "dog" somehow?
Can you try the code below? Java doesn't recognize strings as equivalent from two different instantiations even if their values are equivalent. This is because each string is a pointer, and their pointer values aren't equivalent. Try using the String.equal method!
otis.equals( "dog" )
Because == means "is the same exact object in memory", the constant string "dog" and the string it reads from the console are not the same object, even if they have the same contents. When doing comparisons in Java, always use .equals().
As a possible side effect of this, you have to be careful when comparing things that might be null in Java. If you try to do
String dog = null;
if(dog.equals("dog")) { do_something(); }
You'll end up with a NullPointerException. For this reason, many coders prefer to compare strings like this:
if("dog".equals(dog)) { do_something(); }
since you always know the constant string will not be null.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
If I set the text of a TextView in XML, like this:
<TextView
...
android:text="0" />
Can I compare that string in Java? Doing this:
private void InitializeMethod() {
A_1 = tv_1.getText().toString();
}
private void CheckAnsMethod() {
if (A_1 == "0"){
correctAns.start();
}
}else{
wrongAns.start();
}
}
causes the sound 'wrongAns.mp3' to be played...
You needs to use the String class's equals() method:
if ( "0".equals(A_1) )
"0" == A_1 will compare the values of the references pointing to where the String objects are located. In other words, it's comparing memory addresses when you really want to compare the characters in the strings.
The String class's equals() method will actually compare the strings character by character to check if they're equal.
Also, the reason I use "0".equals(A_1) instead of A_1.equals("0") is because if A_1 is ever null for whatever reason, "0".equals(A_1) will not throw a NullPointerException.
This question already has answers here:
Difference between Equals/equals and == operator?
(11 answers)
Closed 8 years ago.
I am studying some example code that enrol customer into a service, and the method below checks if the customer has that type of service. I assume that if we want to compare to objects, i.e. service, we need to use equals() method.
However the code below (in customer class) works perfectly fine, but it did't work after I changed == to equals.() Can someone help to explain why it behave like this? Is it because under some circumstances we need check equality using ==? Many thanks!
boolean hasService(Service sd) { //Service is a class that has int, String and ArrayList as variable
boolean hasService = false;
for (int i=0; i<.length; ++i) { //
//doesn't work if change to ((serviceAvailable[i] ).equals(pd)), why?
if (serviceAvailable[i]==sd) //serviceAvailable is an Array stores different services
hasService = true;
}
return hasService;
}
The class Service is as below:
class Serivce {
private String name;
private int price;
private ArrayList <Customers> customersErolled;
//geters and setters methods
boolean equals (Serive a){
if (this.paperName.equals(a.paperName)&&a.semester==this.semester&& a.year==this.year&&a.studentsEnrolled.equals(this.studentsEnrolled) ){
return true;
}else{
return false;
}
The equality operator == will compare the object references, while equals will depend on the implementation of equals on the object that you are comparing. By default this will compare the hash of the object (which is unique for each object in the jvm that your code runs in at that moment).
For a propper equals you need to override the equals method in Service and compare the instance variables there one by one (or whathever kind of equality you want / need).
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
savedInstanceState = getIntent().getExtras();
String type = savedInstanceState.getString(TYPE);
if(type == "tree")
{
setContentView(R.layout.activity_sound_tree);
}
else
{
TextView tv = (TextView) findViewById(R.id.heading_sound);
tv.setText("'"+type+"'");
}
I have used this code in the second activity. I know for sure that type == tree. So I do not understand why the first "if" block fails. It always goes to the "else" block, even though I am 100% sure that type == "tree". Can someone point me in the right direction?
Never compare string values with the == operator. Use the equals method instead.
The == operator compares object by references, not by values.
Javadoc: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
Fixed code:
savedInstanceState = getIntent().getExtras();
String type = savedInstanceState.getString(TYPE);
if(type.equals("tree"))
{
setContentView(R.layout.activity_sound_tree);
}
else
{
TextView tv = (TextView) findViewById(R.id.heading_sound);
tv.setText("'"+type+"'");
}
use
type.equals("tree")
instead of
type == "tree"
Reason
equls method check the values of the object where == operator check whether they are the same instance of object.
This looks like classic String comparison question, try
"tree".equals(type); // This is also safe from NullPointerException since you are comparing type with a constant 'tree', which is not null
Why Equals?
A detailed explanation regarding using == vs equals() can be found here