0
code 1:
String s = Character.toString(button[0]);
bt[0].setText(s);//bt[]: JButton array;, button[] = char array
code 2:
String s = Character.toString(button[0]);
bt[0] = new JButton(s);

Suppose, I already initialize bt's by new JButton[num]; code 1 leads to null pointer exception, but code 2 run well. I think bt's already has a pointer value of null. then, i can modify them without restriction. but it isn't. I think code 2 initialize 2 times. but, it hasn't to be.

Rajeev Sreedharan
  • 1,753
  • 4
  • 20
  • 30
garam
  • 1
  • 1
  • When you create an array of reference types (such as `JButton[] bt = new JButton[100]`). You allocate space to store one hundred `JButton` instances, but they are all `null`. Your second example invokes the `JButton` constructor to actually instantiate a `JButton`. – Elliott Frisch Apr 30 '17 at 02:07
  • is there any difference with them?... if we allocate memory for some variables, then aren't we can freely use those position?.. – garam Apr 30 '17 at 02:11
  • *is there any difference with them?* **Yes**. One works. The other doesn't. If you were to fill the array with `JButton`(s) then code 1 would work. – Elliott Frisch Apr 30 '17 at 02:16

1 Answers1

0

The problem is you initialized bt with new JButton[num];. But its content is still null, so bt[0] is null... So you try to run the method setText on a null reference.

Santiago Alzate
  • 397
  • 3
  • 14
  • so that is the problem. But, i'm not dereferencing null. still is it problem?.. – garam Apr 30 '17 at 02:17
  • Yes, it is. When you create the array you're telling Java you will create a bunch of those objects, but none of them are actually created. Thus referencing any if those positions will be a null pointer. You should assign those pointer to real objects, just like you are in the code 2 – Santiago Alzate Apr 30 '17 at 02:56
  • thanks. null pointer can't dereference. – garam Apr 30 '17 at 03:25