Re: Parentheses issue




"Andrew" <andrew.lubitz@xxxxxxxxx> wrote in message
news:1167529951.191362.135990@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This is an order of operations issue. It would also help to know
whether the error you got was a compile-time error or a runtime
error.
(I'm not sure if you said or not.)

Hi, Andrew, and yes, compile time.

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:

if(list.get(index) instanceof Type1)
((Type1)list.get(index)).doSomething();

It's good to see this in another form, especially a common one.
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 the
ternary
operator:

if(object1 instanceof Type1 ?
((Type1)object1).booleanFunction() :
false)
doSomething();

I hope this helps.
Nice, I've never seen ternary used like that.

Thanks Andrew.


.



Relevant Pages

  • Re: Parentheses issue
    ... whether the error you got was a compile-time error or a runtime error. ... ifinstanceof Type1) ... The && operator evaluates the expressions on both sides. ...
    (comp.lang.java.programmer)
  • Re: Parentheses issue
    ... whether the error you got was a compile-time error or a runtime error. ... ifinstanceof Type1) ... private static boolean aCalled = false; ...
    (comp.lang.java.programmer)