Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Tue Dec 25, 2012 1:37 am
by yabmob
I am having a hard time understanding this.

System.out.println( 'a' + 63 ) ; //This works and prints 160

System.out.println( 'a' + 63 + " ") ; //This works and prints 160

String s = 'a' + 63 + "" ; //This works and prints 160

String s = 'a' + 63 ; //This fails to compile !

Re: About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Tue Dec 25, 2012 7:01 am
by admin
A char is an integral value just like an int, short, and byte. So 'a' + 63 means you are adding the integral value of 'a', which is 93 to 67. Hence, you get 160.

Same thing for 'a'+67+" " except the last part where you are basically doing 160+"". Now, + operator is overloaded such a way that if any of its operands is a String, it converts the other non-string operand to a string and joins the two. So 160 is converted to "160" and joined with " ", which prints 160.

Since "160" is a string, you can assign it to a String, so String s = 'a' + 63 + ""; works fine.

String s = 'a' + 63; doesn't work because none of the operands of + is a String here. So the result of this + operation is not a String but an int 160. You can't assign an int to a String.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Tue Dec 25, 2012 12:16 pm
by yabmob
Wow, I did not expect a reply today.

Its simple enough. An int cannot be assigned to a String.

Thanks !

Re: About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Mon Oct 06, 2014 8:57 am
by piotrkmiotczyk
Hmmmm.. What do you mean by: + operator is overloaded?

I've read the docs on promotions, assign conversions, String conversions (by concatenation) this is neither of those cases. Is there some list of overloads (similar to a method) for operators? Can you provide a source please?

Also how does this relate to operator associativity, if at all?

Re: About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Mon Oct 06, 2014 11:16 am
by admin
Java doesn't support operator overloading except for +, which is overloaded for String concatenation. If one of the operands of + is a String the other is automatically converted to a String and then both are concatenated into another String. You may read more about it here: http://docs.oracle.com/javase/specs/jls ... ls-15.18.1

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Sat Jan 13, 2024 11:55 am
by Badem48
Hi,

I want to point out that in the last option Integer constructor is used however it has been depreciated since Java 9 and marked for removal.

Re: About Question com.enthuware.ets.scjp.v6.2.417 :

Posted: Sun Jan 14, 2024 12:50 am
by admin
You right and in the latest version of the question bank for OCP 17 (v. 1.48) all references to constructors have been santized (i.e. either removed or an explanation has been provided).