Monday, 1 October 2012

What is Concatenation in JAVA?

Concatenation describes the operation of joining two strings together. In Java, the operator "+" normally acts as an arithmetic operator unless one of its operands is a String. If necessary it converts the other operand to a String before joining the second operand to the end of the first operand.

when a + is used for concatenation below are the steps which are involved:
  1. A StringBuffer object is created
  2. string1 is copied to the newly created StringBuffer object
  3. The “*” is appended to the StringBuffer (concatenation)
  4. The result is converted to back to a String object.
  5. The string1 reference is made to point at that new String.
  6. The old String that string1 previously referenced is then made null.
Example:
To join the two Strings "pan" and "handle":
 System.out.println("pan" + "handle"); 
If one of the operands is not a String it will be converted:
 int age = 12; 
System.out.println("My age is " + age);
There is also a method called concat defined in the String class that performs the same operation:
 System.out.println("pan".concat("handle")); 

No comments:

Post a Comment