Re: Parentheses issue



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.)

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();

Another common case is getting an item out of a list:

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

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();

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();

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.

.



Relevant Pages

  • 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)
  • Re: Parentheses issue
    ... whether the error you got was a compile-time error or a runtime ... ifinstanceof Type1) ... The && operator evaluates the expressions on both sides. ... So this cast fails at runtime. ...
    (comp.lang.java.programmer)
  • Re: capture error - the better way?
    ... but this will get a runtime error. ... Sorry this is exactly a compile-time error. ... # cat except.pl ... can't we capture it at runtime when meeting such error? ...
    (perl.beginners)
  • Re: Care to test your Delphi knowledge?
    ... I'll stick my neck out: ... Which of the class definitions WILL PRODUCE a Compile-Time ERROR? ... Version C produces a runtime error. ...
    (borland.public.delphi.non-technical)