I have the code at the bottom of this post:

Running abc x = new abc() can often take a long time (minutes or longer) and is only ever necessary if flag is true.

If I leave the code as it is below, I get a "x cannot be resolved error" relating to the x.method() line. As you can see, this is only ever run if flag = true (and flag is only ever set to false, within an if statment in this) - i.e. There would never be a time where x.method() is called, without x being initialised first.

I can resolve this by removing the first if statement, and running abc x = new abc(); every time the software is run, but as mentioned this can be very slow, and is not always necessary.

I understand why java doesn't like me doing what I'm trying (it can't see the semantics of what I'm doing, to ensure it gets a value for "x") but I was wondering if there is any way to override this, or a better way of doing what I'm trying to do?

boolean flag = //(input from user)
if(flag)
{
    	abc x = new abc();
}

do
{
	if (flag)
	{
	  	if (x.method ()) 
                .....
    	{
        else
        {
           .....
        }
}
while(...)

Recommended Answers

All 4 Replies

Try moving the declaration of x outside the if test;

abc x = null;
if(flag)
{
x = new abc();
}
...

Try moving the declaration of x outside the if test;

abc x = null;

Excellent! I'll give that a try when I power my lappy up. I never realised you could assign a variable with null (Doh!)

Is that the standard "correct" way to handle this sort of situation (as I've found similar situations with boolean values, or integers as well, and usually just assign some "dummy" (i.e. false or 0) initial value to get overwritten at a later point)? I've always thought my way of using a dummy seemed untidy!

(Goes off to edit code...)

AFAIK this is a perfectly normal thing to do. If you just declare it, it will have the value null anyway, but the compiler will complain that it may be uninitialised. The runtime will throw a null pointer exception if your logic fails to initilaise it to a genuine reference before you try to use it.
Anyway, your problem was not caused by how it's initialised, it's caused by you declaring the variable in the wrong place. Its scope is limited to the block in which it's declared, so it goes out iof scope as soon as you leave the if block.

Well I tried it and it worked a treat!

Anyway, your problem was not caused by how it's initialised, it's caused by you declaring the variable in the wrong place. Its scope is limited to the block in which it's declared, so it goes out iof scope as soon as you leave the if block.

That makes perfect sense now, thanks again :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.