The answer is b. No compile errors and no runtime errors.
Life is short, play hard.
Joined: Jun 05, 2001
To expand on the concept a little more. The expression undergoes two stages of implicit conversion. 1 - Arithmetic promotion: The right hand side of the equation undergoes arithmetic promotion where everyting is promoted to an int. 2 - Assignment promotion: The equals conversion has really no effect on the primative type of the left hand side of the equation. Assigning an int to a char will compile as long as the int value (located on the left hand side) is in the legal range of a character value (located on the right hand side).
Note that what Greg said is true only because you were using literal constants in the right hand side expression. If any or both of the operands were variables, a compile time error would have occurred.
The '+' is an overloaded operator. It can act in 2 different ways depending on the operands. If one of the operands is a String it will concatenate. If there are no Strings and just primitives, including char, it will add. If there is a primitive and any other non String object it will not compile. This is all assuming 2 operands. If we have more operands than we apply the same rules left to right. For example : 3 + 4 + String; the 3 and 4 should be added first then concatenated to the String. Regarding the earlier commnet about whether literals or variables is used is totally false which you can test easily enough.
Originally posted by herb slocomb: > Regarding the earlier commnet about whether literals or > variables is used is totally false which you can test > easily enough. Herb, you're wrong. It does make a difference if you have variables in the expression rather than literal constants. The compiler chokes on this code: <pre> char a = 'a'; char c = a + 1;
C:\java2\Test.java:12: possible loss of precision found : int required: char char c = a + 1; ^ 1 error </pre> Whereas it compiles cleanly with char c = 'a' + 1; BTW, in this case, the overloading of "+" for Strings does not come into play. The operands are converted into ints.
Joined: Feb 12, 2001
Well, yes JUNILU is right in this specific context. I was trying to give general rules but didn't give examples... Here's some examples to illustrate what I was saying... System.out.println(1 + 2 ) ---> 3 Sytem.out.println("1" + 2) ---> 12 System.out.println( 1 + 2 + "3") ---> 33 Using variables works too : int i = 1; char c = 'c'; String s = "Hi" System.out.println(s + c) i = i + c; // addition will occur OK if result variable is int,float, or double, but not char or smaller s = s + c // concatenation As I said, "+" is overloaded and how it operates depends on the context. Sorry for not giving more details...
[This message has been edited by herb slocomb (edited June 22, 2001).]