0

This question may be redundant but I really don't understand why the following code throws: Exception in thread "main" java.lang.NullPointerException

public class NewClass {
    static StringBuilder SB;
    public static void main(String[] args) {
        SB.append("Tesing");
        System.out.println(SB);
    }

}
Jacki
  • 95
  • 2
  • 8
  • 1
    because you don't initialize it... – 3kings May 07 '16 at 17:10
  • What else should it do? You're not initializing it with a `StringBuilder` object, so the variable remains `null`. – Tom May 07 '16 at 17:10
  • should I initialize static variables as well ? I thought this is only for local variables. – Jacki May 07 '16 at 17:11
  • You need to initialize every object type variable/constant (this is every type that isn't a primitive, like `int`, `float` or `boolean` (mind the lowercase first letter)) at some point or it will remain `null`. – Tom May 07 '16 at 17:32

3 Answers3

4
SB = new StringBuilder();

You missed this part!

Alireza Mohamadi
  • 511
  • 5
  • 19
2

You haven't assigned the SB (shouldn't be capitalised btw) variable, so it is still null when you attempt call a method on it.

public class NewClass {
    // Assignment added below
    static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) {
        sb.append("Tesing");
        System.out.println(sb);
    }

}
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
0

You didn't initialize your StringBuilder. Change it to static StringBuilder SB = new StringBuilder(); and it should work.

SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
n247s
  • 1,898
  • 1
  • 12
  • 30