0

Let's suppose that we have these variables:

Integer nbr;
String str;
ApiClass someInstance;
Date date;

I want to state that nbr is empty, str is empty, someInstance is empty, date is empty(not assigned to any value), without using myVar = null; because oviously this is a bad habit.

is there any way to test if a java variable is not assigned to anything without assigning to each one nullvalue.

cimecut
  • 78
  • 1
  • 7
  • 3
    An `int` in Java cannot be *empty*. It can have a 0 value, but it will never have a `null` or *empty* value. For this you should use it's boxed class `Integer` – CraigR8806 Mar 21 '17 at 12:43
  • 2
    Have a look at [Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) – Fildor Mar 21 '17 at 12:44
  • @CraigR8806 I know that, I also know what is the default value of String & Date & Integer class, I don't want to test for each variable if it has its default value => empty... I want something more advanced and more type independent.I hope that I didn't get downvoted for this – cimecut Mar 21 '17 at 12:45
  • 2
    In that case: No. There is no such thing. You can use Optional or your own implementation of the Null-Object pattern but variables do not have an implicit "hasBeenSet"-Flag. You could emulate those by adding the according bools to your class and use getters/setters to access them (and set/read the flags accordingly in those). – Fildor Mar 21 '17 at 12:47
  • @Fildor Optional is exactly what I'm looking for, write it as an answer so I can accept it. thanks – cimecut Mar 21 '17 at 12:50
  • a field String[] a; is null before assignment. When you assign new String[0];, the field is not null anymore. It now references an array, which is empty. If you assign new String[1];, the field is also non-null and now references a non-empty array with one element, which is a null. – yeoman Mar 21 '17 at 13:05

2 Answers2

4

Have a look at Optional:

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

EDIT: Please consider reading the references in the comments. You should not just replace all the null-checks with "isPresent"-checks!

Especially Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional! (thanks, @ModusTollens)


Another way around null-Checks is the Null-Object-Pattern. But I feel Optional better suits your requirement.

To make sure all fields have been set before the object is "allowed to be used", you could also go with the builder pattern or a little simpler with an immutable object.


Note: I am deliberately not going into if using nulls is an anti-pattern or not. I am just answering the question.

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • Whether null is an antipattern truly depends on a project's culture - made explicit with annotations it can be ok-ish imo, even though I prefer an explicit optional type over just annotations. At least, the annotations allow tools to check and instrument the correct use. – yeoman Mar 21 '17 at 13:02
  • @yeoman I stated it explicitly because I just wanted to not start a discussion on that. But I agree with you. – Fildor Mar 21 '17 at 13:09
  • @cimecut Be careful using Optional; calling the get() method when a value is not present will still return null. So you should make sure to always use "ifPresent" or "orElse". For the primitive value use OptionalInt. See [this answer](http://stackoverflow.com/a/26328555/1288408), [this anwser](http://stackoverflow.com/a/26328314/1288408) and [this post](https://medium.com/@bgourlie/java-s-optional-the-do-s-and-don-ts-4323151bc073#.aymzkt9d9). I'd recommend the Null-Object-Pattern. – Modus Tollens Mar 21 '17 at 13:17
  • 1
    @ModusTollens The [documentation for Optional.get](http://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#get--) states it can never return null. To get a null, you would need something like `orElse(null)`. – VGR Mar 21 '17 at 13:22
  • Downvoter: Care to explain? I always am ready to improve an answer. – Fildor Mar 21 '17 at 13:25
  • @VGR You are right, I misread. But you would want to make sure to not constantly check for NoSuchElementException either. – Modus Tollens Mar 21 '17 at 13:29
  • @ModusTollens You can also use the "isPresent" method instead of risking the exception. But the point is after all, that the OP does not want to rely on a semantical meaning of a field's value. I.e. "null == not set" or "0 == not set" or "1900-01-01 == not set" and that's exactly what Optional is giving him. – Fildor Mar 21 '17 at 13:34
  • 1
    @Fildor You *can* also use "isPresent", but Oracle itself does not recommend it (quoted from [Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!](http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html): "However, this is not the recommended use of Optional (it's not much of an improvement over nested null checks), and there are more idiomatic alternatives, which we explore below."). That's why I mentioned "ifPresent" and "orElse". – Modus Tollens Mar 21 '17 at 13:37
  • 1
    @Fildor There is a fair amount of documentation, including the explanations in Modus’ links, explaining why Optional is intended for method return types, and should never be used for general “nullable variables.” – VGR Mar 21 '17 at 13:38
  • @ModusTollens Again, I agree with you on that. But if your goal is simply to take away the semantic meaning of `null`, then Optional gives you that. – Fildor Mar 21 '17 at 13:39
  • @VGR I agree with that, too. – Fildor Mar 21 '17 at 13:40
  • @ModusTollens Ah, wait ... Now I get what you are thinking ... I am *not* advocating just replacing `if( x!=null )` with `if( x.isPresent() )`. *Of course* he should make use of `ifPresent`, `orElse` ... – Fildor Mar 21 '17 at 13:47
  • @Fildor sorry, but I couldn't resist throwing this pebble into the calm water :D Btw. it's such a shame that Java's built-in Optional is not a Collection. In fact, I would prefer it even being a List, albeit a rather simple one. Plus, directly itself a Monad. Nothing calls for monadic binding like an Optional... – yeoman Mar 21 '17 at 14:48
2

If you are talking about local variables, this is not possible and a compile error. You cannot access a local variable before it has been assigned a value.

For static or instance fields of a reference type there is no difference between not initializing them and initializing them with null. The initial value is always null, not some distinct "not set" value. Similar for primitive fields, they will be initialized to 0 resp. false, if you don't do it yourself.

diesieben07
  • 1,487
  • 1
  • 14
  • 25