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

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.

Related

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/

equals() method is not working with string

I have a string
number="(1234)5678";
But the if block is not executed:
if("(".equals(number.charAt(0)))
{
System.out.println("IFFF");
}
else
{
System.out.println("OUT");
}
How do I change the boolean expression to execute the if block?
charAt() returns a char. Comparing char and String with .equals() will always return false.
You'll need
if('(' == number.charAt(0))
That is because charAt(..) returns char not String. And one of if-clauses in equals in String class is:
if (anObject instanceof String) {
...
}
you can try following code:
if(number.startsWith("(", 0))
{
System.out.println("IFFF");
}
else
{
System.out.println("OUT");
}
Or you can put: if(number.charAt(0)=='(')
The charAt() function always returns char..equals() is used for comparing strings.
Characters are primitives, you can compare them with the "==" operator.
String number="(1234)5678";
if('(' == number.charAt(0))
{
System.out.println("IFFF");
}
else
{
System.out.println("OUT");
}

Searching an ArrayList for a String; always return false

I am having trouble with this method of my class. It always returns false.
Passenger is a separate class. This is a method in my Train class which creates an array list of Passenger objects. I am making a method that will search the ArrayList passengerList for a Passanger object with the name as the parameter.
public boolean search(String a){
Passenger temp;
boolean query = false;
for (int i =0; i<passengerList.size(); i++)
{
temp=passengerList.get(i);
if (temp.getName() == a)
{
query = true;
}
}
return query;
}
if (temp.getName() == a)
should be
if (temp.getName().equals(a))
String comparison should always use equals() method instead of == (except that strings literals).
if temp.getName() and a both not pointing to same object, == condition will fail.
== checks for references equality. equals() checks for content equality.
This tutorial may help you.
if (temp.getName() == a) should be if (temp.getName().equals(a)).
The former compares references for equality. The latter actually checks to see if the string values are equal.
I would suggest writing this code more elegant and cleaner (with checking for null):
public boolean search(String a){
boolean query = false;
for (Passenger temp : passengerList)
{
if (temp != null && temp.getName()!=null && temp.getName().equals(a))
{
query = true;
}
}
return query;
}

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.

If statement with String comparison fails [duplicate]

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.

Categories

Resources