Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Thu Jul 12, 2012 4:51 pm
by ETS User
Hello,

Does anyone know why
String s = 63 + new Integer(10); will lead to a compile error?

The explanation is: Since none of '+' the operands is a String, the + operator will not generate a String. However, due to auto-unboxing, it will generate an int value of 73.

Thank you!

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Fri Jul 13, 2012 10:05 am
by admin
Since the variable s is of type String, you need a String on the right hand side of the assignment. Now, on the right hand side, you have 63 + new Integer(10) , which does not generate a String. It is an int, which cannot be assigned to s. So the compiler will complain.

For + to generate a String, at least one of the operands must be a String. So, had it been something like 63+"10", the resulting value would have been "6310", a String, which can be assigned to s.

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Fri Jul 13, 2012 12:49 pm
by Guest
Thank you

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Mon Jun 08, 2015 3:37 pm
by ElizabethCM
Hi Paul,

I have a question regarding the expression:
System.out.println('b'+new Integer(63));
Normally, this will evaluate to 98 + 63 = 161

Why is this accepted as none of the components are strings?
Is it because it is inside of a "println" statement?

Thanks

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Mon Jun 08, 2015 9:00 pm
by admin
No, it is accepted because both the sides of the operator are numeric, which makes is the basic usecase for the + operator i.e. addition. Remember that char is also a numeric data type. Char is rot a String.
Also, remember that Integer will be unboxed into an int.

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Tue Jun 09, 2015 2:55 pm
by ElizabethCM
Hi,

Yes, you are right, the Integer is unboxed and then it is just like using an addition between two numeric values.
Thanks

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Fri Jan 19, 2018 6:08 am
by Arold Aroldson
I don't understand why 'b' transfers to 98. Can you provide me with any link where i could read about this topic?

Re: About Question enthuware.ocajp.i.v7.2.1164 :

Posted: Fri Jan 19, 2018 12:14 pm
by admin
98 is the unicode (and ascii) value of character b. If you use a char as an int, you will get the unicode value of that char. You may read more about it here: https://coderanch.com/t/404152/java/con ... er-integer