Search code examples
javastringbuffer

getChars() using StringBuffer


I am new to Java. I executed the below program successfully but I don't understand the output. This is the program.

public class StringBufferCharAt {
    public static void main(String[] args)
    {
        StringBuffer sb = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
        System.out.println("Length of sb : " + sb.length());

        int start = 0;
        int end   = 10;

        char arr[] = new char[end - start];
        sb.getChars(start, end, arr, 0);
        System.out.println("After altering : "+ arr.toString());

    }
}

After executing this program: I got the following output:

Length of sb : 26
After altering : [C@21a722ef

My Questions:

  1. Instead of printing 10 characters in the output, why 11 characters.
  2. Instead of printing the original characters "abcdefghij" which are inside sb, why did I get some other characters.

Solution

  • The arr.toString() in your last sentence is giving you a String value of your Object (doc here), here's an array. What you were probably trying to achieve was something like Arrays.toString(arr) which will print the content of your array (doc).