Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Checking variable initialization...  RSS feed

 
Landon Blake
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't believe I've been working for Java as long as I have, and I have never needed to ask this question. Don't laugh at me.

Is there a way to see if a variable has been initialized after it is declared?

If so, what is the syntax to do so?

I ran into this situation in the body of a function. In the function I declare a variable and then attempt to initialize it with a method call. I don't have a guarantee that the method call will sucessfully set the value of the variable. However, I want to use that variable as the return value of the method. I'd like to see if it is intialized before I return it. If has been initialized I can exit the function normally, if not, I'll throw an exception or take other action.

Thanks,

Landon
 
Adam Nace
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, if a variable is declared within the body of a method, then the compiler will guarantee that the method will somewhere call code that will set a value to that variable. If there is any way to complete the method without assigning that some sort of value to that variable, the compiler will exit with an error that says something like "variable may not be initialized".

There are TWO exceptions to that: The first is if the method throws an unchecked (runtime) and uncaught exception. However, then you will not be making it to the return statement ANYWAY.

The other is if you ANYWHERE assign a value of null, either on purpose, or if a method you call returns null. The compiler considers that if you explicitly assign a value of null, that is initializing that variable.

So I guess the answer you are looking for is to do a check for null before returning. If your variable == null at the end of the method, then throw an exception.

Just be careful that null is not a valid value to return from your method, first. Remember, null is an in-band (sort of) value for a variable to have.

If you want null to be a valid value, and you still need to detect whether or not you have properly initialized your variable, there is a trick I have used from time to time that sometimes works.

Say you had the following code:



Now, if anyOldMethod returns null, then you want to return null as well. But if anyOldCondition failed, you want to throw your exception. It makes sense in this case to just use an else block and throw the exception, but lets say things were more compilcated than that.

What I have done before is this:



(Note that the hashCode and equals methods are redundant in the case of Object, but not necessarily for other types).

This should work for you.

- Adam
[ July 26, 2006: Message edited by: Adam Nace ]
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it's setting a variable you can see then it must be a field. If it's an instance variable it will be initialized when the memory for the object is allocated. If it's a class variable then it's initialized when the class is initialized. I suspect, however, that's not what you mean by "initialized" which you didn't really define. If "intialized" means non-null then check for null. If it means something more then you'll have to have some way of indicating the object was successfully "initialized".
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well there are a number of ways to interpret this, but I think "In the function I declare a variable" pretty much tells us the variable is local, not a member. Most likely what's desired here is either catch an exception, or check for null. I think Adam has covered the possibilities.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jim Yingst:
Well there are a number of ways to interpret this, but I think "In the function I declare a variable" pretty much tells us the variable is local, not a member. Most likely what's desired here is either catch an exception, or check for null. I think Adam has covered the possibilities.


Maybe, until you consider the rest of what they said in which the method calls another method to "set the value of the variable". Considering Java lacks pass-by-reference that screams field to me and who knows maybe they're on of those crazy people that look at objects as functions. It's kind of a shot in the dark until they define "initialized" and show us what's going on.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Ken]: Maybe, until you consider the rest of what they said in which the method calls another method to "set the value of the variable".

Hm, I figured that just meant

To me that seems more likely than to assume "In the function I declare a variable" refers to a member variable. Oh well; guess it's just a case where we have different assessments of which parts of a statement have some wiggle room.
[ July 26, 2006: Message edited by: Jim Yingst ]
 
Landon Blake
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I should have been more specific about what I meant by "initialized". I read all of the responses to my question however, which were very good!

What I want to do is check for null in a local variable declared inside a method. Now that I have read your posts, I know I need to do this:



Thanks for all the help guys. I'd never be able to program in Java wihtout you!



[ July 26, 2006: Message edited by: Landon Blake ]
[ July 26, 2006: Message edited by: Landon Blake ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Landon --

Yuk. This wouldn't be necessary if someEvenFunkierMethod() didn't return 0 to indicate failure (if that's indeed what it's doing.) Based on what you've shown here, that's what's going on; although your example shows the variable being tested against "null', and of course that's impossible, as an int can't be null.

In any case, do things the right way: someEvenFunkierMethod() should throw an exception to indicate failure. Then someFunkyIntegerMethod() becomes just



Then this method will return only if someEvenFunkierMethod() succeeded, and otherwise there will be an exception. Make sense?
 
Adam Nace
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Landon,

I won't cover the lack of fail-fast behavior in the someEvenFunkierMethod method, because Ernest already did. By the way, did you write someEvenFunkierMethod, or are you using a method written by somebody else?

Anyway, I just wanted to comment on another part of the code you provided:



(Please don't mind the code reformatting, I'm a bit of a stickler)

Ernest already mentioned that the method cannot return null, because null is not an int. This makes things even uglier, because now you have in-band error signalling (by that, I mean, it's harder to distinguish between an error condition, and a valid return value of 0).

(just to clarify, I suppose returning null for a reference type is TECHNICALLY in-band signalling too, but null is a bit of a special case, so I consider it "quasi-in-band". Exceptions, on the other hand, are clearly out-of-band signals)

If I WAS going to attempt to return an in-band error conditions, I would sooner write the method to return an Integer as opposed to an int, and return null on an error condition. Or course, Even better, as Ernest said, would be to throw an exception.

Anyway, that wasn't what I wanted to talk about. I just wanted to mention the placement of the return code in the else section of the if structure. The else is redundant, because if it passes the if condition, it immediately exits the method. While this is okay in this situtaion, I wanted to warn you about the possible difficulties it can cause later, if you need to add any else-if statements later.

If you simply omit the "else", and put the return at the end of the method, you will ensure that there will always be a retern at the end of the method, regardless of which branch of the if selection takes.

As always, it depends on the situation, but I just wanted to point that out, because in more complicated code situations, this is more difficult to sort out when you need to modify the code slightly.

- And just a minor nit-pick on code formatting: you should try to be consistent with your braces. In the code as you had it formatted, you used braces on the if condition, but not on the else condition. If you use braces on the if condition, you should probably use them on the else condition as well. Furthermore, the code guidelines endorsed by Java Ranch suggest that you should always use braces in if structures. I don't want to start a holy war on braces, but I do suggest consistency, because it makes your code more readable.

- Adam
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!