Java: == in print statement gives different answers [duplicate] - java

This question already has answers here:
String equals and == with String concatenation [duplicate]
(4 answers)
Closed 7 years ago.
String a = "abc";
String b = "abc";
System.out.println("Result .... " + a==b); // false
System.out.println(a==b); // true
1st print statement prints false and 2nd prints true, though ideally it has to be true. Why is it false in 1st print statement ?

System.out.println("Result .... " +a==b); -> the result string will be appended with 'a' and then compares with b so it results false.

Order of operations:
"Result .... " + a==b
is equivalent to
("Result .... " +a) == b
which will be false since the two strings are not the same reference.
The explanation for this is that the + addition operator has a higher precedence than == logical equivalence.
The expression a == b is returning true in your second statement due to interning, in which a and b actually refer to same string object.
Click here for a link to Oracle's table of operator precedence in Java.

Forgot checking equality by == in java. In Java this operation checks equality of object link. Additionally it is applicable for checking equality of simple numbers. You should use .equals method
String a = "abc";
String b = new String(a);
System.out.printLn(a == b);//false
System.out.println(a.equals(b));//true
Learn about operation order in java

It is because in "Result .... " +a==b it first add "Result .... " with a and then == to b. If you write like this "Result .... " +(a==b), then it will be OK.

In the first statement, you're comparing "Result .... " + a with b. In the second one, you're comparing a with b, hence the difference. Change your first statement as follows:
System.out.println("Result .... " + (a==b));
And keep in mind that strings should be compared using the equals() method instead of ==.

System.out.println("Result .... " +a==b);
String Result is appended with 'a' and then compares with b so it provides false. (Result .... a == b) which is false.
Follow this link to understand precedence of operators in java and this.
Operator + has more precedence than == operator.
try adding brackets, you will see the diff. Bracket is evaluated separately.
public static void main(String[] args) {
String a = "abc";
String b = "abc";
System.out.println("Result .... " + (a == b)); // false
System.out.println(a == b); // true}
}
output
Result .... true
true

Related

String not getting printed in the output [duplicate]

This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
String equals and == with String concatenation [duplicate]
(4 answers)
Java string == Vs Equals giving true or false when combined with concatenation [duplicate]
(5 answers)
String concatenation and comparison gives unexpected result in println statement
(5 answers)
The expressions which evaluate to a boolean value can not be concatenated with a String in Java. Why? [duplicate]
(5 answers)
Closed 2 years ago.
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1 == r2);
I tried running this code and i am not getting the String output in the console. The only value getting printed is the r1==r2 result i.e false.
The question here is I am expecting the output to be "Result: false" and why is false just getting printed.
Also i understand that .equals should be used, I just wanted to know why the result is such in the given scenario.
It would be great if some one can point to relevant documentation and help why this is the behaviour.
Indeed the output is "false" because first the concatenation is done so it is "Result: hello" and then it is compared to r2 ("hello") which returns false.
That's why you see "false" in console.
If you want to see "Result: true" you need to use equals instead of == because that's how we compare Strings in java. See below post to understand differences:
How do I compare strings in Java?
If you really want to compare them using "==" you need to add brackets so the comparison will be first before concatenation.
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1 == r2); // output: "false"
System.out.println("Result: " + r1.equals(r2)); // output: "Result: true"
System.out.println("Result: " + (r1 == r2)); // output: "Result: true"
Because it was processed as
("Result: " + r1 ) == r2
which is false. It was processed in this way because + has a higher priority than ==.
What you need to do to get the string as well is
System.out.println("Result: " + (r1 == r2));
which will give you Result: true
To compare strings and print the way you want you should use method equals(). Like this:
String r1 = "hello";
String r2 = "hello";
System.out.println("Result: " + r1.equals(r2));

System.out.println behavior when using String and int together [duplicate]

