Can anyone please explain why output of the following is such? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
String str1 = "abc:5";
String str2 = "abc:" + str1.length();
String str3 = "abc:" + 5;
System.out.println(str1==str2);
System.out.println(str1==str3);
Output of the program is :
false
true
But I don't understand why?

== operator will compare reference only
.equals() will compare the values.
in your case
str1==str2 // compares the two references, which are different.
had it been, str1.equals(str2), it would have compared the values, which will return true
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.The “==” operator compares the objects’ location(s) in memory
The “equals” method
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory.

Here str1 = "abc:5"; is located in constant pool of string and str2 is concatenated with 2 different object with new operator. So both str1 and str2 are referring to different object. That's the reason it is showing false.

The == operator is used for only reference variables in java. For example if you are comparing characters a1 and a2 you can use the == operator because the char type is highlighted in most IDEs in Java. To check if two Strings are equal to each other you can use .equals()or .equalsIgnoreCase() to compare the Strings. This is because Strings are objects, not primitives, and require their own method in the class to test if Strings are the same.
For the first System.out.println(); statement, you would use System.out.println(str1.equals(str2)); or System.out.println(str1.equalsIgnoreCase(str2));.
For the second System.out.println(); statement, you would use System.out.println(str1.equals(str3)); or System.out.println(str1.equalsIgnoreCase(str3));.

Related

What does == in java represent? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
What is "==" in Java ? Why can i only compare numerical data type with it and characters can be compared. But not the string data types. What does it provide when i compare two strings?
== compares reference equality: it returns true if its operands have the same value on the stack. (that is, they are either the same numerical quantity or they point to the same object)
Strings are objects, so here we're asking whether they point to the same object on the stack. This will be true if we're talking about String literals defined in code:
If we have
String s1 = "Hello";
String s2 = "Hello";
then s1 == s2 => true
However, if one of the Strings is obtained by some run-time process, for example user input, then it will not be reference-identical, even if the contents of the two Strings are the same.
In Java == compare reference two reference value. If left side reference equals to right side reference will return true else false.
When you come to compare String(objects) you should use equals()
Why?
String a= new String("a");
String b= new String("a");
Here a and b are same by value but they have two different reference.
If you compare to objects (strings are objects) you will compare the reference of both objects.
The '==' operator in Java is used to compare similar variables (like an integer and another integer). For an over-complicated reason, Strings are considered 'Object' type variables. To compare strings use the operator variableString.equals(otherString);

Comparing two strings with equal(==) operator [duplicate]

This question already has answers here:
String comparison and String interning in Java
(3 answers)
Closed 9 years ago.
I was kind of telling some one that , we must use String.equals method to compare two strings values, we can not simply use == operator in java to compare Strings, and told him that == will return false as it doesn't compare the string value but String object reference value.
I have written this example to show him, but for my surprise it always prints true for == operator..
here is the code
public void exampleFunc1(){
String string1 = "ABC";
String string2 = "ABC";
if(string1 == string2)
System.out.println("true");
else{
System.out.println("false");
}
System.out.println(" Are they equal "+(string1 == string2)); // this shouldn't print True but it does
System.out.println(" Are they equal "+(string1.equals(string2)));
}
Output:-
Are they equal true
Are they equal true
So question here is in what circumstances == operator on objects can print true, except that both objects are same instance?
String is one of a few special cases.
Class String keeps a special pool of "interned" Strings. Method myString.intern() looks up myString in this pool. If another String with the same contents already exists in the pool, a pointer to it is returned. If not, myString is added (and a pointer returned).
When you say myString= myString.intern() ;, you are effectively making myString refer to a shared copy or its underlying String available for future sharing (and no duplication). Most library methods creating Strings are subject to this, particularly String literals.
Other cases of "interning" occur with wrapper types Integer, Long, etc. They don't have constructors, but static methods valueOf() that return pre-built, shared objects when they can (usually the 256 values closest to zero), and new objects when they can not. The later is not much problematic because these types are more lightweight than Strings. Long, for example, has a payload of just 8 bytes. String contains a char[] that even empty is 16 bytes or so.
To answer your question, you can not count on any "interning" mechanisms. They have changed in the past, and they could change in the future (or even from one JVM to another), making your code unusable. Always use equals.
You should use
String string1 = new String("ABC");
String string2 = new String("ABC");
Then everything would be correct like what you think,
In this case, "ABC" is just a reference to a const string.
The compiler may be optimizing the assignments and only creating one String object. If you use the explicit String constructor, the == operation should behave as expected.

