Why does Eclipse allow string comparisons with ==? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I understand and know why you typically have to use == to compare strings in java, but for some reason I am able to do it in Eclipse. My code is
Code:
public class Test{
public static void main(String [] args){
String str1 = "string";
if(str1 == "string"){
System.out.println("wtf");
}
}
}
Why does this print "wtf" yet using javac from command line does not?

Eclipse allows you to compare references because it is a legitimate comparison. Just probably not the one you really want.
Because of String interning it will sometimes appear to work, but you should not rely upon it unless you know the strings you're comparing have been interned. The correct way to compare Strings for equal value is to use .equals.

It allow cause it probably faster to compare two address than comparing 2 string (but use it with caution, you probably never have to compare two String address).
It is sometime usefull to compare Object memories address, and as long as String is an object, eclipse allow you to compare using ==

Related

Java - Never Quitting While Loops [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am trying to create a file system/file commander in java, and I want to make the following loop a quit system that triggers when I type dc.
public static void main(String[] args)
boolean x; x=true;
String dc; dc="dc";
while (x=true) {
System.out.println("_____________________");
System.out.println("local disk C:");
System.out.println("bin");
System.out.println("_____________________");
String ltstcmdddd; ltstcmdddd = ltstcm.nextLine();
if (ltstcmdddd==dc) {
break;
}
}
So this is the code for the file commander, it's part of a game so ltstcm is a scanner, and lstcmd is a string you use to input commands for the game (Can't re-use it, I kept adding d's.), like I said before I want to leave this loop when I write dc, I made an if that checked lstcmdddd, I tried with checkingif (lstcmdddd=="dc") and that didn't work. I suspected that changing the value of the boolean x wouldn't work after discovering 'break', that failed. I then tried defining the string dc which contained "dc", and that didn't work either. I searched Stack Overflow about quitting loops, quitting loops failing, and changing values after defining a variable correctly. Nothing relevant to my problem, nothing I could salvage to solve the problem. (I AM NOT ASKING ABOUT COMPARISON!)
You cannot use the == comparison for strings, you have to use .equals, ie: lstcmdddd.equals("dc").
In Java, Strings are objects, so you cannot compare them using the double equal operator. As you are doing that however, your conditional will always return false and the break statement will never execute.
You should rather use .equals than ==. == is used to compare a single char or number, while .equals is used to compare strings.
[...]
String ltstcmdddd; ltstcmdddd = ltstcm.nextLine();
if (ltstcmdddd.equals(dc)) {
[...]
Use ltstcmdddd.equals(dc) instead of ltstcmdddd==dc
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal

How is this thing works internally? [duplicate]

This question already has answers here:
Comparing strings with == which are declared final in Java
(6 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Please follow the code below:
String s="helloworld";
String ss="hello";
String sss=ss+"world";
System.out.print(sss==s);
The output is false. Don't they get checked with the string pool rule for String? And what if we make them final?
A little explanation of internal working will help. Thanks in Advance.
String literals points to the same location if the content of them is same, that's what I got from different sources, am I right? If yes, then what's happening here? I'm a little confused about it.
EDIT:-
I think I didn't phrase it correctly. Let me rephrase it a little(Sorry for earlier attempt):-
String ss="hello";
System.out.print(ss+"world"=="helloworld");
This returns false. However these are String literals and as I have read they don't create two different objects for same value. They are just reference to a same value. Here, "helloworld" is the value for both sides of ==. I hope that I'm able to communicate it well.
Because String is an object, it is comparing that the two objects are the same with ==, which will equate to false.
Using the object ss to concat into sss will not make s = sss.
If you set ss to s, then using == will equate to true since they are now the same object.
If you set a second String object with a string literal, using == will equate the true.
If you use the String object's function .equals(String), you will find that it equates to true.
If you compare two string literals, i.e. "helloworld" == "helloworld" or "helloworld" == "hello" + "world", these will also equate to true.
As lealceldeiro pointed out, strings should always be compared with .equals().
EDIT
A good thing to look at is this answer. It has good references and explanation.
Other resources:
JournalDev
Baeldung

Java test String Handling [duplicate]

This question already has answers here:
Comparing strings with == which are declared final in Java
(6 answers)
Closed 7 years ago.
I was doing some java tests to practice and I came across a question that I don't understand. I created a small program to test it:
The question was to say what would be the output of System.out.println(ab==abc);
I answered 'true' thinking that String literals are not objects, so the can be seen as a kind of primitive type so the comparation == would compare the values and nothing to do with references. But actually the answer in "false";
Then I did this test and I even print the outputs and as you can see ab and abc are exactly the same, however the comparation is returning false , but if I do the comparation directly without doing any concatenation (as I did at the end of the program) the comparation is returning true. So it seems clear the reason has to be with the concatenation, I know that Strings are inmutable so when concatenating then we are getting another String literal with exactly same value.
Can someone please explain me who't going on here?
For those telling me that String literals are objects, why then this code returns true?
String p="meowdeal";
String o="meowdeal";
System.out.println(o == p);
//output true
Of course I would understand that this code
String o=new String("meowdeal");
String p=new String("meowdeal");
System.out.println(o==p);
returns false because in that case they are really objects but not when they are String literal, am I right?
Thank you for your time
public static void main(String ads[] ){
String a="meow";
String ab=a+"deal";
String abc="meowdeal";
System.out.println(a);
System.out.println(ab);
System.out.println(abc);
System.out.println(ab == abc);
//output
//meow
//meowdeal
//meowdeal
//false
String p="meowdeal";
String o="meowdeal";
System.out.println(o == p);
//output
//true
}
ab and abc are objects so .equals() is used to see if they have the same contents and == is used to see if they are the same object.
The last test is only true due to a compile optimization known as string interning
(Your second comment below is correct)
In Java you should compare Strings with .equals(String s) because the '==' returns only true if it's the exact same String in the memory and doesn't compare if the content is the same. In your first example you've got two different strings in your memory. In the second, java saw, that these would be the same and allocated only space for one string and your p and o are only a reference to the same object.
String literals are Objects. User equals method instead of == operator.
Just to explain what happen here,
String p="meowdeal"; //creates "meowdeal" in heap
String o="meowdeal"; // o also refer to same object in heap.
This is called pooling of String. Since both refer to same memory location == operator returns true.

Equality of string references in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Can you explain me why do I have "false" output? If I understand correctly, references point to the same object!
public class mainC {
String str1,str2;
public static void main(String [] args){
mainC m=new mainC();
m.str1="a";
m.str2="b";
System.out.print("m.str1 == m.str2: "+m.str1 == m.str2);
}
}
Thank you.
m.str1 and m.str2 point to different String objects, which is why you get false. The == compares str1 and str2, not m.
Side note: Now, if you had:
m.str1="a";
m.str2="a"; // Same series of characters, e.g., "a"
...you'd be getting true, but it would be misleading. == compares object references. So you can have two different String objects that have the same characters in them, but they would not be == to each other (in fact, that's quite common). To compare strings, you use equals. The reason my example above returns true is that both strings are initialized pointing to literals, and String literals in Java are intern'd by default, so that literals with the same characters are mapped to the same object.
A string in Java is implemented as a reference type and not a value type. Since this is the case, their pointers in memory aren't equal. To get around this, you can use their equals function to compare them.

Comparing two strings in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I know it' a dumb question but why this code doesn't work.
boolean correct = "SampleText" == ((EditText)findViewById(R.id.editText1)).getText().toString();
if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");
The point is to check if content of "editText1" is equal to "Sample Text"
In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.
To fix your code, do this:
String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);
Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.
In Java Strings have to be compared with their equals() method:
String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).
The correct way to compare 2 objects in java is using equals() method of Object class
And as String is an object in java, it should be compared in same way.
The correct way to compare a String is with,
s1.equals(s2)
So you can use this,
boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());
((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!");
It's a bit long and theres probably a better way you could do this. The .toString() feels weird!

Categories