If statement with String comparison fails [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I really don't know why the if statement below is not executing:
if (s == "/quit")
{
System.out.println("quitted");
}
Below is the whole class.
It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out.
Thanks for looking :)
class TextParser extends Thread {
public void run() {
while (true) {
for(int i = 0; i < connectionList.size(); i++) {
try {
System.out.println("reading " + i);
Connection c = connectionList.elementAt(i);
Thread.sleep(200);
System.out.println("reading " + i);
String s = "";
if (c.in.ready() == true) {
s = c.in.readLine();
//System.out.println(i + "> "+ s);
if (s == "/quit") {
System.out.println("quitted");
}
if(! s.equals("")) {
for(int j = 0; j < connectionList.size(); j++) {
Connection c2 = connectionList.elementAt(j);
c2.out.println(s);
}
}
}
} catch(Exception e){
System.out.println("reading error");
}
}
}
}
}

In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))

To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>

Strings in java are objects, so when comparing with ==, you are comparing references, rather than values. The correct way is to use equals().
However, there is a way. If you want to compare String objects using the == operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";
String b = "aaa";
boolean b = a == b;
b would be true. Why?
Because the JVM has a table of String constants. So whenever you use string literals (quotes "), the virtual machine returns the same objects, and therefore == returns true.
You can use the same "table" even with non-literal strings by using the intern() method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.

You can use
if("/quit".equals(s))
...
or
if("/quit".compareTo(s) == 0)
...
The latter makes a lexicographic comparison, and will return 0 if the two strings are the same.

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Related

If statement doesn't work, the program enters directly the "else" statement [duplicate]

This question already has answers here:
How != and == operators work on Integers in Java? [duplicate]
(5 answers)
Closed 5 years ago.
I am trying to write a program which detects "idle" status but I don't see the problem in my code. Could someone help me please with an useful tip? Here's my code:
package idlestatus;
import java.awt.MouseInfo;
public class Idlestatus {
public static void main(String[] args) throws InterruptedException {
Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
Integer afterPointX;
Integer afterPointY;
while (true) {
Thread.sleep(10000);
afterPointX = MouseInfo.getPointerInfo().getLocation().x;
afterPointY = MouseInfo.getPointerInfo().getLocation().y;
if (firstPointX == afterPointX && firstPointY == afterPointY) {
System.out.println("Idle status");
} else {
System.out.println("(" + firstPointX + ", " + firstPointY + ")");
}
firstPointX = afterPointX;
firstPointY = afterPointY;
}
}
}
If is working but your condition is always getting false, because you are using Integer instead of primitive int. Note that when you use Object, compare them with .equals() method instead of ==.
Therefore :
if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
//your code...
}
See this for difference between == and Object.equals() method.
And as mentioned in comments, you can always use int for such purposes, instead of Integer.
See this for difference between Integer and int.
You are comparing two objects memory addresses , which is Integer object(wrapper class).
if (firstPointX == afterPointX && firstPointY == afterPointY)
What you want to do is compare values in these two objects. To do that you need to use like below:
if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY))
Wrapper / covering classes:
There is a wrapper class for each primitive data type.
Primitive types are use for performance reasons(Which better for your
program).
Cannot create objects using primitive types.
Allows a way to create objects and manipulate basic types(i.e.
converting types).
Exsample:
Integer - int
Double - double

iBeacon.getProximityUuid() can't equal to string?

I try to compare iBeacon.getProximityUuid() with the custom string, but it can't work.
I'm very sure the first char is "a", but the result always return false!
I use the RadiusNetwork's iBeacon library.
String tempstr = iBeacon.getProximityUuid().substring(0, 1);
if (tempstr == "a") {
return true;
}
else {
return false;
}
You must change Change if (tempstr == "a") to if (tempstr.equals("a")). In Java, the == operator is used for object equality. Because the two objects aren't the same instance, tempstr == "a" always returns false. Using the .equals method actually compares the strings.

If statement returns only the result from the "else" statement

