0

Please refer to the following code:

        Scanner scan = new Scanner(System.in);
    int T = Integer.parseInt(scan.nextLine());
    StringBuilder []str = new StringBuilder[T];
    String temp = new String();
    for (int i=0; i < T; i++){
        temp = scan.nextLine();
        str[i].append(temp);
    }
    System.out.println(str);

The above code throws a Null Pointer Exception on the line:

str[i].append(temp);

I want to do it with StringBuilder.

  • 3
    Creating an array of any objects creates one object. The empty array. – Kayaman Jun 07 '16 at 13:56
  • Please, elaborate. I am not able to get you. – Ishan Saini Jun 07 '16 at 13:58
  • You're creating an array of uninitialized StringBuilder objects. These are all null. – venture Jun 07 '16 at 13:58
  • For more details about your problem read http://stackoverflow.com/a/23852556 (it is one of answers from duplicate question). Also what are you trying your code to do? For now it looks like you want to create array of StringBuilders and put one word in each StringBuilder which doesn't really make sense since that class is used to concatenate many string, not just one. – Pshemo Jun 07 '16 at 13:59
  • @IshanSaini `new StringBuilder[T]` creates an array object with the default values for each element, which, since these are not primitives, are `null`. Invoking something on a `null` reference -> `NPE`. – SomeJavaGuy Jun 07 '16 at 13:59
  • Thank You @KevinEsche for your explaination. I was able to find a solution. Here, is the code: `String temp ; StringBuilder []str = new StringBuilder[T]; for (int i=0; i < T; i++){ temp = scan.nextLine(); str[i] = new StringBuilder(temp); }` – Ishan Saini Jun 08 '16 at 06:03
  • Thank You @Pshemo I am able to find the solution to my problem. Also, I can see you very passionate about this community. Kudos! – Ishan Saini Jun 08 '16 at 06:07

0 Answers0