Why doesn't my string comparison with == work? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have this, in my onPostExecute :
String test = currentActivity.getClass().getSimpleName();
if(test == "SplashScreen"){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
The problem is, the value of test is "SplashScreen" (that we can see with the log), but the code never goes in the if, only in the else.
Why does this happen?

As the others had already said you can not use the == operator on strings.
The reason for this is that strings are objects and not primitive datatypes.
With that said the == operator will check if the two strings has the same memory point in the memory if I'm not mistaken.

use equals to compare strings:
if(test.equals("SplashScreen"){
Log.e("OK",test);
} else {
Log.e("OK",test);
}

You can't use == on strings. You should use:
"SplashScreen".equals(test)
Test might be null, it is better to call equals() on "SplashScreen" since you know that it is no null.

Don't compare string with == use .equals()
String test = currentActivity.getClass().getSimpleName();
if(test.equals("SplashScreen")){
Log.e("OK",test);
} else {
Log.e("OK",test);
}

It's better to use equalsIgnoreCase(String string).
String test = currentActivity.getClass().getSimpleName();
if(test.equalsIgnoreCase("SplashScreen")){
Log.e("OK",test);
} else {
Log.e("OK",test);
}

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/

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 conditional statement [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I am using jcreator to practice java language. I came up with a conditional statement in which if the user input is = "test" it will print an "okay!" message. This is my code:
class conditional {
public static void main (String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
if (username == "test") {
System.out.println("okay");
}
else {
System.out.println("not okay");
}
}
The above code does not show any error, it does not display the "okay" && "not okay" message either. I am not sure what's wrong with my logic.
Strings should be compared using .equals rather than ==. This is the case for all non-primitive comparisons. For example, you would compare two int fields with ==, but because Strings are not primitive, .equals is the correct choice.
if (username.equals("test")) {
You should use String.equals here.
if (username.equals("test")) {
Otherwise, you're comparing the identities of the objects rather than their semantics. In fact, you have two separate Strings here, which satisfy semantic equality.
as #veer said,
you can use equalsIgnoreCase / equals if (username.equals("test")) { ... }
Or
You can use compareToIgnoreCase / compareTo
if (username.compareTo("test")==0) { ... }
Or If you want to use == do username.intern(); Then you can use ==.
Note: Not a recommended approch just for FYI.
To compare string you need to use .equals() method and also if you need ignore the case of the letters in the String you can use .equalsIgnoreCase()
if (username.equals("test")){
}
else{
}
It will work if you do it like this:
import java.util.Scanner;
class Conditional {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
if (username.equals("test")) {
System.out.println("okay");
} else {
System.out.println("not okay");
}
user_input.close();
}
}
A few remarks:
Class names should start with an upper case.
Use equals to compare Strings.
You state that no result is printed at all. You will have to click in the console to type your answer and end the input with Enter.

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