-3

I'm currently working on making a basic TextEditor in Java FX but I'm having a bit of difficulty. I am trying to incorporate the MVC development style and using any object of type Document in the model when working with the editor although when I try to save the area of the contents I get a NullPointException when I try set any variables in the when the Document is initialised to null. It works fine with it set to a new document will null parameters though...

Any information on the reasoning for this would be really appreciated!

Edit:

Sorry for the ambiguity, I was meaning in terms of initialising an object that I am trying to then set variables for. I had it initialised to simply null:

Document workingDocument = null 

When I changed this to:

Document workingDocument = new Document(null, null);

I understand what creating a new Documents does in terms of memory but not what simply initialising it to null does...

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Can you show us some code? – Christoffer May 31 '16 at 21:36
  • 1
    If the object is null and you're trying to call a method on it, what would you expect to happen ? – Nir Alfasi May 31 '16 at 21:41
  • NullPointerException is thrown when you are trying to get something from null. For instance `null.someField`, `null.getSomething()`, or `null[1]`. It happens because `null` doesn't have any fields, methods nor it is an array. You don't need to do these operations directly on `null`. Same thing will happen if you will in that way reference which is holding null like `String s = null; s.length();`. – Pshemo May 31 '16 at 21:54

2 Answers2

0

Not 100% sure what you mean, but if there is no object - you can't set any variables in it - since it doesn't exist. So if it is initialized to null it is null - i.e nothing.

If you have instantiated an object, you can set the member variables of it - even if the variables in it is null - since the object actually exists.

Null is null. So even if a variable is of a certain type, it will point to null if it's instantiated to it.

Shoe myShoe; // This is a shoe typ variable
myShoe = new Shoe(); // Now it's pointing to a new shoe object
myShoe = null; // Now it's pointing to null, meaning there is no shoe object there anymore.
Christoffer
  • 7,470
  • 9
  • 39
  • 55
0

You cannot operate on null values. The only operation that are available for nulls (of the top of my head) are

  1. Nullchecks - if(document==null)
  2. Assignements - document=null

NullPointerException will be thrown for example if you will try to invoke some sort of method on null value.

Document doc=new Document();
doc.toString(); // works just fine
doc=null;
doc.toString(); throws NPE. 

You should familiarize yourself with the concept of OOP , as null values are widely used here. You can check the related topic here What is a NullPointerException, and how do I fix it?

Community
  • 1
  • 1
Antoniossss
  • 31,590
  • 6
  • 57
  • 99