I am trying to make a script that compares the user input with another string. The problem is with my if statement. I don't get errors but it always returns the result that is in the "else" statement. Here is the code:
String [] lessons_titles = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","30","40","50","60","70","80","90"};
final TextView dan_view = (TextView)findViewById(R.id.DanText);
final int position = getIntent().getExtras().getInt("position");
final String title = lessons_titles[position];
check_b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textField = check_text.getText().toString();
if (textField == title){
dan_view.setTextColor(Color.GREEN);
}
else {
dan_view.setTextColor(Color.RED);
}
}
});
Use equals() method instead of == operator when you compare String. In case of String, two string will be equal if their reference are same and to find out that both of them referencing to the same point, you have to use equals() method. == operator can only compare primitive type value but instance of String is object.
So, your condition should be as follows...
if (textField.equals(title)){
dan_view.setTextColor(Color.GREEN);
} else {
dan_view.setTextColor(Color.RED);
}
== is for testing whether two strings are the same object; - reference equality.
You want to check the value so should use .equals()
Take a look at:
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
for further clarification.
Your error is here:
if (textField == title){ //<--
textField is a string, you need to check string equality using .equals(), e.g.
if (textField.equals(title)){ //<--
use this
if (textField.compareTo(title) == 0)
{
dan_view.setTextColor(Color.GREEN);
}
else {
dan_view.setTextColor(Color.RED);
}
"textField == title" Using == will check that they are the exact same, not just value wise but also stored in the same memory location.
Instead try using
if (textField.equals(title)){
A good example is shown here http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

Using Recursion with Username matching [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am implementing a String matching algorithm for a username database. My method takes an existing Username database and a new username that the person wants and it checks to see if the username is taken. if it is taken the method is supposed to return the username with a number that isn't taken in the database.
Example:
"Justin","Justin1", "Justin2", "Justin3"
Enter "Justin"
return: "Justin4"
since Justin and Justin with the numbers 1 thru 3 are already taken.
In my code sample below, newMember returns Justin1 even though it already exists--where is the mistake?
public class UserName {
static int j = 0;
static String newMember(String[] existingNames, String newName){
boolean match = false;
for(int i = 0; i < existingNames.length; i++){
if(existingNames[i] == (newName)){
match = true;
}
}
if(match){
j++;
return newMember(existingNames, newName + j);
}
else{
return newName;
}
}
public static void main(String[] args){
String[] userNames = new String[9];
userNames[0] = "Justin1";
userNames[1] = "Justin2";
userNames[2] = "Justin3";
userNames[3] = "Justin";
System.out.println(newMember(userNames, "Justin"));
// I don't understand why it returns Justin1 when the name is already taken
// in the array.
}
}
This line:
if(existingNames[i] == (newName)){
Should become
if(existingNames[i].equals(newName)){
In general, always use equals instead of == for Strings in Java.
I would change your approach to this. I think it would be better to use a Map<String, Integer>. For example, the fact that "Justin" - "Justin3" are taken usernames can be represented by the map:
{"Justin": 3}
To check if a username is taken, check if it's a key in the map. To get the "next" username for a specific taken username, get the value corresponding to the name from the map and add 1. Something like this:
static String newMember(Map<String, Integer> existingNames, String newName) {
if (existingNames.containsKey(newName)) {
int newNum = existingNames.get(newName) + 1;
existingNames.put(newName, newNum);
return newName + newNum;
}
existingNames.put(newName, 0);
return newName;
}
Oh, and use .equals() instead of == when comparing strings :)
*Never ever compare equality of Strings with ==. use equals() *
Use .equals to compare strings in Java, not ==.
== will determine if the string references are the same which they almost certainly will not be. (There are rare cases when they may be due to the intern pool.)
.equals will determine if the content of the strings are the same.
When comparing strings in Java, you should generally use the equals() methods to do so.
Using == with strings compares the references, not the underlying objects. Use str.equals().
I guess you have a function somewhere in your application answering if a username already exists, I call this usernameExists(String username) returning true or false.
String getOkUsername (String wantedUsername) {
//if it's free, return it!
if(!usernameExists(wantedUsername)) {
return wantedUsername;
};
//OK, already taken, check for next available username
int i=1;
while(usernameExists(wantedUsername+Integer.toString(i))) {
i++;}
return wantedUsername + Integer.toString(i);
}
You're not comparing the strings correctly, and you're adding the integer 1 to a string. Comparing strings is done with .equals. In order to concatenate the integer onto the end of the string:
static Integer j=0;
return newMember(existingNames, newName + j.toString());
It is much easier to do it in SQL:
select ... where ... LIKE username%

Java comparison with == of two strings is false? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
String parts is String[6]:
["231", "CA-California", "Sacramento-155328", "aleee", "Customer Service Clerk", "Alegra Keith.doc.txt"]
But when I compare parts[0] with "231":
"231" == parts[0]
the above result is false,
I'm confused, so could anybody tell me why?
The == operator compares the object references, not the value of the Strings.
To compare the values of Strings, use the String.equals method:
"231".equals(parts[0]);
This is true with any other object in Java -- when comparing values, always use the equals method rather than using the == operator.
The equals method is part of Object, and should be overridden by classes which will be compared in one way or another.
If the strings are not interned, then == checks reference identity. Use:
"231".equals(parts[0]);
instead.
== in Java compares the address of the objects (strings in this case).
What you want is parts[0].equals("231")
The following prints out "true";
String s = "231";
if(s == "231")
{
System.out.println("true");
}
else
{
System.out.println("false");
}
This is because Strings are not mutable and java will try and save as much space as possible, so it points both to the same memory reference.
However, the following prints out "false":
String s = new String("231");
if(s == "231")
{
System.out.println("true");
}
else
{
System.out.println("false");
}
new will force it to store the string in a new memory location.
By the way, you should ALWAYS use .equals() to compare strings (for cases just like this one)
Use equals method: parts[0].equals("231"). == operator compares object references.
"==" compares object references, in your case "231" is a different object than parts[0].
You want to use String.equals.
parts[0].equals("231")
The answer is very simple: when you compare strings through == operator, you actually compare if two different variables refer to a single String object. And they don't, the string in the array and newly created "231" are different String objects with the same contents.
The right thing to do is to use the folllowing expression: "231".equals(parts[0]) or "231".equalsIgnoreCase(parts[0]). This will give you what you need and return true if these String objects contain the same values.
I thought it might be helpful to express the answer in a test case:
public class String231Test extends TestCase {
private String a;
private String b;
protected void setUp() throws Exception {
a = "231";
StringBuffer sb = new StringBuffer();
sb.append("231");
b = sb.toString();
}
public void testEquals() throws Exception {
assertTrue(a.equals(b));
}
public void testIdentity() throws Exception {
assertFalse(a == b);
}
}
You may also use compareTo(String) method:
String str = "test";
if( str.compareTo("test") == 0)
//the argument string is equal to str;
else
//the argument string is not equal to str;
Use the equals method to compare objects:
String[] test = {"231", "CA-California", "Sacramento-155328", "aleee",
"Customer Service Clerk", "Alegra Keith.doc.txt"};
System.out.println("231".equals(test[0]));
The comparison '==' compares references, not values.
Here's really nice example. The '==' operator with string can be really tricky in Java.
class Foo {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = "h";
c = c + "ello";
String operator = null;
if(a == b) {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(a + operator + b);
if(a == c) {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(a + operator + c);
if(a == "hello") {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(a + operator + "hello");
if(c == "hello") {
operator = " == ";
} else {
operator = " != ";
}
System.out.println(c + operator + "hello");
}
}
Which will produce following output:
hello == hello
hello != hello
hello == hello
hello != hello
As many others have already explained, you try to compare with equality operator, but then it would relies on Object.equals() instead of String.equals().
So you can do the job by explicitly calling String.equals(), but instead of writing
parts[0].equals("blahblah")
I would prefer such :
"blahblah".equals(parts[0])
As it avoids testing potential nullity of parts[0] (but be careful that parts variable itself could be null...)
Another way is using String.intern() :
if (parts[0].intern() == "blahblah") ...
See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern() for more info on that.

Categories

Resources