Page 1 of 1

About Question enthuware.ocpjp.i.v11.2.1408 :

Posted: Wed Dec 11, 2019 12:19 pm
by demetrio
I read "...+ operator is not overloaded for anything except String". Well, why "System.out.println(true + "hello" + 3); " is fine?
System.out.println(true + "hello" + 3); //fine
System.out.println(2 + (2 >= 2) + 3); //exception
System.out.println(2 + true + "hello" + 3); //exception

Jshell console:

jshell> /open C:\WSs\to-learn\deleteLater.java
truehello3
| Error:
| bad operand types for binary operator '+'
| first type: int
| second type: boolean
| System.out.println(2 + (2 >= 2) + 3);
| ^----------^
| Error:
| bad operand types for binary operator '+'
| first type: int
| second type: boolean
| System.out.println(2 + true + "hello" + 3);
| ^------^

jshell>

Re: About Question enthuware.ocpjp.i.v11.2.1408 :

Posted: Wed Dec 11, 2019 9:28 pm
by admin
>why "System.out.println(true + "hello" + 3); " is fine?
Because true and 3 are converted to String and then combined with "hello". This is usually explained in all the books. For example,
Section 5.1.2 of OCP Java 11 Certification Exam Fundamentals by Hanumant Deshmukh clearly says:
"The + operator is overloaded in such a way that if either one of its two operands is a string, it converts the other operand to a string and produces a new string by joining the two. There is no restriction on the type of operands as long as one of them is a string.
The expression 2 + true + "hello" + 3 fails to compile because of the way expressions are evaluated (left to right). There is no string in 2 + true. Please go through a book for the details.