Is it more proper to use the equivalent operator or the equals() method to compare the contents of Strings? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm reading about the notion of interned strings:
String s1 = "Hi";
String s2 = "Hi";
String s3 = new String("Hi");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); //true
String is an object in Java, but the compiler allows us to use a literal for assigning to a String reference variable, instead of requiring us to use the new operator, because of the ubiquity of strings in programming. The use of the literal for assignments creates an interned string. All interned strings with the same literal point to the same space in memory, thus the equivalent operator is permitted.
It got me wondering, however: would it not be more proper to use the equals() method to compare two string reference variables, given that in Java strings are objects (and not arrays like in other languages) and the contents of objects should be compared using equals(), as the == operator in regards to objects only tells us that they point to the same spot in memory?
Or is it not more proper because the very concept of interned strings makes it clear that one String can only be equivalent (==) to another string if they share the same literal?
If it is more proper, do people commonly use the equals() method regardless, or is it considered overkill?
Yes equals is the method used to compare the contents of string objects. Using == we can only compare whether the two references point to the same memory location or not. But using equals you can check whether two references hold the same string content, be them at the same memory location or not. Logically speaking, when you are trying to compare two strings, you must be looking for comparing the contents of those strings and not the memory locations of them.
As a practice or almost everywhere string equals method is used for string comparision and not ==

condition == between string and constant [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Someone can tell me why this condition
if (lista.getString(0)=="username")
do not return true? I've used to try
if (lista.getString(0)==lista.getString(0))
and dont work, and i have understand that is a language problem.
== tests for reference equality.
.equals tests for value equality.
Threfore you should use:
if (lista.getString(0).equals("username"))
See How do I compare strings in Java?
For String comparison always use equals().
if (lista.getString(0).equals("username"))
Using == , you will end up comparing references, not values.
A simple snippet to clarify further:
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // true because values are same
System.out.println((s1 == s2)); // false because they are different objects
From Java Techniques
Since Strings are objects, the equals(Object) method will return true if two Strings have
the same objects. The == operator will only be true if two String references point to the
same underlying String object. Hence two Strings representing the same content will be
equal when tested by the equals(Object) method, but will only be equal when tested with
the == operator if they are actually the same object.
Use
if (lista.getString(0).equals("username"))
The correct way to compare objects is with,
object1.equals(object2)
And String is an object in Java, so it implies same for String too
s1.equals(s2)
eg :
if (lista.getString(0).equals("username"))

java operator == uses [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Strings in Java : equals vs ==
Comparing strings in java
is == can be apply to Strings ?
if so then what is the use of it for String's data type?
in other words although we should use equal method for comparing two string java, what is the use of == operator for String in java?
== will not compare the value of the String but its addresse. If you want to compare the value use the method equals().
When you want to compare objects in Java, you should use the equals() method. The operator == is used to compare references, not values, in Java objects.
For example:
String s1 = "hello";
String s2 = new String("hello");
boolean comp = s1.equals(s2); // correct, returns true
comp = s1 == s2; // wrong, returns false
The '==' operator compares two Object references. So, in the case of two Strings, it is examining those objects, and seeing if they represent the same location in memory.
The .equals() method compares the Strings' contents to each other.
Comparing objects, == operator compares if the references are the same. In primitive types (int, float, double, boolean) it actually compares the value. Since Strings are objects, it's better to use the equals() method. == will compare if both references of strings are the same, which may not. equals() method is also used by Java Collections.

Categories