StringBuilder append() in Java

append(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

StringBuilder java.lang.StringBuilder.append(Object obj)

This method takes one argument of type Object (like int, boolean, long, etc). This method appends the string representation of the Object argument. The overall effect is exactly as if the argument were converted to a string, and the characters of that string were then appended to this character sequence.

Parameters: One parameter is required for this method.

obj: an Object.

Returns: a reference to this object.

Approach

Java

public class AppendStringBuilder {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder();

        // append the boolean value
        str.append(false);

        System.out.println("After boolean = " + str);

        // append the char value
        str.append('a');
        System.out.println("After char = " + str);

        //// append the char array
        char arr[] = { 'a''b' };
        str.append(arr);
        System.out.println("After char array = " + str);

        // append the CharSequence value
        CharSequence s = "abc";
        str.append(s);
        System.out.println("After CharSequence = " + str);

        // append the double value
        double d = 16.78;
        str.append(d);
        System.out.println("After double = " + str);

        // append the float value
        float f = 12.34f;
        str.append(f);
        System.out.println("After float = " + str);

        // append the int value
        int i = 5;
        str.append(i);
        System.out.println("After int = " + str);

        // append the long value
        long lng = 1999191;
        str.append(lng);
        System.out.println("After long = " + str);

        // append the String value
        String str1 = "Hello";
        str.append(str1);
        System.out.println("After String = " + str);

        // append the StringBuffer value
        StringBuffer sb = new StringBuffer("World");
        str.append(sb);
        System.out.println("After StringBuffer = " + str);

    }
}


Output:

After boolean = false After char = falsea After char array = falseaab After CharSequence = falseaababc After double = falseaababc16.78 After float = falseaababc16.7812.34 After int = falseaababc16.7812.345 After long = falseaababc16.7812.3451999191 After String = falseaababc16.7812.3451999191Hello After StringBuffer = falseaababc16.7812.3451999191HelloWorld


No comments:

Post a Comment