How do you declare x and y so that x+=y gives a compilation error and x=x+y not?
Asked Answered
S

4

54

I ran into this question in an interview and couldn't come up with a solution. I know the vice versa can be done as shown in What does the "+=" operator do in Java?

So the question was like below.

..... x = .....;
..... y = .....;

x += y; //compile error
x = x + y; //works properly
Showbread answered 15/11, 2011 at 14:18 Comment(7)
Curiously, does java allow concatenation with the plus sign? I don't know java, but that seems like a possibilityBevy
@mazzzzz just tested that, doesn't seem to be the solution here. += works fine to concatenate two strings.Clobber
What a useless interview question.Pushover
@Jonathon Completely agree. Such details are fine if you're looking at working on a compiler or JVM implementation, but for a regular programmer this is the kind of thing you just look at the spec for and then forget.Cur
@Jonathon: Like most interview questions... I was interviewed recently in a job, and the interview was a pair-programming test with actual code to write and design to discuss. What a relief from stupid questions!Fisticuffs
@Jonathon - it depends on whether it's being asked to find out whether the interviewee knows the answer - which would be useless. But seeing how someone reacts to a stupid interview question, or seeing how they work out loud on such a problem, maybe with hints, to see whether they have any language-lawyering proficiency at all -- those are worth something.Emie
"Let's see if he goes and asks the question on StackOverflow. If he does, then let's hire him, because that would be the right and appropriate behaviour while working on an actual project!"Euratom
X
54

Try this code

Object x = 1;
String y = "";

x += y; //compile error
x = x + y; //works properly

not entirely sure why this works, but the compiler says

The operator += is undefined for the argument type(s) Object, String

and I assume that for the second line, toString is called on the Object.

EDIT:

It makes sense as the += operator is meaningless on a general Object. In my example I cast an int to an Object, but it only depends on x being of type Object:

Object x = new Object();

It only works if x is Object though, so I actually think it is more that String is a direct subclass of Object. This will fail for x + y:

Foo x = new Foo();

for other types that I have tried.

Xenon answered 15/11, 2011 at 14:37 Comment(4)
Thank you. I tried in Eclipse and it is as you said. But I realized that in NetBeans it just compiles without any errors. So, does it mean that it isn't a general issue of java but depends on compilers?Showbread
x+=y should compile if x is Object and y is String, see bugs.sun.com/bugdatabase/view_bug.do?bug_id=7058838Mousey
Yeah, it is compiler dependent, because the question is how can you cause a compiler error in this manner. The Java language itself might not allow this sort of thing to happen, but compilers might not implement the spec correctly. So it's not really a clear question, and pretty horrific interview questionXenon
It's one JAVA tricky question... Better call it magic question ;-)Gothurd
A
3

It is not possible.

X x = ...;
Y y = ...;

x += y;         //1
//equivalent to
x = (X) (x+y);  //2

x = x+y;        //3

Suppose the type of x+y is Z. #2 requires a casting conversion from Z to X; #3 requires an assignment conversion from Z to X. "casting conversions are more inclusive than assignment conversions"(1). Therefore, as long as #3 is legal, #2 is legal, and #1 is legal.

On the reverse side, it is possible that #1 is legal, but #3 is illegal, for example

    byte x = 0;
    int y  = 1;
    x+=y;     // ok, x=(byte)(x+y), cast int to byte is allowed.
    x = x+y;  // error, assign int to byte

This information is not useful whatsoever; it is a flaw of Java making such surprising differences.

(1) http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5

Ash answered 15/11, 2011 at 16:13 Comment(1)
It is possible, see the answer from @Craigy.Odoric
M
2
int  i = 5;
String s = "a";
System.out.println(i+=s);  //Error
System.out.println(i+s);   // No error

Basically, works for Any object or any non-string primitive and String combination.

I wonder which company it was? :)

Maize answered 16/11, 2011 at 18:27 Comment(1)
This isn't really equivalent because here they are being converted to Strings while they would be converted to an int in the second case with i = i + s which gives a compile error.Xenon
L
1

This thing will not always give you compilation error

If you are doing smoething like this :

class A{
public static void main(String args[]){
    String x = "10";
    String y = "s";
    x += y;
    System.out.println(x);
}
}

It will work fine

even if you do

class A{
public static void main(String args[]){
    int x = 10;
    float y = 11.5F;
    x += y;
    System.out.println(x);
}
}

it will work properly.

But if you take x and y two different type of variables like :

class X{
 }
class A{
public static void main(String args[]){
    X x = new X();
    float y = 11.5F;
    x += y;
    System.out.println(x);
}
}

In such cases it will fail to compile.

*Even you can concatinate any int, float etc with String.

Licit answered 21/11, 2011 at 13:28 Comment(1)
But in this case x + y will also fail and not just x += y.Visceral

© 2022 - 2024 — McMap. All rights reserved.