Sunday, October 25, 2009

no operator overloading in java? tell it to + operator

Lets begin with the wikipedia definition of operator overloading.

In computer programming, operator overloading (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments.



It's generally thought that Java does not support operator overloading which is not true.
Take a look at + operator.



int two = 2;
int six = 6;

int sum = two + six;

System.out.println(sum); // output is 8



Quite expected right? I give two operands (two and six) and + operator adds them together. What if I use strings as operands?


String a = "avenged";
String b = "sevenfold";

String result = a + b;

System.out.println(result); // output: avengedsevenfold


+ operator concatenates two strings. As you can easily see + operator has different implementations depending on the type of operands.
Now, lets take a look at some gotchas of the + operator.
What if I mix different types of operands?


int two = 2;
int six = 6;

String str = "depechemode";

System.out.println(two + six + str);

System.out.println(two + str + six);

System.out.println(str + two + six);


The outputs are quite interesting. Let me explain you how it's processed. From left to right it's inspected if there are any strings as operands. As long as I don't see a string I treat + as addition but when I see one I begin to treat every subsequent operand as strings and I concatenate them.

So I have two + six which are two integers. I add them together which makes 8. Then I see a string and treat 8 as a string and concatenate it with str which in result gives "8depechemode".

Later I have two + str. str is a String so two will be treated like one. As I saw a string I treat all of the rest as strings and concat them. The result is "2depechemode6".

For the last example, we see a string as the first operand. We will begin treating every operand as strings and concat them so I'll have "depechemode26" as result.

I hope that everything is clear for + operator and its overloading capabilities.

2 comments:

  1. Operator overloading is one of the potentially useful parts of .Net (e.g. creating an "ImaginaryNumber" class and being able to treat it the same as other numbers) and it lets you override it yourself. Can you actually do that in Java, or does Java just have two definitions of "+" - one for adding numbers and one for concatenating strings with no way of actually overloading it yourself? (which, IMO, _would_ be overloading support as it supports you overloading it).

    ReplyDelete
  2. The second one IBBoard. There's two behaviors of + for different types and it's all. The operator overloading is quite limited in Java.

    ReplyDelete