Android string compare is false [duplicate] - android

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have the following piece of code:
String week = this.getIntent().getStringExtra("weekNumber");
String correctWeek = Integer.toString(Calendar.WEEK_OF_YEAR);
if (week == correctWeek) {
correct();
}
else incorrect();
They are both "3", but the comparation result is false and I don't know why:
Where is the error?

Use equals() to compare strings for content, not ==.
== will check if the objects are the same.
String foo = "foo";
if (foo == foo) {
// same object, so true
}
String foo1 = "foo";
String foo2 = "foo";
if (foo1 == foo2) {
// both are string literals set at compile time, so true
}
String foo1 = loadFoo1(); // imagine this returns "foo"
String foo2 = loadFoo2(); // imagine this also returns "foo"
if (foo1 == foo2) {
// not the same object, and not string literals, so false
}
if (foo1.equals(foo2)) {
// both strings hold "foo", so true
}

The two strings are separate objects, and "==" tests if its two operands are the same exact object.
To compare strings, try week.equals(correctWeek)

The "==" operator is used for reference comparison. It checks if both objects point to the same memory location, which returns false in your case as you are comparing two different string objects.
For your purpose you should use .equals(), which evaluates to the comparison of values in the objects.
Example:
String week = new String("3");
String correctWeek = new String("3");
System.out.println(week == correctWeek);
System.out.println(week.equals(correctWeek));
will output:
false
true

Related

multiple check or,and in if statement

