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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
demetrio
Posts: 16
Joined: Mon Sep 30, 2019 11:40 am
Contact:

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

Post 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>

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 49 guests