This question already has answers here:
Java String Concatenation with + operator
(5 answers)
Closed 3 years ago.
Consider the below code snippet -
public class Student {
public static void main(String args[]) {
int a = 3;
int b = 4;
System.out.println(a + b +" ");
System.out.println(a + b +" "+ a+b);
System.out.println(""+ a+b);
}
}
The output for the above snippet is coming as -
7
7 34
34
It is clear from the output that if we use String at first in the print statement then the integers are concatenated. But, if we use integer at first then the values are added and displayed.
Can someone please explain why is this behavior?
I even tried to look at the implementation of println() method in PrintStream class but could not figure out.
Actually it's not println() implementation who's causing that, this is Java way to treat the + operator when dealing with Strings.
In fact the operation is treated from left to right so:
If the string comes before int (or any other type) in the operation String conversion is used and all the rest of the operands will be treated as strings, and it consists only of a String concatenation operation.
If int comes first in the operation it will be treated as int, thus addition operation is used.
That's why a + b +" " gives 7 because Stringis in the end of the operation, and for other expressions a + b +" "+ a+b or ""+ a+b, the variables a and b will be treated as strings if the come after a String in the expression.
For further details you can check String Concatenation Operator + in Java Specs.
It has nothing to do with the implementation of println. The value of the expression passed to println is evaluated before println is executed.
It is evaluated left to right. As long as both operands of + are numeric, addition will be performed. Once at least one of the operands is a String, String concatenation will be performed.
System.out.println(a + b + " ");
// int + int int + String
// addition, concatenation
System.out.println(a + b + " " + a + b);
// int + int int + String Str+Str Str+Str
// addition, concat, concat, concat
System.out.println("" + a + b);
// String+int String+int
// concat, concat
First case:
System.out.println(a + b +" ");
In this order, a + b will first be evaluated as a int sum, then converted to a string when adding the space (the second + here is for string concatenation).
Second case:
System.out.println(a + b +" "+ a+b);
Here the first part will be int sum operation then converted to a string as we add the space (the 2nd + is for string concatenation), the rest will be string concatenation as the left operand is already a string.
Third case:
System.out.println(""+ a+b);
Same as 2nd.
Notes:
In order to change this behavior, just add parenthesis to force the int sum before the string concatenations.

How + internally works on Strings in JAVA

I read from the blogs that internally java use StringBuilder to concat the String when we use + operator. I was just checking it and found some strange outputs.
public class StringDemo {
public static void main(String[] args) {
String a = "Hello World";
String b = "Hello World";
String c = "Hello";
String d = c + " World".intern();
String e = new StringBuilder().append(String.valueOf(c)).append(" World").toString().intern() ;
String f = new StringBuilder(String.valueOf(c)).append(" World").toString().intern();
System.out.println(a == b); // Line 1 Expected output true
System.out.println(a == d); // Line 2 Output is false
System.out.println(a == e); // Line 3 Output is true
System.out.println(a == f); // Line 4 Output is true
}
}
So i am using + operator to concat two strings c & " World" and then use intern() method to move String in the pool for String d.
As per my understanding java use StringBuilder, so now I use StringBuilder to concat the String and use intern() method for Strings e and f.
So if both the equivalent then address of both the String must be same but the output of Line 2 not matching with Line 4 & 5.
Thanks in advance for your valuable feedback.
How + internally works in JAVA
Here is my post on the same, give a read Compiler version : How String concatenation works in java.
And coming to your code inside
System.out.println(a == d);
That should be false only.
As per your understanding you are expecting true. No. Your understanding is wrong. There is a clear difference between
String d = c + " World".intern();
And
String d = (c + " World").intern();
In first line only "World" got interned and the second line "Hello World" got interned
When you do (c + " World").intern(), you'll see the output true.

Boolean Functionality in Java

