AppletTalk.com Forum Index AppletTalk.com
Java discussions newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Test to see of a variable has been used/initialised
Goto page 1, 2, 3  Next
 
Post new topic   Reply to topic    AppletTalk.com Forum Index -> Java Language Programming
View previous topic :: View next topic  
Author Message
Anon
Guest





PostPosted: Mon Apr 26, 2004 7:11 pm    Post subject: Test to see of a variable has been used/initialised Reply with quote



Hi,

How do I find out if a variable has been used or initialised yet?

Thanks,

Anon.


Back to top
Eric Sosman
Guest





PostPosted: Mon Apr 26, 2004 8:16 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote



Anon wrote:
Quote:

Hi,

How do I find out if a variable has been used or initialised yet?

If it's a local variable in a method, the compiler will
complain if it thinks the variable might be used before
being initialized. The compiler will sometimes issue bogus
complaints, but if it issues no complaint you can be sure
the variable is initialized before use.

If it's an argument of a method or constructor, it is
initialized by the method's caller or by the `new' expression.

If it's a class variable it is always initialized, either
when an object is constructed (for instance variables) or when
the class is loaded (for static variables). However, you and
Java may disagree about what "initialization" really means:
the variable will acquire a legitimate value of some kind due
to Java's own actions, but that's not a guarantee that your own
application-specific "initialization" has been performed:

/** A mutable integer. */
class Goof {
int number; /* Java initializes this to zero */

/** Constructs a new Goof with the given value. */
Goof(int number) {
number = number; // intended: `this.number = ...'
/* `this.number' is "uninitialized" in the sense
* your application intended, even though it is
* "initialized" from Java's point of view. */
}
}

