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
Related
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.
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:
How do I compare strings in Java?
Java String.equals versus ==
I am new to Selenium and Java.
I have tried the below to compare the field value of last name to the one which i supplied.
String lastname=selenium.getValue("//*[#id='lastName']");
System.out.println(lastname);
assertTrue (lastname == "xxx");
It is keep on failing.
Just literally tried to change the last line with help of Eclipse (just trial and error)
assertTrue("lastname.equals("xxx"));
It is working fine... Why it is failed in first case? == is not allowed to compare strings?
Short answer: == checks for same object .equals checks for the same value.
More info in How do I compare strings in Java?
equals function checks the actual contents of the lastname. == operator checks whether the references to the objects are equal.
You must use equals() to compare strings with Java, as you guessed.
You're actually comparing pointers (or really reference equality) when you use == with strings. In other words you're testing if two objects are the same, rather than the content of the objects.
For comparing equality of string ,We Use equals() Method. There are two ways of comparison in java. One is "==" operator and another "equals()" method . "==" compares the reference value of string object whereas equals() method is present in the java.lang.Object class. This method compares content of the string object.
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:
How do I compare strings in Java?
I read some records from a csv file and store them into a string type array, then save each field in proper variable after convert them. In a part of code I have to compare a field in array with one of those variables with string type. both these arrays filled from a csv file.
int count=0;
String name=resourceArray[i][j+1] ;
while(machineArray[count][0]==name)
{
machineID=Integer.parseInt(machineArray[count][1]);
machinePe=Integer.parseInt(machineArray[count][2]);
count++;
}
the problem is 'while' condition never become true. I debug it and I'm sure machineArray[0][0] and 'name' have same value.
Try changing your condition from machineArray[count][0]==name to machineArray[count][0].equals(name).
Essentially you are comparing pointers to two String objects by using == instead of comparing Strings.
To compare Strings you have to use Strings equals method:
machineArray[count][0].equals(name)
Strings do not always have the same identity (although it is common). Try:
machineArray[count][0].equals(name)