String s1="hi";
String s2="hi";
boolean b1 = true;
boolean b2 = false;
(1) System.out.println(s1==s2); //true
(2) System.out.println(s1==s2 + s1==s2); //false
(3) System.out.println(s1==s2+ " " + s1==s2); //false
(4) System.out.println(b1+b2); //error : bad operand types
(5) System.out.println(b1 + " " + b2); //true false
(6) System.out.println(true +" "+ s1==s2); //false
What is the difference between (2) & (4)?
What is the difference between (3) & (5)?
Why it gives result false in (3) & (6)?
Except for 4, all of these rely on operator precedence.
And in Java, + has precedence over ==.
Which means 2 actually "reads":
s1 == ((s2 + s1) == s2)
Therefore the right side operand of the first == is a boolean expression which compares two object references to one another (the fact that they are both Strings here is irrelevant) and here they are not the same. Hence the right side operand is boolean false.
But since the left side operand is a String, and since == is not applicable to operands String and boolean, this gives a compile error. JLS, section 15.21:
The equality operators may be used to compare two operands that are convertible (ยง5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.
If this really compiles for you, you are using a buggy Java compiler which autoboxes the right side operand to a Boolean, which it shouldn't. Let me guess: Eclipse's ECJ?
4 is an error since the + operator doesn't accept booleans as operands.
3 reads nearly the same as 2, except that this time it is s2 + " " + s1 which is (attempted to be) compared to s2. It fails to compile for the same reason.
In 5, booleans are autoboxed because of string concatenation.
6 again relies on the operator priority mentioned in 2; this time it is string true + " " + s1 which is (reference) compared with s2 (and that gives false). See 5 for what happens to true.
What is the difference between (2) & (4)?
Your second statement simply becomes System.out.println(hi == hihi ==hi); and the answer is false but your 4th statement is straight forward
What is the difference between (3) & (5)?
This is same as your previous question
Why it gives result false in (3) & (6)?
Your 3rd statement follows the above where as 6th statement convers as System.out.println("true hi" =="hi"); and output is false
P.S : '+' operator comes first in operator precedense
1) What is the difference between (2) & (4) ?
Ans :- == has more precedence over + so 2nd is actually reads as a " s1 == ((s2 + s1) == s2) " where we can't even imagine about ( boolean+boolean )
2) What is the difference between (3) & (5)?
Ans:- 3rd won't even compile and 5th is simple put values b1=true and b2=false and simple String concatenation performed

Java: String immutability and operator == [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have this code which I cannot understand. In the beginning you can see two identical Strings, and when I compare them with use of operator == it says it is true, same as equals() method, but when I create two identical strings during runtime operator == says false. Why is this happening ?
Does it mean that when I hardcode identical strings they are placed in the same position in the memory and both references point to it? I found similar question, but there were no explicit answer.
public class StringTesting {
public static void main(String[] args){
String string1 = "hello"; //\
// } same place in the memory ?
String string2 = "hello"; ///
System.out.println(string1 == string2); //true
System.out.println(string1.equals(string2)); //true
String string3 = "hey";
String string4 = "he";
System.out.println(string3 == string4); //false
System.out.println(string3.equals(string4)); //false
string4 += "y";
System.out.println(string3 == string4); //false ????
System.out.println(string3.equals(string4)); //true
System.out.println(string3 + " " + string4); //hey hey
}
}
The following compound assignment operator:
string4 += "y";
performs String concatenation at runtime. Since the value of string4 is evaluated at runtime only. And String concatenation done at runtime creates a new object.
From JLS Section 3.10.5 (See towards the end of this section):
Strings computed by concatenation at run time are newly created and therefore distinct.
However if you perform concatenation of two string literals, it won't create a different objects. So the following code will return true:
"he" + "y" == "hey";
That JLS section contains code segment for various string concatenation example:
String hello = "Hello",
String lo = "lo";
System.out.print((hello == "Hello") + " "); // true
System.out.print((Other.hello == hello) + " "); // true
System.out.print((other.Other.hello == hello) + " ");// true
System.out.print((hello == ("Hel" + "lo")) + " "); // true
System.out.print((hello == ("Hel" + lo)) + " "); // false
System.out.println(hello == ("Hel" + lo).intern()); // true
string4 += "y"; creates a new object.
String literals however are placed in the same place in memory as an optimization (this is called string interning).
string1, string2, and string3 are all string constants. i.e., they appear as constant pool entries in the .class file. In Java, string constants are interned.
string4 is a new string, created by taking the string constant "he" and then appending "y". Therefore, it's not a string constant, and is not interned.
That is why string3 != string4.

Categories