This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
im new to android and this is my first post in StackOverflow.In short I face a very strange problem :
in some methods I used if(...) ,and both of the values were equal ,yet it doesn't go through the if .
Here is an example :
String []s=db.getStudentsNames();
String []t=CopyNames(s);
String t1,t2;
t2=Id.getText().toString();
for(int i=0;i<s.length;i++)
{
t1=t[i].substring(t[i].indexOf("-")+1).toString();
Notifications(t[i].substring(t[i].indexOf("-")+1).toString());
if(t1.toString()==t2.toString())//Problem!
{
Notifications("Id already exists for "+t[i].substring(0,t[i].indexOf("-")).toString());
return false;
}
}
The variables t1 & t2 are : t1="123456789" & t2="123456789" , yet it doesn't enter the if like they are not equal.
And there are other places were two equal sides are considered as not equal - in the same java page (activity) like:
if(add.getText().toString()=="Add Student") : add refers to a button which has ,by default , a text :"Add Student"
so how can I solve this problem ?
**when this problem started , I started to see in LogCat:
W/KeyCharacterMap(282): No keyboard for id 0
W/KeyCharacterMap(282): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
D/dalvikvm(282): GC_FOR_MALLOC freed 5438 objects / 256800 bytes in 73ms
You shouldn't use == to compare Strings in Java. Use t1.toString().equals(t2.toString()) instead.
never use == on String objects. Use t1.equals(t2) instead.
Related
This question already has answers here:
Two ways to check if a list is empty - differences?
(4 answers)
Closed 3 years ago.
I do not have a way of really testing this without completely the other code I am working on but I just wanted to confirm this. If I am trying to code this statement:
If a node contains only positives, set decision to true.
If it contains only negatives set it to false
where pos is an ArrayList of all of the positive examples of a node and neg is othe same but with all of the negatives. Would this statement be valid?
if(!node.pos.isEmpty() && node.neg.isEmpty())
node.decision = true;
if(!node.neg.isEmpty() && node.pos.isEmpty())
node.decision = false;
So pretty much I am wondering if i put that the ArrayList is != null then does that mean that it must contain at least 1 thing and then when I put == null then that means it is empty?
No. An ArrayList is an object and will only be null if it hasn't been instantiated using the new keyword.
Use ArrayList.isEmpty() or ArrayList.size() > 0.
This question already has answers here:
Comparing strings with == which are declared final in Java
(6 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Please follow the code below:
String s="helloworld";
String ss="hello";
String sss=ss+"world";
System.out.print(sss==s);
The output is false. Don't they get checked with the string pool rule for String? And what if we make them final?
A little explanation of internal working will help. Thanks in Advance.
String literals points to the same location if the content of them is same, that's what I got from different sources, am I right? If yes, then what's happening here? I'm a little confused about it.
EDIT:-
I think I didn't phrase it correctly. Let me rephrase it a little(Sorry for earlier attempt):-
String ss="hello";
System.out.print(ss+"world"=="helloworld");
This returns false. However these are String literals and as I have read they don't create two different objects for same value. They are just reference to a same value. Here, "helloworld" is the value for both sides of ==. I hope that I'm able to communicate it well.
Because String is an object, it is comparing that the two objects are the same with ==, which will equate to false.
Using the object ss to concat into sss will not make s = sss.
If you set ss to s, then using == will equate to true since they are now the same object.
If you set a second String object with a string literal, using == will equate the true.
If you use the String object's function .equals(String), you will find that it equates to true.
If you compare two string literals, i.e. "helloworld" == "helloworld" or "helloworld" == "hello" + "world", these will also equate to true.
As lealceldeiro pointed out, strings should always be compared with .equals().
EDIT
A good thing to look at is this answer. It has good references and explanation.
Other resources:
JournalDev
Baeldung
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
From what i know, jdk 8 now is assigning as hashCode the memory address of the object.
And, obj1 = obj2 returns true iff the obj1 is obj2, i.e., they're sitting at the same memory location.
However, the following code executes the "else" part-- not the "then" part of the if-stat which is what i expect:
String h1 = "heya";
String h2 = new String ("heya");
System.out.println("hashCodes "+h1.hashCode()+" "+h2.hashCode());
if (h1 == h2)
System.out.println("yeah - the same ");
else System.out.println("nope-- difft objects ");
What am i missing here?
TIA.
h1 and h2 are not sitting in the same memory location. You are calling a new String("heya") so the JVM will create a new instance of String. Therefore, h1 == h2 is false. The hasCode is the same because it is based on the char composing the String.
Using equals method instead of == will return true.
The String class overrides hashCode().
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I wrote a simple code just to check the values between textfields and compared whether they are the same or not. I want them to be the same, if not it will produce an error. It's about rewriting an email.
String a = studentemail.getText();
String b = rewritestudentemail.getText();
if(a != b){
JOptionPane.showMessageDialog( null, "Student Email rewritten incorrectly.","Error!",JOptionPane.OK_OPTION);
}
The program persists that there is an error even though I indicated the same string values in both of the fields. Why's that?
Change your conditional to be this:
if(!a.equals(b))
{
JOptionPane.showMessageDialog( null, "Student Email rewritten
incorrectly.","Error!",JOptionPane.OK_OPTION);
}
Make sure you have the ! before a.equals(b)) since you only want the error to appear when they are not equal.
rather layout your logic like this:
if (!a.equals(b)){
//JoptionPane...
}
In java two strings are compared by using the ".equals()" function.
Try:
if (!a.equals(b)) {
...
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So I'm trying to check a list of account names to see if the username entered by the operator is in the database or not. At the moment I have:
for(int i = 0; i < rowCount; i ++){
System.out.println("Stored in array:" + accounts[i+1]);
System.out.println("name entered:" + LoginPage.usrname);
if(accounts[i+1] == LoginPage.usrname){
System.out.println("match");
}else{
System.out.println("no match");
}
}
I tried messing around with things like indexOf string and can't get anything to work. I'm sure there's a simple solution, just having trouble finding one. I don't understand why I can't compare a String array index to a String variable, seems like ti should be cake.
This is what you're looking for:
if(acounts[i+1].equals(LoginPage.usrname))
Using the == operator on Strings in Java doesn't do what you think it does. It doesn't compare the contents of the Strings, but rather their addresses in memory. The equals method compares the contents of the Strings.
As a note that may help you remember, this isn't anything particularly special about Strings. Strings are objects, and in Java, using == to compare objects of ANY type will present the same problem. If you want to compare the contents of two objects of a custom class you create, you'll have to write an equals method for that class. Strings work exactly the same.
String are unique reference type that behave like value type.
At Java when trying to compare String's using == operator, Java will try to check if both of the reference are equals, Not the strings.
In order to achieve a value type comparison you will be to use one of the following:
Method 1: str1.equals(str)
Method 2: str1.compareTo(str) == 0