58

I need to use something similar to php's isset function. I know php and java are EXTREMELY different but php is my only basis of previous knowledge on something similar to programming. Is there some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...

if(box.isset()) {
  box.removeFromCanvas();
}

So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.

CaldwellYSR
  • 3,056
  • 5
  • 33
  • 50

2 Answers2

91

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    Nice explanation except its completely wrong: won't compile if box have not been initialized like Box box; if(box!=null)//error – iantonuk May 06 '16 at 13:18
  • @bedbad: That's true for *local* variables, but not for fields. Hence the part at the bottom "The difference is also visible for local variables, which can't be read before they've been "definitely assigned"" and the example of it not compiling. Will make it clearer that the first part is about fields. – Jon Skeet May 06 '16 at 13:25
  • you just answered yourself. The question asks "how to check if **variable**" was initialized. variables not fields and fields are not variables. fields are initialized with the whole object, so there can be no question how to check if **field** is initialized. You just confused a bunch of people. And by the way it true for **any** variable not just local. – iantonuk May 06 '16 at 14:14
  • 5
    @bedbad: I see no sign that I confused anyone, and http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.3 shows that fields are variables. The OP seems to have been happy enough with my answer... – Jon Skeet May 06 '16 at 14:16
  • @bedbad: From the question: "I just wondered if there was some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not." So this question was about fields, not local variables. I agree that not all variables are fields, but that's not the same as saying fields are not variables. And no, a member field can't be a function. All fields are variables, as per the piece of the JLS I linked to. If you believe there's such a thing as a field which isn't a variable, please link to the relevant piece of the JLS. – Jon Skeet May 06 '16 at 14:48
  • @bedbad: Have you got a concrete example of a non-variable field yet, with a JLS reference? I'm interested - I suspect you *may* be getting confused between members and fields, but maybe there's something I'm unaware of. – Jon Skeet May 07 '16 at 10:06
  • being field - foundamental property of a class member. In strict definition its everything listed inside class{member) except methods(and constructors). I already gave you a very good example - enum. A class is also a good example. Inner generic class, will be allocated with a nesting class. In no good sense you can call a class(aka "type") a variable. This should affirmatively end this conversation: http://docs.oracle.com/javase/tutorial/reflect/member/field.html I will write a clear answer on what is going on in "compilation" & in jvm with variables and fileds, when have time.ty – iantonuk May 09 '16 at 01:33
  • 4
    @bedbad: No, you're just plain wrong I'm afraid. A field *is* a class member, but it's only *one* kind of class member. From http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.6: "A class body may contain declarations of members of the class, that is, fields (§8.3), methods (§8.4), classes (§8.5), and interfaces (§8.5)." The doc you referred to isn't saying what you think it's saying - which is easy to show, because if you call `Class.getDeclaredFields` with the reflection API (which that doc is describing) you won't get values for methods or nested types. – Jon Skeet May 09 '16 at 05:13
  • 4
    He clearly asks about an *instance variable*. "Instance" denotes the scope: aka a non-static field. Contrast this to a local variable (variable in method) or a class variable (static field). You removed some comments so we're missing context but as far as I read it the question was answered and had extra information added to it – Jeroen Vannevel May 09 '16 at 07:57
  • this answer is wrong. @iantonuk is right. The reason why this works for fields is because fields are initialized to null. – thang Apr 27 '19 at 00:31
  • 2
    @thang: Which precise part do you think is wrong? Fields *are* variables, as I've demonstrated in the JLS. All fields *are* implicitly initialized to the default value for the type. Local variables are *not* implicitly initialized. It's very hard to comment in a more concrete way when there's been a lot of discussion and your comment is so broad. – Jon Skeet Apr 27 '19 at 06:54
  • I googled for "How to check to see if a variable has been initialized in Java" and this came up. Your answer doesn't answer. Fields are vars but vars are not fields. A question about fields can be answered with answers pertaining to vars, but not the other way around. No need to bring up null etc. @iantonuk is right. The right answer is there is no way to do it in java. In order to get un/assigned info, the var has to carry meta data along with it at run time. This is not the case for Java, so it has to do the checking at compile time. PHP is dynamically typed, so possible – thang May 03 '19 at 00:25
  • 1
    @thang: The question was specifically about fields - it asks about *instance* variables, which are fields. And my answer *starts* saying there's no way to tell this, and talks about `null` to effectively counter the incorrect idea that checking for null *is* checking whether or not the variable has been initialized. Nothing you've said points to any incorrect statement in my answer or comments, as far as I can see. – Jon Skeet May 03 '19 at 00:29
  • @thang: Also note that while you're saying iantonuk was right, they were claiming that fields *aren't* variables, whereas you agree with me that fields *are* variables... – Jon Skeet May 03 '19 at 00:36
  • The question's not about fields. The title is "Java check to see if a variable has been initialized". I don't see field mentioned anywhere. Also, the original poster originally refer to PHP's isset, which is actually a general variable check. "I just wondered if there was some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. " That's my gripe. I am hoping to convince you to somehow change this answer to not waste another passerby's time. The answer is misleading and doesn't answer the question. – thang May 03 '19 at 03:30
  • you've invented a way to have an XY answer :) ask question Y, answer question X. This is as far as I will say about this. This question shows up in Google as the first item when asked about variables due to the text and title. If you want to do a service to the world, change it in a way that is relevant or delete it. Otherwise, you're like a telemarketer. – thang May 03 '19 at 03:33
  • 1
    @thang: I answered *the question written*, not your Google search. To quote the question directly: "I just wondered if there was some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not." How can you claim the question is *not* about fields? (And you *still* haven't told me where you think I've said anything inaccurate.) I'm happy that everything my question states is correct, and helps people who are interested in fields *and* those who are interested in local variables. – Jon Skeet May 03 '19 at 06:13
20

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

Timo Giese
  • 55
  • 9
Protongun
  • 3,230
  • 1
  • 15
  • 13
  • 3
    What's the default value for `MyClass object`? Are objects references (default value: `null`)? – Matt Jun 11 '21 at 00:39