The best way to deal with errors of this sort is, of course,
not to commit them Wink If perfection is not an option, you may
sometimes be able to "Java-initialize" a variable with a value
that makes no sense to your application, so your application can
later recognized that value as meaning "somebody goofed." The
value `null' can often be used this way for reference variables;
the method is more difficult to apply to non-reference types.

--
[email]Eric.Sosman (AT) sun (DOT) com[/email]

Back to top
John C. Bollinger
Guest





PostPosted: Mon Apr 26, 2004 8:27 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote



Anon wrote:

Quote:
How do I find out if a variable has been used or initialised yet?

To check for user initialization, you can compare the value against the
default value or instance initialization value. Of course that fails if
the user initializes the variable to its default value, or later sets it
to that value. If you *must* reliably determine this then you can make
sure that initialization can only be performed via an instance method,
and then let the object track whether or not that method has been invoked.

As for usage, you'll have to define more precisely what you mean to get
any answer. It will in any case involve protecting access to the
variable by a method, as there is *no* way in standard Java to determine
whether or if a field has been read directly.

NOTE WELL, however: if your design depends on being able to determine
this sort of thing, then probably it is severely broken. In general,
instead of writing your classes in such a way as to have a need to check
such things, you should write them so that they only allow permitted
operations. And, no, that is in general not a circular requirement.


John Bollinger
[email]jobollin (AT) indiana (DOT) edu[/email]


Back to top
Roedy Green
Guest





PostPosted: Mon Apr 26, 2004 8:37 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

On Mon, 26 Apr 2004 20:11:30 +0100, "Anon" <voidrubbish (AT) hotmail (DOT) com>
wrote or quoted :

Quote:
How do I find out if a variable has been used or initialised yet?

compile the code. Java won't let you write code with uninitialised
variables.


See http://mindprod.com/jgloss/initialisation.html

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.

Back to top
Anon
Guest





PostPosted: Mon Apr 26, 2004 9:46 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

Hi all,

Thanks for the tips.

The program I'm developing needs to decide whether or not to do something
(buy/sell an equity) based on order types (limit/market/stop). And I was
initially planning to test for the presence of the different order types
(e.g. stop orders are optional and may not always be present) by testing for
initialisation of the different parameters. However, judging by your
responses I believe it may be wiser to use boolean variables to flag weather
or not the variables have already been set or not.

Thanks again!

Anon.

"Roedy Green" <see (AT) mindprod (DOT) com.invalid> wrote

Quote:
On Mon, 26 Apr 2004 20:11:30 +0100, "Anon" wrote or quoted :

How do I find out if a variable has been used or initialised yet?

compile the code. Java won't let you write code with uninitialised
variables.


See http://mindprod.com/jgloss/initialisation.html

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.



Back to top
steve
Guest





PostPosted: Mon Apr 26, 2004 9:55 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

On Tue, 27 Apr 2004 04:37:02 +0800, Roedy Green wrote
(in article <9msq80dc5cv1287uv6rpj9cl464ntatoh9 (AT) 4ax (DOT) com>):

Quote:
On Mon, 26 Apr 2004 20:11:30 +0100, "Anon" wrote or quoted :

How do I find out if a variable has been used or initialised yet?

compile the code. Java won't let you write code with uninitialised
variables.


See http://mindprod.com/jgloss/initialisation.html

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.


So you are saying a null variable is initialised ?


Back to top
Tony Morris
Guest





PostPosted: Mon Apr 26, 2004 10:37 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

Quote:
The compiler will sometimes issue bogus complaints,

Care to back this up with a bug report ?
Sounds like baloney to me.

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform



Back to top
Virgil Green
Guest





PostPosted: Mon Apr 26, 2004 10:51 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

"steve" <me (AT) me (DOT) com> wrote

Quote:
On Tue, 27 Apr 2004 04:37:02 +0800, Roedy Green wrote
(in article <9msq80dc5cv1287uv6rpj9cl464ntatoh9 (AT) 4ax (DOT) com>):

On Mon, 26 Apr 2004 20:11:30 +0100, "Anon" wrote or quoted :

How do I find out if a variable has been used or initialised yet?

compile the code. Java won't let you write code with uninitialised
variables.


See http://mindprod.com/jgloss/initialisation.html

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.


So you are saying a null variable is initialised ?

Absolutely. An unitialized variable would contatin whatever garbage was
previously hanging around in that memory location. Null, in this case, is
definitely the result of initialization.

- Virgil



Back to top
Tony Morris
Guest





PostPosted: Mon Apr 26, 2004 11:06 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

Quote:

So you are saying a null variable is initialised ?


No.
The concept of a "null variable" is undefined in this context (the Java
Programming Language).

The suggestions that the compiler will complain if a variable may not have
been explicitly initialized apply to local variables only.
For example:

void m()
{
// local variable
int x;

if(something == 42)
{
x = 7;
}

// Compile error - x may not have been initialised.
System.out.println(x);
}

A member variable is always implicitly initialized (AND (not OR - this can
be demonstrated if need be) optionally explicitly initialized).
The default value that a member variable is explicitly initialized to is
dependant on the type of the varaible - I suggest reading the Java Language
Specification or an appropriate tutorial to learn these values.

class C
{
// member variable
int x;

void m()
{
// fine - x has been implicitly initialized to 0
System.out.println(x);
}
}


--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform



Back to top
Tony Morris
Guest





PostPosted: Mon Apr 26, 2004 11:39 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

Quote:
Absolutely. An unitialized variable would contatin whatever garbage was
previously hanging around in that memory location. Null, in this case, is
definitely the result of initialization.



No, it wouldn't contain anything - it would simpyly be uninitialized and
prevented from use.

Java != C

--
Tony Morris
(BInfTech, Cert 3 I.T.)
Software Engineer
(2003 VTR1000F)
Sun Certified Programmer for the Java 2 Platform (1.4)
Sun Certified Developer for the Java 2 Platform




Back to top
Roedy Green
Guest





PostPosted: Mon Apr 26, 2004 11:56 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

On Mon, 26 Apr 2004 22:46:26 +0100, "Anon" <voidrubbish (AT) hotmail (DOT) com>
wrote or quoted :

Quote:
However, judging by your
responses I believe it may be wiser to use boolean variables to flag weather
or not the variables have already been set or not.

If at all possible never allow objects to exist that are in an
dangerous half-baked state. Make the constructor them at least to a
non-dangerous minimalist state.

No one should have to be testing fields before touching an object.

Another way to do it, which unfortunately is exceedingly clumsy in
java is to have a set of classes like nested dolls.

An object starts out small, and as you discover more, it adds layers
with new fields to hold the additional information.

You know how complete it is by its type. You CAN'T write code that
uses the object improperly!

The catch is there is no easy way to covert a Dog to a Dalmatian and
then add the Dalmatian-specific fields. You need a copy constructor
that takes a Dog, and then fishes the fields out of Dog one by one.
PHHT! Very error prone, hard to maintain, and can't clone private
fields.

I wish there were some shortcut to do this. In assembler, it could be
implemented with single move instruction, to copy over the common
part.


--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.

Back to top
Roedy Green
Guest





PostPosted: Mon Apr 26, 2004 11:57 pm    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

On Tue, 27 Apr 2004 05:55:05 +0800, steve <me (AT) me (DOT) com> wrote or quoted
:

Quote:
So you are saying a null variable is initialised ?

Yes, null is a value. Uninitialised variables is C have a random
value in them left around from the last guy who used the RAM.

That never happens in Java. Either Java nulls/zeroes for you, or
forces you to set locals to something, possibly null/0.

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.

Back to top
Larry Barowski
Guest





PostPosted: Tue Apr 27, 2004 5:20 am    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote


"Tony Morris" <dibblego (AT) optusnet (DOT) com.au> wrote

Quote:
The compiler will sometimes issue bogus complaints,

Care to back this up with a bug report ?
Sounds like baloney to me.


It's not a bug. The problem of determining if a variable is initialized is
not computable (for those not familiar with computational theory, this
basically means "impossible to solve in the general case using an
algorithm").

Here is a simple example:

int j;
int i = 5;
if(i == 5)
j = 0;
j++;

Here is an example you could not expect any compiler to catch
(assume you have a method to compute the nth digit of pi):

int j;
if(digitOfPI(98000009) == 3)
j = 0;
j++;

-Larry Barowski



Back to top
Chris Uppal
Guest





PostPosted: Tue Apr 27, 2004 8:21 am    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote

Eric Sosman wrote:

Quote:
If it's a local variable in a method, the compiler will
complain if it thinks the variable might be used before
being initialized. The compiler will sometimes issue bogus
complaints

I think the wording you've choosen is a bit misleading.

The complaints are "bogus" in the sense that a different analysis with
different rules might have recognised the case.

However they are not "bogus" in the sense of being wrong. There are definite
rules for deciding whether a variable has been intialised before use, those
rules are part of the definition of the Java language, and the compiler follows
them -- it is not allowed any choice. There may be bugs, of course, but I,
personally, don't know of any.

-- chris



Back to top
Tony Morris
Guest





PostPosted: Tue Apr 27, 2004 9:44 am    Post subject: Re: Test to see of a variable has been used/initialised Reply with quote


"Larry Barowski" <larrybarATengDOTauburnDOTeduANDthatISall> wrote

Quote:

"Tony Morris" <dibblego (AT) optusnet (DOT) com.au> wrote in message
news:c6k2ud$mho$1 (AT) news (DOT) btv.ibm.com...
The compiler will sometimes issue bogus complaints,

Care to back this up with a bug report ?
Sounds like baloney to me.


It's not a bug. The problem of determining if a variable is initialized is
not computable (for those not familiar with computational theory, this
basically means "impossible to solve in the general case using an
algorithm").

Here is a simple example:

int j;
int i = 5;
if(i == 5)
j = 0;
j++;

Here is an example you could not expect any compiler to catch
(assume you have a method to compute the nth digit of pi):

int j;
if(digitOfPI(98000009) == 3)
j = 0;
j++;

-Larry Barowski



When the compiler complains about those cases, it is correct.

Consider the following example:

class S
{
String s;
}

// omitted
myS.s = "blah";

// point X
if(myS.s == "blah")
{
// this is NOT guaranteed to execute
}

If a thread pre-empts at point X and changes the object referred to by myS.s
then the boolean expression may evaluate to false (otherwise, it will
evaluate to true).
It is unreasonable to expect that the compiler should *know that*, in your
case, the int can never be altered by another thread (since it is a
primitive type and cannot be dereferenced), and therefore will evaluate
always to true.

Most JIT compilers will determine that the condition always evaluates to
true (unless it is declared with the volatile keyword to indicate
otherwise), and so will not bother evaluating the expression.

Either way, I'm not convinced that this case was the intended reference.
Unless proven otherwise, I'll maintain that the comment itself was bogus.

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)



Back to top
Display posts from previous:   
Post new topic   Reply to topic    AppletTalk.com Forum Index -> Java Language Programming All times are GMT
Goto page 1, 2, 3  Next
Page 1 of 3

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.