Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, April 8, 2019

String Conversions and concatenation Example in Java | Interview Questions

String Conversions and concatenation 

String is nothing but a sequence of characters. To concatenation of string can be done using either concat method in String api class or binary '+' operator.

a) concat(String content) method
2) Binary '+' operator.



String Conversions and concatenation



Case a: concat(String content) method


in String api concat method is available.

Systax:

public String concat(String str)

This method accepts String literal which will appended at end of the this String and will return new String.

Example:

package org.java.w3schools.conversions;

/**
 * @author Java-W3schools Blog StringConversion
 */
public class StringConversion {
    /**
     * @param args
     */
    public static void main(String[] args) {
        String one = "Java";
        String two = one.concat("W3schools");

        System.out.println("Two :: " + two);
    }
}

Output:

Two :: JavaW3schools

public String concat(String str): Method internally copy original string content and new content to char array first than creates a new string object. Because String class is Immutable.


Case b: Binary '+' operator.


Binary "+" operator.

See below example and Guess the output.


package org.java.w3schools.conversions;


/**

 * @author Java-W3schools Blog StringConversion

 */

public class StringConversion {

    /**

     * @param args

     */

    public static void main(String[] args) {

        String three = "222";

        String four = 200 + three + 100;


        System.out.println("four : " + four);

    }

}


Output:


four : 200222100


Analysis :


In the following line, first 200 is int, second is string and third is again int.

String four = 200 + three + 100;

Internally during runtime integer primitive type will be converted to new Integer(200) then converted to String by invoking toString method. This for int primitive type.

As well same concept apply to all primitive types to corresponding reference type than it invokes toString() method to convert to String.

If we append null reference than will be converted to String "null".

String four = 200 + three + 100 + null;

Output:

four : 200222100null

This binary '+' operator conversion apply for all primitive types and references.

For primitive types, will be converted to appropriate object creation.

boolean use new Boolean(x)
char use new Character(x)
byte, short, or int use new Integer(x)
long use new Long(x)
float use new Float(x)
doubl use new Double(x)

1 comment:

Please do not add any spam links in the comments section.