Wednesday, 1 February 2017

STRING CONCATENATION IN JAVA

Concatenate means combining multiple strings and form it as a single string. There are basically two ways to concatenate strings in java. They are –

1. + operator – It would act as an arithmetic operator only if both the operands supplied are arithmetic values. But the same operator would act as a concatenation operator, if atleast one operand supplied to the ‘+’ is a string class object.

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1="10";
                   String s2="20";
                   String s3="hello";
                   System.out.println(s1+s2);
                   System.out.println(10+20);
                   System.out.println(s1+s3);
                   System.out.println("hello"+20);            
          }
}

Output –
1020
30
10hello
hello20


2. concat() method – This method is used to concat the given string on the RHS.

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1="10";
                   String s2="20";
                   System.out.println(s1.concat(s2));                           
          }
}

Output –

1020

No comments:

Post a Comment