This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
How can it be possible, that If statement doesn't understand two equal things that they are the same?
Situation:
I write into txfName field only letter b and then push button "Ok".
Code:
String letter = "b";
boolean same = false;
if (letter == txfName.getText()) {
same == true;
}
After if statement program shows me that variable same is false. Why? How can it be possible?
If I write code like this:
String letter = "b";
boolean same = false;
if (letter == "b") {
same == true;
}
Then after if statement program shows me that variable same is true. I don't understand, how it can be possible.
== compares to see if two objects are the same. When you are dealing with strings they are objects, so they may not have the same reference event though they can have the same value. You want to use .equals() instead.
For more details, Strings are special in java, as there are some internal workings that have a String pool. So in some cases the == may actually seem to be working, but in other cases it may not be. The reason is the String pool tries to cache recently used Strings to reduce the memory overhead. Anyway .equals() is what you are looking for.
for your first question
String letter = "b";
boolean same = false;
if (letter.equals( txfName.getText())) {
same = true;
}
return same;
will return true if txfName.getText() returns "b"
To compare objects in java use .equals() method instead of "==" operator
Replace the following code
if (letter == txfName.getText())
to
if (letter.equals(txfName.getText()))
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I'm trying to make a dutch zipcode validator. On the first step i need to check if the first char of the zipcode (which is always a number), is between 1-9. But when i just tried to make a simple if statement to check if the first char is false, it comes back as true. In this example I took a premade string "2097AR" as input for the method "checkPostcode".
public static boolean checkPostcode(String postcode){
String postcodeEen = postcode.substring(0,1);
boolean resultCheck = true;
System.out.println(postcodeEen);
if (postcodeEen == "1"){
resultCheck = false;
}
return resultCheck;
}
The = operator for strings in Java checks if the two objects are the same, whereas #equals(String s) checks if the contents of the string are the same.
The function always returns true because postcodeEen and "1" aren't the same object, which makes the condition postcodeEen == "1" false.
Here is the working code segment:
if(postcodeEen.equals("1"){
return false;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I ave a code where I want to use != sign. But since I am using String, How do I not equals Sign. Hers is my code. So I want all this statement not to equal to each other so it can print Tie Game.
if (Array[0] == Array[currentPlayer] && Array [1] ==
Array[currentPlayer] && !Array [2] == Array[currentPlayer])
The above code is when everything equals to each other. But I want this statements not to equal each other.
Keep in mind that I have not used Int or Char, I am using String.
For string inequality, negate a call to the equals method using the !:
String x = "ABC";
String y = "XYZ";
if(!x.equals(y)) {
//do stuff
}
! can be used to negate ANY boolean expression, and String.equals returns a boolean.
You can do something like:
if (!Array[0].equals(Array[currentPlayer]) && !Array[1].equals(Array[currentPlayer])
&& Array[2].equals(Array[currentPlayer]))
Use equals() if you want case sensitive match meaning it will look at case of string as well when matching.
If you want case insensitive matching you can use equalsIgnoreCase() method in place of equals()
This question already has answers here:
String.equals() with multiple conditions (and one action on result) [duplicate]
(7 answers)
Closed 2 years ago.
I was wondering how I can compare multiple strings in one line. I tried using the || but it doesn't work for booleans or strings. this is what my code is like:
}else if(question != "a" || "b") {
System.out.println("Sorry that isn't an A or a B");
For those who marked it duplicate, I checked over 200 questions here on stack overflow, and none worked. The one #Chrylis posted actually didn't help. they were just asking about the difference in == and .equals()
First of all, don't use == for strings. You'll learn why later. You want to compare strings by their contents, not where they are in memory. In rare cases a string of "a" could compare false to another string called "a".
Second, split it up so you are performing boolean logic on the comparison results:
else if(!(question.equals("a") || question.equals("b")) {
You can try using Arrays.asList():
else if (!Arrays.asList("a", "b").contains(question)) {
...
}
Two things wrong: You can't just specify multiple values with || (or &&) like that. You need to specify both the left side and the right side explicitly each time.
Second, use equals to compare String values, not the == (or in this case !=) operators. == compares two object references to see if they are the same object.
} else if (!("a".equals(question) || "b".equals(question)))
Or an alternative is to make a temporary List and use contains, which might be clearer for longer lists of things to test:
} else if (!Arrays.asList("a", "b").contains(question))
String[] options = {"a", "b"}; // Must be sorted.
if (java.util.Arrays.binarySearch(options, question) < 0) {
System.out.println("Sorry that isn't an A or a B");
}
Alternatively (assuming your strings don't contain |:
if ("a|b".indexOf(question) == -1) {
System.out.println("Sorry that isn't an A or a B");
}
As an aside, you should use equals for objects not ==
To answer your question, you have to repeat the equals call on both sides of the ||
}else if( ! (question.equals("a") || question.equals("b")) ) {
}else if( !(question.equals("a") || question.equals("b")) {
System.out.println("Sorry that isn't an A or a B");
You can't do NOT equals a OR b
You have to do NOT(equals a OR equals b)
Secondly, you are comparing strings with !=, but you should be comparing strings using the .equals(String) method. This has been said millions of times, but: == and != are comparing object references, whereas .equals(String) is comparing String values.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
String firstanswer = scan.nextLine();
if(firstanswer == answer2)
{
System.out.println("OK lets get started");
}
else
{
System.out.println("That is incorrect, of course you want to play");
}
//answer2 is set to "yes", i declared it above
make it firstanswer.equals(answer2) instead of firstanswer == answer2.
When you want to check for equality of String in java then use equals method instead of == operator.
equals method checks whether the contents of String objects are same
== operator checks whether both the reference variables refer to same String object
To understand about strings and equality, read String comparison with equals and assignment operator It will help you understand the concept well.
Use equals() instead of == to compare strings.
if(firstanswer.equals(answer2)) is what you're looking for.
firstanswer and answer2 are pointers to string objects. == checks to see whether the pointers are equal (whether they point to the same object), while equals() compares the contents of the two strings and returns a boolean representing whether or not the contents are equal.
This question already has answers here:
String comparison and String interning in Java
(3 answers)
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 10 years ago.
I'm new to this site and didn't realize there were other questions that answered what I'm asking. I've figured it out and I will delete this post as soon as it lets me. Thank you.
I just started learning java again and I have a quick question.
Usually, using == to compare strings would not work and you would have to use .equals instead.
But now while coding, I found they are doing the same thing when they are not supposed too and I'm trying to figure out why.
Here's the code.
String s = "Hello";
String x = "Hello";
if (x == s){
System.out.println("It is working!");
}//end if
else {
System.out.println("It is not working");
}//end else
if (x.equals(s)){
System.out.println("Match");
}//end if
else {
System.out.println("No match");
}//end else
Basically you're seeing the result of string interning. From section 15.28 of the JLS:
Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
So your two variable values actually refer to the same strings. If you use:
String s = new String("Hello");
String x = new String("Hello");
... then you'll see the behaviour you expect.
Reason is that your vars x and s have the same reference hence == behaves same as .equals.
When Java compiler optimizes your string values (literals), it determines that both x and s have same value and hence you need only one String object. As result, both x and s point to the same String object and some little memory is saved. It's safe operation since String is an immutable object in Java.
well, In this particular case there is only one string object created and cached in the string constant pool and both of the reference variables refer to the same string object which is stored in the string constant pool . thus you == test passes
String s = "Hello"; Line 1
String x = "Hello"; Line 2
When line 1 is executed one string object (Hello) is created and cached in String Constant pool .
**String Constant Pool:** {s--->"Hello"}
when line 2 is executed, it first checks if there is any object with the same value in string constant pool, if there exists one. it simply points the reference to the already created object in the pool.
**String Constant Pool:** {s,x--->"Hello"}