how to check reference equality in an object which implements content equality? - java

...in other words:
let's suppose I have 2 Strings declared as so:
String one = new String("yay!");
String two = new String("yay!");
these two Strings are two different objects, but if I run
if(one.equals(two))
System.out.println("equals() returns true.");
I get "equals() returns true".
This is because the String class overrides the equals() method to implement a content level equality.
However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two.
How can I do that?
I tried this:
one.getClass().getSuperclass().equals();
to try to invoke the Object equals() method of the String one but it didn't work.
Any advice?

If you want to check reference just perform:
one == two
But be careful with strings. There is a thing called String constant pool so they may refer to the same object.

String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:
String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
System.out.println("equals() returns true.");
if(one == two)
System.out.println(" == operator returns true.");
result is :
equals() returns true.
see following link for more information:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
Java String.equals versus ==

Use simple == comparison. However to avoid String interning you have to create your Strings using char arrays such as: String me = new String(new char[] { 'm', 'e' }); instead of using String literals "me" such as String me = new String("me");.

if (one == two)
System.out.println("one and two are the same object");

The only this you need is "==" equality operator.

Related

Substring in if statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
public static void main(String...aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos = "Jorman 14988611";
StringTokenizer tokens = new StringTokenizer(strDatos, " ");
int nDatos = tokens.countTokens();
String[] datos = new String[nDatos];
int i = 0;
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
datos[i] = str;
i++;
}
//System.out.println (usuario);
if ((datos[0] == usuario)) {
System.out.println("WORKING");
}
}
Use the string.equals(Object other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.
Meet Jorman
Jorman is a successful businessman and has 2 houses.
But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals() method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals method behaves. So datos[0].equals(usuario) will return true, because it performs a logical comparison.
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.
Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.
Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1; // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2; // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.
equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.
== operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is true.
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.
Hope you understood the difference between == and <Object>.equals()
Thanks.
== tests for reference equality.
.equals() tests for value equality.
Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).
== is for testing whether two strings are the same Object.
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.
Instead of
datos[0] == usuario
use
datos[0].equals(usuario)
== compares the reference of the variable where .equals() compares the values which is what you want.
Let's analyze the following Java, to understand the identity and equality of Strings:
public static void testEquality(){
String str1 = "Hello world.";
String str2 = "Hello world.";
if (str1 == str2)
System.out.print("str1 == str2\n");
else
System.out.print("str1 != str2\n");
if(str1.equals(str2))
System.out.print("str1 equals to str2\n");
else
System.out.print("str1 doesn't equal to str2\n");
String str3 = new String("Hello world.");
String str4 = new String("Hello world.");
if (str3 == str4)
System.out.print("str3 == str4\n");
else
System.out.print("str3 != str4\n");
if(str3.equals(str4))
System.out.print("str3 equals to str4\n");
else
System.out.print("str3 doesn't equal to str4\n");
}
When the first line of code String str1 = "Hello world." executes, a string \Hello world."
is created, and the variable str1 refers to it. Another string "Hello world." will not be created again when the next line of code executes because of optimization. The variable str2 also refers to the existing ""Hello world.".
The operator == checks identity of two objects (whether two variables refer to same object). Since str1 and str2 refer to same string in memory, they are identical to each other. The method equals checks equality of two objects (whether two objects have same content). Of course, the content of str1 and str2 are same.
When code String str3 = new String("Hello world.") executes, a new instance of string with content "Hello world." is created, and it is referred to by the variable str3. And then another instance of string with content "Hello world." is created again, and referred to by
str4. Since str3 and str4 refer to two different instances, they are not identical, but their
content are same.
Therefore, the output contains four lines:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4
You should use string equals to compare two strings for equality, not operator == which just compares the references.
It will also work if you call intern() on the string before inserting it into the array.
Interned strings are reference-equal (==) if and only if they are value-equal (equals().)
public static void main (String... aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;
while(tokens.hasMoreTokens()) {
String str=tokens.nextToken();
datos[i]= str.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}
Generally .equals is used for Object comparison, where you want to verify if two Objects have an identical value.
== for reference comparison (are the two Objects the same Object on the heap) & to check if the Object is null. It is also used to compare the values of primitive types.
== operator compares the reference of an object in Java. You can use string's equals method .
String s = "Test";
if(s.equals("Test"))
{
System.out.println("Equal");
}
If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.
Example:
String a = "name";
String b = "name";
if(a == b) and (a.equals(b)) will return true.
But
String a = new String("a");
In this case if(a == b) will return false
So it's better to use the .equals operator...
The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.
I know this is an old question but here's how I look at it (I find very useful):
Technical explanations
In Java, all variables are either primitive types or references.
(If you need to know what a reference is: "Object variables" are just pointers to objects. So with Object something = ..., something is really an address in memory (a number).)
== compares the exact values. So it compares if the primitive values are the same, or if the references (addresses) are the same. That's why == often doesn't work on Strings; Strings are objects, and doing == on two string variables just compares if the address is same in memory, as others have pointed out. .equals() calls the comparison method of objects, which will compare the actual objects pointed by the references. In the case of Strings, it compares each character to see if they're equal.
The interesting part:
So why does == sometimes return true for Strings? Note that Strings are immutable. In your code, if you do
String foo = "hi";
String bar = "hi";
Since strings are immutable (when you call .trim() or something, it produces a new string, not modifying the original object pointed to in memory), you don't really need two different String("hi") objects. If the compiler is smart, the bytecode will read to only generate one String("hi") object. So if you do
if (foo == bar) ...
right after, they're pointing to the same object, and will return true. But you rarely intend this. Instead, you're asking for user input, which is creating new strings at different parts of memory, etc. etc.
Note: If you do something like baz = new String(bar) the compiler may still figure out they're the same thing. But the main point is when the compiler sees literal strings, it can easily optimize same strings.
I don't know how it works in runtime, but I assume the JVM doesn't keep a list of "live strings" and check if a same string exists. (eg if you read a line of input twice, and the user enters the same input twice, it won't check if the second input string is the same as the first, and point them to the same memory). It'd save a bit of heap memory, but it's so negligible the overhead isn't worth it. Again, the point is it's easy for the compiler to optimize literal strings.
There you have it... a gritty explanation for == vs. .equals() and why it seems random.
#Melkhiah66 You can use equals method instead of '==' method to check the equality.
If you use intern() then it checks whether the object is in pool if present then returns
equal else unequal. equals method internally uses hashcode and gets you the required result.
public class Demo
{
public static void main(String[] args)
{
String str1 = "Jorman 14988611";
String str2 = new StringBuffer("Jorman").append(" 14988611").toString();
String str3 = str2.intern();
System.out.println("str1 == str2 " + (str1 == str2)); //gives false
System.out.println("str1 == str3 " + (str1 == str3)); //gives true
System.out.println("str1 equals str2 " + (str1.equals(str2))); //gives true
System.out.println("str1 equals str3 " + (str1.equals(str3))); //gives true
}
}
The .equals() will check if the two strings have the same value and return the boolean value where as the == operator checks to see if the two strings are the same object.
Someone said on a post higher up that == is used for int and for checking nulls.
It may also be used to check for Boolean operations and char types.
Be very careful though and double check that you are using a char and not a String.
for example
String strType = "a";
char charType = 'a';
for strings you would then check
This would be correct
if(strType.equals("a")
do something
but
if(charType.equals('a')
do something else
would be incorrect, you would need to do the following
if(charType == 'a')
do something else
a==b
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant.
You want to know if two references are to the same object
"a".equals("b")
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.
Use Split rather than tokenizer,it will surely provide u exact output
for E.g:
string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}
After this I am sure you will get better results.....

Can't get else if statement to work in Java

Ok I am trying to make this simple thing but it won't work. I am a beginner in Java and would like some help. Every time I run the code below I get the output That is not a valid option. What am I doing wrong?
package test;
import java.util.Scanner;
public class options {
public void options() {
Scanner scnr = new Scanner(System.in);
String slctn;
System.out.println("What would you like to do?");
System.out.println("a) Travel the expedition");
System.out.println("b) Learn more about the expedition");
slctn = scnr.nextLine();
if (slctn == "a"){
travel exeTravel = new travel();
exeTravel.travel();
}else if (slctn=="b"){
learn exeLearn = new learn();
exeLearn.learn();
}else{
System.out.println("That is not a valid option");
}
}
}
Well, first off, == is a fundamental operator in the language. The result type of the expression is a boolean. For comparing boolean types, it compares the operands for the same truth value. For comparing reference types, it compares the operands for the same reference value (i.e., refer to the same object or are both null). For numeric types, it compares the operands for the same integer value or equivalent floating point values. See the Java Language Specification.
In contrast, equals() is an instance method which is fundamentally defined by the java.lang.Object class. This method, by convention, indicates whether the receiver object is "equal to" the passed in object. The base implementation of this method in the Object class checks for reference equality. Other classes, including those you write, may override this method to perform more specialized equivalence testing. See the Java Language Specification.
The typical "gotcha" for most people is in using == to compare two strings when they really should be using the String class's equals() method. From above, you know that the operator will only return "true" when both of the references refer to the same actual object. But, with strings, most uses want to know whether or not the value of the two strings are the same -- since two different String objects may both have the same (or different) values.
slctn = scnr.nextLine();
if (slctn.equals("a")){
travel exeTravel = new travel();
exeTravel.travel();
}else if (slctn.equals("b")){
learn exeLearn = new learn();
exeLearn.learn();
}else{
System.out.println("That is not a valid option");
}
slctn.equals("a") will work.
Read this to understand why: What is difference between == and equals() in java?
In Java, when you need to compare two objects for equality (that is, to determine if they have the same value) you must use equals(). The == operator is used for testing if two objects are identical, that is: if they're exactly the same object in memory. In your code, replace this:
slctn == "a"
slctn == "b"
With this:
"a".equals(slctn)
"b".equals(slctn)
Also notice that it's a good idea to invert the order of the comparison ("a" before slctn), just in case slctn is null.
In java when matching any object the == operator will only match the reference of those two objects.
If we take your example slctn == "a". Say slctn has its reference value at abc123, your other sting "a" will have a different reference value as it is not the same object.
The method .equals checks what the letters in the string object are and matches the value of the letters in the two strings. Therefore if your object slctn contains "a", it will match with the string "a"
In java == operator compare reference of two objects, for sample :
String s_1 = new String("Sample");
String s_2 = new String("Sample");
System.out.println(s_1 == s_2);
result will is :
false
this happen because s_1 is a reference at memory and s_2 is difference refernce at memroy also.
For solve this issue , you have to compare tow objects by equals method. for sample
String s_1 = new String("Sample");
String s_2 = new String("Sample");
System.out.println(s_1.equals(s_2));
result will is :
true

("kg"=="kg") returns false. How Do I tell java, that this comparison returns true? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java string comparison?
I was trying to do this:
boolean exit = false;
while(exit==false && convStoreIndex<convStoreLength) {
if(conversionStore[convStoreIndex].getInUnit()==inUnit) {
indexCount++;
exit=true;
}
convStoreIndex++;
}
but the if-condition never went true, even if the two Strings were the same(checked this in the debugger).
so I added some lines:
boolean exit = false;
while(exit==false && convStoreIndex<convStoreLength) {
Log.v("conversionStore["+String.valueOf(convStoreIndex)+"]", conversionStore[convStoreIndex].getInUnit()+"|"+inUnit);
String cs = conversionStore[convStoreIndex].getInUnit();
String iu = inUnit;
Log.v("cs", cs);
Log.v("iu", iu);
Log.v("Ergebnis(cs==iu)", String.valueOf(cs==iu));
if(conversionStore[convStoreIndex].getInUnit()==inUnit) {
indexCount++;
exit=true;
}
convStoreIndex++;
}
and here is the extract from LogCat:
09-15 11:07:14.525: VERBOSE/cs(585): kg
09-15 11:07:16.148: VERBOSE/iu(585): kg
09-15 11:07:17.687: VERBOSE/Ergebnis(cs==iu)(585): false
the class of conversionStore:
class ConversionStore {
private String inUnit;
[...]
public String getInUnit() {
return inUnit;
}
}
Who is going crazy, java or me?
Don't use == to compare String objects, use .equals():
if(conversionStore[convStoreIndex].getInUnit().equals(inUnit)) {
To compare Strings for equality, don't use ==. The == operator checks
to see if two objects are exactly the same object. Two strings may be
different objects, but have the same value (have exactly the same
characters in them). Use the .equals() method to compare strings for
equality.
Straight from the first link Google provided when searching "Java string comparison"...
Please use String.equals() to compare by string content instead of reference identity.
You are comparing your Strings using == : cs==iu.
But this will return true only if both Strings are actually the same object. This is not the case here: you have two distinct instances of String that contain the same value.
You should use String.compareTo(String).
use .equals(); method instread of ==
Becase ::
They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.
For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.
s1 = new String("abc");
s2 = new String("abc");
Now, if you use the "equals()" method to check for their equivalence as
if(s1.equals(s2))
System.out.println("s1.equals(s2) is TRUE");
else
System.out.println("s1.equals(s2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.
Lets check the '==' operator..
if(s1==s2)
System.out.printlln("s1==s2 is TRUE");
else
System.out.println("s1==s2 is FALSE");
Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.
Try running the program without 'new String' and just with
String s1 = "abc";
String s2 = "abc";
You will get TRUE for both the tests.
Reson::
After the execution of String str1 = “Hello World!”; the JVM adds the string “Hello World!” to the string pool and on next line of the code, it encounters String str2 =”Hello World!”; in this case the JVM already knows that this string is already there in pool, so it does not create a new string. So both str1 and str2 points to the same string means they have same references. However, str3 is created at runtime so it refers to different string.
Two things:
You don't need to write "boolean==false" you can just write "!boolean" so in your example that would be:
while(!exit && convStoreIndex<convStoreLength) {
Second thing:
to compare two Strings use the String.equals(String x) method, so that would be:
if(conversionStore[convStoreIndex].getInUnit().equals(inUnit)) {

Comparing two identical strings with == returns false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am making an archive for my family. There are no syntax errors, however whenever I type in "Maaz", it evaluates realName == "Maaz" to false and goes to the else statement.
import java.util.Scanner;
public class MainFamily {
public static void main (String [] args) {
System.out.println("Enter you're name here");
Scanner name = new Scanner(System.in);//Scanner variable = name
String realName;
realName = name.nextLine();//String variable = user input
System.out.println("Name: "+ realName);
if (realName == "Maaz") {
System.out.println("Name: Maaz");
} else {
System.out.println("This person is not in the database");
}
}
}
TL;DR
You wrote (this doesn't work):
realName == "Maaz"
You meant this:
realname.equals("Maaz")
or this:
realname.equalsIgnoreCase("Maaz")
Explanation
In Java (and many other Object-Oriented programming languages), an object is not the same as a data-type. Data-types are recognized by the runtime as a data-type.
Examples of data-types include: int, float, short.
There are no methods or properties associated with a data-type. For example, this would throw an error, because data-types aren't objects:
int x = 5;
int y = 5;
if (x.equals(y)) {
System.out.println("Equal");
}
A reference is basically a chunk of memory that explicitly tells the runtime environment what that data-block is. The runtime doesn't know how to interpret this; it assumes that the programmer does.
For example, if we used Integer instead of int in the previous example, this would work:
Integer x = new Integer(5);
Integer y = new Integer(5);
if (x.equals(y)) {
System.out.println("Equal");
}
Whereas this would not give the expected result (the if condition would evaluate to false):
Integer x = new Integer(5);
Integer y = new Integer(5);
if (x == y) {
System.out.println("Equal");
}
This is because the two Integer objects have the same value, but they are not the same object. The double equals basically checks to see if the two Objects are the same reference (which has its uses).
In your code, you are comparing an Object with a String literal (also an object), which is not the same as comparing the values of both.
Let's look at another example:
String s = "Some string";
if (s == "Some string") {
System.out.println("Equal");
}
In this instance, the if block will probably evaluate to true. Why is this?
The compiler is optimized to use as little extra memory as is reasonable, although what that means depends on the implementation (and possibly runtime environment).
The String literal, "Some string", in the first line will probably be recognized as equivalent to the String literal in the second line, and will use the same place in memory for each. In simple terms, it will create a String object and plug it into both instances of "Some string". This cannot be relied upon, so using String.equals is always a better method of checking equivalence if you're only concerned with the values.
do this instead
if (realName.equals("Maaz"))
equals() should be used on all non-primitive objects, such as String in this case
'==' should only be used when doing primitive comparisons, such as int and long
use
if(realName.equals("Maaz"))
use == with primitive data type like int boolean .... etc
but if you want to compare object in java you should use the equals method
You have to compare objects with realName.equals ("Maaze"), not with ==.
It is best practice to compare Strings using str.equals(str2) and not str == str2. As you observed, the second form doesn't work a lot of the time. By contrast, the first form always works.
The only cases where the == approach will always work are when the strings are being compared are:
string literals or references to string literals, or
strings that have been "interned" by application-level code calling str = str.intern();.
(And no, strings are not interned by default.)
Since it is generally tricky to write programs that guarantee these preconditions for all strings, it is best practice to use equals unless there is a performance-related imperative to intern your strings and use ==.
Before that you decide that interning is a good idea, you need to compare the benefits of interning with the costs. Those costs include the cost of looking up the string in the string pool's hash table and the space and GC overheads of maintaining the string pool. These are non-trivial compared with the typical costs of just using a regular string and comparing using equals.
You can also use
realname.equalsIgnoreCase("Maaz")
This way you can accept Maaz, maaz, maaZ, mAaZ, etc.
== tests shallow equality. It checks if two objects reference the same location in memory.
Intriguing. Although, as others have stated, the correct way is to use the .equals(...) method, I always thought strings were pooled (irrespective of their creation). It seems this is only true of string literals.
final String str1 = new String("Maaz");
final String str2 = new String("Maaz");
System.out.println(str1 == str2); // Prints false
final String str3 = "Laaz";
final String str4 = "Laaz";
System.out.println(str3 == str4); // Prints true
Since you are working on strings, you should use equals to equalsIngnorecase method of String class. "==" will only compare if the both objects points to same memory location, in your case, both object are different and will not be equal as they dont point to same location. On the other hand, equals method of String class perform a comparison on the basis of the value which objects contains. Hence, if you will use equals method, your if condition will be satisfied.
== compares object references or primitive types (int, char, float ...)
equals(), you can override this method to compare how both objects are equal.
for String class, its method equal() will compare the content inside if they are the same or not.
If your examples, both strings do not have the same object references, so they return false, == are not comparing the characters on both Strings.
It seems nobody yet pointed out that the best practice for comparing an object with a constant in Java is calling the equals method of the constant, not the variable object:
if ("Maaz".equals (realName)) {}
This way you don't need to additionally check if the variable realName is null.
if(realName.compareTo("Maaz") == 0) {
// I dont think theres a better way do to do this.
}

Comparing java Strings with == [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java String.equals versus ==
Is it possible to compare Java Strings using == operator?
Why do I often see, that equals() method is used instead?
Is it because when comparing with literal Strings (like "Hello") using == doesn't imply calling equals()?
there is no custom operator overloading in java. [so you cannot overload it to call equals()]
the equals() ensures you check if 2 Objects are identical,while == checks if this is the exact same object. [so no, using == does not invoke equals()].
== checks if the two objects refer to the same instance of an object, whereas equals() checks whether the two objects are actually equivalent even if they're not the same instance.
No, it's not possible, because with == you compare object references and not the content of the string (for which you need to use equals).
In Java, you cannot overload operators. The == operator does identity equality. The equals(...) method, on the other hand can be be overridden to do type-specific comparisons.
Here's a code snippet to demonstrate:
String a = "abcdef";
String b = a;
String c = new String(a);
println(a == b); // true
println(a.equals(b)); // true
println(a == c); // false
println(a.equals(c)); // true
The one complication is with equals(...) you need to care about null, too. So the correct null-safe idiom is:
(a == null ? b == null : a.equals(b))
This is a loop you don't have to jump through in say C#
To expand on #amit's answer, the == operator should only be used on value types (int, double, etc.) A String is a reference type and should therefore be compared with the .equals() method. Using the == operator on a reference type checks for reference equality in java (meaning both object references are pointing to the same memory location.)
String is a class.So if you try to compare a String with its object that holding a string value you can't use == as it is looking for an object.For comparing the contents of the object you have to use equals
Operator == compares for string object references ,whereas String.equals method checks for both object references + object values . Moreover , String.equals method inturn uses == operator inside its implementation.
From what I know the '==' operator is used to check whether or not to objects are identical.
The presumable compared strings might have the same value(nr of chars etc), but be in fact two totally different objects, thus rendering the comparison false.
== returns true if the memory address is equal on both sides, except for primitive types.
equals should be used on everything that isn't a primitive. classes for the main part.
== operator checks the bit pattern of objects rather than the contents of those objects, but equals function compare the contents of objects.
String str1=new String("abc");
String str2=new String("abc");
System.out.println(str1==str2); will return false because str1 and str2 are different object created with "new" .
System.out.println(str1.equals(str2)) will return true because equals() checks for contents of object.
As amit already said, == checks for being the same object whereas equals() checks for the same content (ok, the basic implementation is equal to == but String overrides this).
Note:
"Hello" == "Hello" //most probably would be true
"Hello".equals( "Hello" ) //will be true
String s1, s2; //initialize with something different than a literal, e.g. loading from a file, both should contain the same string
s1 == s2 //most probably will NOT be true
s1.equals( s2) //will be true, if both contain the same string, e.g. "Hello"
Besides that, the same holds true for object wrappers of primitives, e.g.
Long l1 = 1L;
Long l2 = 1L;
l1 == l2 //will most likely be true for small numbers, since those literals map to cached instances
l1.equals(l2) //will be true
new Long(1) == new Long(1) //will NOT be true
new Long(1).equals(new Long(1)) //will be true

Categories