Sunday 3 February 2013


How concatenation operator work in java:

Java can't do operator overloading, but works okay for String and Integer and someother classes. How is this possible?

Why does this work?


Integer i = 4 ; 
Integer p = 5 ; 
System . out . println ( i * p ); // prints 20

String s = "string 1" "string 2" ;

What actually is execute is:

(new StringBuilder ()). append ( "string 1" ). append ( "string 2" ). toString ()

is not an example of operator overloading. is built into the language as a concatentation operator and an arithmetic-addition operator.

What this means is that a person It works for other classes such as Integer and Double because of autoboxing .

If you take a look at the bytecode of a Java program that performs string concatenation, you'll see that it creates StringBuilder and uses the append() method. The Java compiler sees the operator and realizes that the operands are strings and not primitive types (like int ).

If you look at the bytecode of a program that does integer addition, you will see that it uses the iadd instruction to perform integer addition. This is because the compiler realizesthat the operands to the operation are integers.

As far as doing something like Integer i = 4 , the bytecode will show that you're actually doing Integer i = Integer.valueOf(4) . This is called autoboxing. Later on, when you do something like i p , where both i and p are of type Integer , the generated bytecode will show that you're doing i.intValue() p.intValue() , where the return types of both methods are int (the actual bytecode instruction again, is iadd ).
This is why works Integer even though they are not actual primitive types.

No comments:

Post a Comment