This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
(true or false)Suppose String objects b and c contain the same sequence of characters. Then b == c is true.
public static void main(String[] args) {
String a = "abc";
String b = "abc";
System.out.println(a == b);
System.out.println(a.equals(b));
}
The result is true, but the answer to the question is false. I was wondering why.
public static void main(String[] args) {
String a = new String("abc");
String b = new String("abc");
System.out.println(a.equals(b));
System.out.println(a == b);
}
Prints true, then false. So two strings with the same sequence of characters do have to equal each other, but can either == each other or not.
Obviously, a == a under all circumstances, and a is a String containing the same sequence of characters as a.
But in the example above, we're creating two different instances, which just happen to contain the same sequence of characters. Hence a != b.
So what's happening in your example? String interning.
Any string literals are allocated in a special pool by the compiler, and any duplicate literals share the same reference. So even though the literal is defined twice, as far as the compiler's concerned, they're the same instance.
The reason your test results in true is a very weird thing that the JVM likes to do. Because you've defined two String literals, the JVM will just decide to store one of those values, and have both a and b refer to the same string. This is why doing == comparison results in true.
As someone else stated, doing String b = new String("abc"); will force a new String literal to be made, which would be a separate block of memory. Thus == comparison would result in false.
Related
This question already has answers here:
Why does == return true for a String comparison? [duplicate]
(1 answer)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
String str1 = "apple";
String str2 = "apple";
System.out.println(str1 == str2);
Why does the 3rd line return true? I thought you couldn't compare strings like that
I understand that compareTo should be used for strings, why can I do ==
Because '==' is used to compare the reference of the objects
String string1 = new String("apple");
String string2 = new String("apple");
// Is false, they are two different objects
string1 == string2;
// Is true, their value are the same
string1.equals(string2);
// Is true because java uses the same object if you don't create a new one explicitly
"apple" == "apple";
Read this chapter of the article and you will understand.
The behavior you observe has to do with String literals where the JVM usually optimizes the storage by creating new literals if they don't already exist, otherwise providing the existing reference.
This should not be the way that you handle Strings though as they are still objects and you want to compare them by their content and not their memory reference which is what is happening when you use == .
This is why oracle explicitly advices for Strings to be compared using the equals method. There are many cases where a different object reference would be returned for some string that already exists in memory.
Check the following example to see one of those cases
public static void main(String[] args) {
String str1 = "apple";
String str2 = "apple";
System.out.println(str1==str2); //prints true
String str3 = "apple2";
String str4 = str3.replaceFirst("2","");
System.out.println(str1); //prints apple
System.out.println(str4); //prints apple
System.out.println(str1==str4); //prints false
System.out.println(str1.equals(str4)); //prints true
}
This question already has answers here:
Java String literals concatenation
(2 answers)
Closed 6 years ago.
When I perform the == operator comparison, I'm seeing false though I'm expecting the value to be true.
Why does this happen?
public class String1 {
public static void main(String[] args) {
//case 1
String s1="Hello";
String s2=s1+"Java";
String s3="HelloJava";
System.out.println(s2.equals(s3));// true
System.out.println(s2==s3);// expected True but getting output False
System.out.println(s2);
System.out.println(s3);
// case 2
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y);// TRUE as exepected
}
}
In Java the == operator tests reference equality -> same object
.equals() tests for value equality
in both of your cases you have different objects (s1, s2, x, y)
== compares references (i.e. pointer values) of objects.
In case 2 the compiler can shorten "he" + "llo" to "hello" as opposed to the first case where the concatination is performed at runtime.
Also string literals are cached in a pool. Thus two occurences of "hello" will normally refer to the same object. This is possible because strings are immutable.
Strings follow the same rule as every other object. If you want to compare pointers use ==, if you want to compare content use equals.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am getting a value as 9999912499 from the database.
I have separated it in two parts 99999 and 12499 using substring.
Now I want to check whether if the 1st string is equal to 99999 then i do some processing otherwise something other processing.
But controls never gets in to the if loop
Following is a snapshot:
String strPscId = Long.toString(pscID);
String convPscID = strPscId.substring(5, strPscId.length());
String checkNine = strPscId.substring(0,5);
BigDecimal jpaIdObj = jeuParam.getJpaIdObj();
Long mod_id = modele.getModId();
log.info("outstrPscId == " +strPscId);
log.info("outconvPscID == " +convPscID);
log.info("outcheckNine == " +checkNine);
log.info("outjpaIdObj == " +jpaIdObj);
log.info("outmod_id == " +mod_id);
if(checkNine == "99999") { <method-call> }
else { <another - method - call> }
For some reason, the people that make java decided that == shouldn't be used to compare Strings, so you have to use
checkNine.equals("99999");
Look at the following code:
String str1 = "abc";
String str2 = str1;
In the first line, a new string is created and stored in your computer's memory. str1 itself is not that string, but a reference to that string. In the second line, str2 is set to equal str1. str2 is, like str1, only a reference to a place in memory. However, rather than creating an entirely new string, str2 is a reference to the same place in memory that str1 is a reference to. == checks if the references are the same, but .equals() checks if the each character in a string is the same as the corresponding character in the other string.
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
If this code were added to the code above that, both bool1 and bool2 would be true.
String str1 = "abc";
String str2 = new String(str1);
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
In this case bool2 is still true, but bool1 is false. This is because str2 isn't set to equal str1, so it isn't a reference to the same place in memory that str1 is a reference to. Instead, new String(str1) creates an entirely new string that has the value of str1. str1 and str2 are references to two different places in memory. They contain the same value, but are fundamentally different in that they are stored in two different places, and therefore are two different things.
If I replaced new String(str1) with "abc" or str1, bool1 would be true, because without the key word new, the JVM only creates a new string to store in memory if absolutely necessary. new forces the JVM to create an entirely new string, whether or not any place in memory already has the same value as the new string being created.
.equals() is slow but generally more useful than ==, which is far faster but often does not always give the desired result. There are many times when == can be used with the same result as .equals(), but it can be difficult to tell when those times are. Unless you a knowledgeable programmer making something where speed is important, I would suggest that you always use .equals().
You need use equals method, rather than == to compare strings.
Change from
if(checkNine == "99999")
to
if(checkNine.equals("99999"))
The == operator is used to compare the content of two variables. This works as expected when using primitive types (or even wrapper classes because of auto-boxing). However, when we are using == with a reference to an object (e.g., checkNine), the content is the reference to the object but not the value of the object. This is where equals() method is used.
if("99999".equals(checkNine)){
<method-call>
}
else {
<another - method - call>
}
if(checkNine.equals( "99999")) {
<method-call>
}
else {
<another - method - call>
}
if (strPscId.startsWith("99999"))
{
bla bla
}
else
{
sth else than bla bla
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Why does (("+k").split("k"))[0] not equal "+"? I am so confused.
Program:
//The Control Test
String a = "+";
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");
//The Error
a = (("+k").split("k"))[0];
System.out.println(a);
System.out.println((byte) a.charAt(0));
System.out.println(a == "+");
Output:
+
43
true
+
43
false -- Why?
So why in the world does a "+" not equal a "+"?!
You shouldn't compare Strings with ==. You should compare them with .equals() instead.
if(a.equals("+"))
{
// ...
}
This person explained it very well so there is no need for me to explain it again: look at this answer to a similar question.
String literals (strings placed directly in code) are stored in String pool and if some string literal is used few times same object from String pool is used. Since == compares references it will return true for
String a = "+";
System.out.println(a == "+");
Now Strings that are results of methods are separate objects that are not placed in String pool so in
String a = (("+k").split("k"))[0];
String object stored in a is different then "+" from String pool that is why == returns false.
To get rid of this problem you need to use equals method which will compare characters stored in String objects.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What makes reference comparison (==) work for some strings in Java?
I know this has been asked before, but in spite of recommendations to use .equals() instead of the == comparison operator, I found that == works all the time:
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true
Can anyone give me an example of the == operator failing?
This is because you're lucky. The == operator in Java checks for reference equality: it returns true if the pointers are the same. It does not check for contents equality. Identical strings found at compile-time are collapsed into a single String instance, so it works with String literals, but not with strings generated at runtime.
For instance, "Foo" == "Foo" might work, but "Foo" == new String("Foo") won't, because new String("Foo") creates a new String instance, and breaks any possible pointer equality.
More importantly, most Strings you deal with in a real-world program are runtime-generated. User input in text boxes is runtime-generated. Messages received through a socket are runtime-generated. Stuff read from a file is runtime-generated. So it's very important that you use the equals method, and not the == operator, if you want to check for contents equality.
Can anyone give me an example of the == operator failing?
Example 1:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false
Example 2:
Integer a=1000,b=1000;
System.out.println(a == b); // false
When you do this, you are actually creating string literals:
String s1 = "Hello";
String s2 = "Hello";
The compiler finds identical string literals and then optimizes by keeping one instance in the heap and making all the variables in the stack point to it. So doing an == will return true because they point to the same memory address.
When you do this, you are creating string objects:
String s1 = new String("Hello");
String s2 = new String("Hello");
The instantiation will create unique space on the heap for each of these and the stack variables will point to those separate locations. Thus, these will be equal using .equals() because their values are the same, but they will not be equal using == because they are different objects in the heap memory space.
Seasoned Java developers rarely if ever use new String(String), but the problem arises in other cases as well. For example:
String hello = "Hello"
String hell = hello.substring(0, 4);
System.err.println("Hell" == hell); // should print "false".
(Most String instances in a real-world applications are formed either by taking a substring of some other String, or by constructing it from an array of characters. Very few applications will only use String instances created as literals.)