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
}
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:
Getting strange output when printing result of a string comparison
(3 answers)
Closed 3 years ago.
Below code return boolean false value. Any explanation for this ?
String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2);
Actual Result : false
Use equals to compare string, it will return true for this case.
The == operator compares that the Strings are exactly the same Object.
This might theoretically happen in case of internalized strings, but you cannot rely on this. For your case, comparing String values, use str.equals(str2).
str and str2 are both assigned the same String instance, since String literals are automatically stored in the String pool. Therefore str == str2 is true.
However, you are printing the expression "==" + str == str2. That expression is evaluated from left to right, so first "==" + str is evaluated, and results with the String "==Bee". Then the == operator is applied to "==Bee" and "Bee", which returns false.
If you change the statement to:
System.out.println("==" + (str == str2));
you'll get true, since now the comparison will take place prior to the String concatenation.
The behavior of String literals is very confusing in the code below.
I can understand line 1, line 2, and line 3 are true, but why is line 4 false?
When I print the hashcode of both they are the same.
class Hello
{
public static void main(String[] args)
{
String hello = "Hello", lo = "lo";
System.out.print((Other1.hello == hello) + " "); //line 1
System.out.print((Other1.hello == "Hello") + " "); //line 2
System.out.print((hello == ("Hel"+"lo")) + " "); //line 3
System.out.print((hello == ("Hel"+lo)) + " "); //line 4
System.out.println(hello == ("Hel"+lo).intern()); //line 5
System.out.println(("Hel"+lo).hashCode()); //hashcode is 69609650 (machine depedent)
System.out.println("Hello".hashCode()); //hashcode is same WHY ??.
}
}
class Other1 { static String hello = "Hello"; }
I know that == checks for reference equality and check in the pool for literals. I know equals() is the right way. I want to understand the concept.
I already checked this question, but it doesn't explain clearly.
I would appreciate a complete explanation.
Every compile-time constant expression that is of type String will be put into the String pool.
Essentially that means: if the compiler can (easily) "calculate" the value of the String without running the program, then it will be put into the pool (the rules are slightly more complicated than that and have a few corner cases, see the link above for all the details).
That's true for all the Strings in lines 1-3.
"Hel"+lo is not a compile-time constant expression, because lo is a non-constant variable.
The hash codes are the same, because the hashCode of a String depends only on its content. That's required by the contract of equals() and hashCode().
Strings computed by concatenation at runtime are newly created and therefore distinct
here is a link to read: http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5
String object can be created in the following ways:
String str = new String("abcd"); // Using the new operator
// str is assigned with "abcd" value at compile time.
String str="abcd"; // Using string literal
// str is assigned with "abcd" value at compile time.
String str="ab" + "cd"; // Using string constant expression.
// str is assigned with "abcd" value at compile time.
String str1 = "cd";
String str = "ab"+str1; // Using string expression.
// str is assigned with "abcd" value at run time only.
and Hashcode will be calculated only at runtime based on the contents of the String objects.
It's because the comipler in this instance is not smart enough to work out that it can burn in the same string literal.
Hashcode needs to always return the same value for strings that are equivelent (calling .equals on it returns true) so will return the same result.
Its because following code
("Hel"+lo)) + " "
is translated internally to
new StringBuilder("Helo").append(new String(lo)).append(new String(" ")).toString()
So you can see that entirely a new String instance is created with help of different String instances. That is why you get false as they point to different memory locations in heap
The hashCode doesn't have anything to do with an objects reference (The == check is a reference comparator). Its possible to have 2 objects where the hashCode returns the same value, the equals operator returns true, but == returns false. This is when they are 2 different objects, but with the same value.
I believe the reason line 4 is returning false is that it is a value computed at runtime, and thus is a different string instance, with a different reference.
String literals are saved in a special memory, if they are exactly the same, they are pointed to the same map of memory. If you don't create a literal String, a new object will be created so it won't point to that memory so the reference won't be the same.
The intern() method tells the virtual machine to put it into that shared, string literals map of memory so next time you do that literal, it'll search there and point it.
As you already know ... this is just because of reference ...when string comes from the pool it will have same refrence ...but when u do manuplations a new string with new refrence is generated ...
You can check this link for pooling concept
The difference between line number 3 and 4 are as follows.
•Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
•Strings computed by concatenation at run time are newly created and therefore distinct.
The above reference is taken from java spec. Please let me know if you need more clarification.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5
System.identityHashCode() would be returned by the default method hashCode(), this is typically implemented by converting the internal address of the object into an integer.
Finally I know the answer !
Read Java SE 8 specification section 15.21.3 Reference Equality Operators == and != (http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.21.3)
While == may be used to compare references of type String, such an
equality test determines whether or not the two operands refer to the
same String object.
The result is false if the operands are distinct
String objects, even if they contain the same sequence of characters(§3.10.5). The contents of two strings s and t can be tested for
equality by the method invocation s.equals(t).
So the following code :
class Test {
public static void main(String[] args) {
String hello = "Hello";
String lo = "lo";
System.out.println((hello == ("Hel"+lo))); // line 3
}
}
The expression ("Hel"+lo) in line 3, return the new Strings that computed by concatenation at run time.
*Strings computed by concatenation at run time are newly created and therefore distinct.
(http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#d5e1634)
So the result of this code:
class Test {
public static void main(String[] args) {
String hello = "Hello";
String lo = "lo";
System.out.println((hello == ("Hel"+lo))); // line 3
}
}
would result:
false
Because,
the "Hello" object in this expression:
String hello = "Hello";
and ("Hel"+lo) object in this expression:
System.out.print((hello == ("Hel"+lo)) + " ");
is different, although :
*they both contain the same sequence character, which is "Hello".
*they both have the same hashCode.
*hello.equals(("Hel"+lo)) will return true.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have a situation of appending String. And i'm confused ..
public static void foo() {
String s = "str4";
String s1 = "str" + s.length();
System.out.println("(s==s1) = " + (s1 == s));
}
And
public static void bar() {
String s = "str4";
String s1 = "str" + "4";
System.out.println("(s==s1) = " + (s1 == s));
}
In 1st case it's returning 'false' but in 2nd case 'true'
As i understand in both cases 'str4' object is being created on the heap. So it should return true in both cases. But it's not.
Kindly someone help me out why it's so. ? Thanks.!
Use
s1.equals(s)
to compare strings, otherwise you compare references.
In second case it returns true because String s1 = "str" + "4"; would be optimized to String s1 = "str4"; and s and s1 would refer to the same String.
The == operator in Java only returns true if both references refer to the same object. If you are trying to compare two Strings for equivalent content, you must use the equals() method.
you need to use .equals() for this
.equals() // if you dont want to ignore case
.equalsIgnoreCase() // if you want to ignore case
== compare the references.
In the second case both strings are equal .So references are also equal.
String s = "str4";
String s1 = "str" + "4"; .//finally str4
Here s1 ans s2 contents are equal.So they have same reference.
In my own understanding :
"str" => String
"4" => String
However,
s.length() => int
With ==, memory locations are compared.
Using the first example, Java creates another String which is in another memory location other than the location of 's' because you are trying to do String + int = String.
The second example returns true because it is just the same memory location as your 's' only that the value is changed. String + String = Concatenated String
Since you are trying to compare if the two strings have the same characters inside but not necessarily the same location, then s.equals(s1) is the best solution.
However, should you want to test if both variables are pointing to the same object then == must be used because of its shallow comparison.
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.)