Re: Parentheses issue
- From: "jupiter" <jupiter49byebyeSpam@xxxxxxx>
- Date: Sat, 30 Dec 2006 22:58:30 -0500
"Andrew" <andrew.lubitz@xxxxxxxxx> wrote in message
news:1167529951.191362.135990@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This is an order of operations issue. It would also help to knowHi, Andrew, and yes, compile time.
whether the error you got was a compile-time error or a runtime
error.
(I'm not sure if you said or not.)
If it was a compile-time error, read this, but you might want to
read
it anyway:
Sometimes you can use
(Type)object
without having to put an extra set of parentheses around the
whole
thing, like if you are saying
Type1 object2 = (Type1)object1;
but since the casting operation happens in the order it does, to
do
most other operations on the casted object, you will need another
set
of parentheses, like in the following example:
if(object1 instanceof Type1)
if(((Type1)object1).booleanFunction())
doSomething();
I guess the "order it does" is last on the to-do list, eh?
Another common case is getting an item out of a list:It's good to see this in another form, especially a common one.
if(list.get(index) instanceof Type1)
((Type1)list.get(index)).doSomething();
The order of execution with cast is something I've never paid much
attention until now.
OTHERWISE, if it was a runtime error, read this (and you might
want to
read it anyway):
The && operator evaluates the expressions on both sides. Even if
the
first side is false (and therefore it would logically return
false
regardless of the second side's value) the second side will still
be
evaluated. Thus, in a case such as
if(object1 instanceof Type1 &&
((Type1)object1).someBooleanFunction())
doSomething();
So this cast fails at runtime. Got it.
the Java Virtual Machine will come across an error if the object
is not
of the required type, because it will try to evaluate the second
expression.
The way to solve this is to do either this
if(object1 instanceof Type1)
if(((Type1)object1).booleanFunction())
doSomething();
Thanks .... good to know.
or, if you are feeling bold and know or are ready to learn theNice, I've never seen ternary used like that.
ternary
operator:
if(object1 instanceof Type1 ?
((Type1)object1).booleanFunction() :
false)
doSomething();
I hope this helps.
Thanks Andrew.
.
- References:
- Parentheses issue
- From: jupiter
- Re: Parentheses issue
- From: Andrew
- Parentheses issue
- Prev by Date: Re: MIDI OUT transmitter not available?
- Next by Date: Re: Parentheses issue
- Previous by thread: Re: Parentheses issue
- Next by thread: Re: Parentheses issue
- Index(es):
Relevant Pages
|