What will be output and explanation? [duplicate] - java

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.

Related

Why does setting the value of two string the same and using == to compare them return true? [duplicate]

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
}

getting == operator comparison false while comparing reference concatenated with literal with other reference [duplicate]

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.

Checking a number in String Variable [duplicate]

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
}

Java String Split Method Error? [duplicate]

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.

Confused in appending Strings in Java [duplicate]

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.

Categories

Resources