hi i'm wonder why my if always Toast me : "names Successfully saved!"
i'm try every thing.
public void btnSave_Clicked(View view) {
TextView txtOname = (TextView)findViewById(R.id.txtOname);
TextView txtXname = (TextView)findViewById(R.id.txtXname);
String X = txtXname.getText().toString();
String O = txtOname.getText().toString();
if((X!="") && (O!="")){
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtOname))
.getText().toString());
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtXname))
.getText().toString());
Toast.makeText(this,"names Successfully saved!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"E",Toast.LENGTH_SHORT).show();
}
}
}
Strings are reference types in Java, and thus the reference of a dynamically created empty string will be different from your variables. Another option to isEmpty is equals.
if (!x.equals("") && !o.equals(")) {
//code
}
Though I'd probably go with isEmpty
Replace your if statement with:
if (!x.isEmpty() && !o.isEmpty()) {
//code
}
operator == compares Object reference.
.equals() compares String value.
.isEmpty() return true if String length is 0.
Strings are objects. Object instances (the value behind them) have to be compared manually with a method to assure that the content is the same.
The == operator just compares the string references ("adresses"). So when you create 2 object instances at runtime, they have different adresses even if the content is the same. Compile-time strings on the other hand are internalized, they are put into special memory and duplicates are sorted out.
System.out.println(new String("test") == new String("test"));
This will print false, because those 2 objects get created at runtime. The new keyword in the first example mandates that a new object with a new adress is created.
System.out.println("test" == "test");
This will print true, because they are String literals, which are known at runtime, you are not explicitly stating the new keyword here either. You are simply specifying that you want those literals represented in the code somehow, so the compiler internalizes them.

Android comparing strings with == to each objects

I'm coming from C#, so typically I try to relate everything that i'm doing.
I cannot figure out why the below statement doesn't work. Basically String val = "admin". Then an I have an if statement, however the if statement is always false. I'm sure it's something simple.
Thanks!
EditText edt = (EditText) findViewById(R.id.email);
//String val = edt.getText().toString();
String val = "admin";
EditText edt2 = (EditText) findViewById(R.id.password);
String val2 = edt2.getText().toString();
if(val.toString() == "admin") {
String hero = val;
}
You should use
if (val.equals("admin")) {
String hero = val;
}
instead of using an equal sign. Using an equal sign in java is asking if they're the same object, which will be false even if the strings are the same.
Also, be careful with what you're doing inside of the if statement, because the variable "hero" won't be accessible outside of that block.
In Java you can't compare strings using ==
You need to change your if statment like this
if(val.equals("admin")){}
First of all you have never changed the value of String val to anything so there is no need to try convert it to a string in your if statement.
String val = "admin";
if (val == "admin") {
//code here
}else{
//code here
}
Hope this helps
In java, == operator check the address of each value, and equals() method check the value.
So If you want to compare the value of each string, you should use the equals() method.
Please search for the concept of 'call by reference' and 'call by value'.
And you already declare val to String, so it didn't need toString().
if(val.equals("admin")) {
String hero = val;
}
I'm surprised no one mentioned the difference between .matches() and .equals() depending on your needs, what you could also be looking for is .matches()
if(val.toString().matches("admin")) {
String hero = val;
}
Matches checks the match of a String to a regular expression pattern, not the same string.
For example:
"hello".equals(".*e.*"); // false
"hello".matches(".*e.*"); // true
use .equals() instead of ==.
for example:
if (val.equals("admin")) ...

Comparing strings that use the substring method [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I hope somebody could give me an explaination why the below code wont work:
//Why doesnt this work
String l = myString.substring(cut, lengthLastBtn-1);
String c = myString.substring(cut, lengthLastBtn-1);
if(l==c){
Log.i(TAG, "Correct");
}
//End
//This work!
String l = "hi";
String c = "hi";
if(l==c){
Log.i(TAG, "Correct");
}
// End
// Or if i want the Vars as in the first code i have to use the if statement like this
if(l.contains(c)){
Log.i(TAG, "Correct");
}
//End
So, why cant a compare a string when i have used the substring method on it. I even see in the log for the strings that they are the same, or have the same text at least.
When you use the “==“ operator with String`s, it means a comparison between objects, not the value that objects hold.
In order to compare Strings values , you should use the built-in method equals. The result is true if the String object represents the same sequence of characters.
if(string1.equals(string2)) {
//Match
}

"==" for Strings always returning false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I can't seem to get the code within the second if statement to execute. I have logged both values being compared and also ran the debugger and checked them. They are both "a". It always shows the incorrectPasswordDialog. This question seems difficult because it seems as though it should just work but any help is appreciated.
private void logUserIn(AppUser user) {
if (user != null){
Log.d("mPassword: ", mPassword);
Log.d("user.getPassword(): ", user.getPassword());
String userPassword = user.getPassword().toString();
String formPassword = mPassword.toString();
if ( userPassword == formPassword ){
Intent welcomePage = new Intent(this, StartScreenActivity.class);
welcomePage.putExtra("name", mName);
startActivity(welcomePage);
}
else {
showIncorrectPasswordDialog();
}
}else {
showIncorrectUserNameDialog();
}
}
You are comparing the object identity. Use string.equals() to check for equivalence.
if(userPassword.equals(formPassword)){
}
Change
if ( userPassword == formPassword ){
to
if ( userPassword.equals(formPassword) ){
== compares object references, whereas .equals compared String values.
You can not compare string using ==
try like this
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
if ( userPassword.equals(formPassword)){
// do some stuff
}
or
Compares the specified string to this string ignoring the case of the characters and returns true if they are equal.
if(userPassword.equalsIgnoreCase(formPassword))
{
//do some stuff
}
In JAVA to compare between strings, you should use:
if(userPassword.equals(formPassword)) {
// they are equal
}
Change
if ( userPassword == formPassword ){
to
if ( userPassword.equals(formPassword)){
In Java, String comparison is done with .equals(). Using == compares the object reference and not their values.
Java String comparison
In JAVA you should use equals to judge equal of value of different String.
== is used to judge object pointer for string, so it would only return false in your case.

Incompatible types in string

Resources r1 = getResources();
String[] refrigerant = r1.getStringArray(R.array.refrigerant);
if (refrigerant == "")
{
if (et1.getText().toString() == refrigerant[i3]
{
flag = true;
}
I got the error incompatible operand types String[] and string
please give me solution.
refrigerant is an array, but here refrigerant == "" you compare and array with "", which is not possible. You could check for null and refrigerant.length >0
If refrigerant is an String array you can not compare it as an empty String.
Try
if(refrigerant == null || refrigerant.length == 0){
}
Note also that comparing Strings using == as in your second if clause will very often not work, as it tests object identity. You usually want to use string1.equals(string2).
looks like you are trying to compare a string array to a string in your first "if" statement

Categories

Resources