Continuing Reading Java Language Specification turned to section Evalution of Operands in compound assignment operations.
Can you predict the output of this program?
Object x[] = new String[3];
x[0] = new Integer(0);
System.out.println(x[0]);
It prints:
Exception in thread "Main Thread" java.lang.ArrayStoreException: Cannot store java.lang.Integer in [Ljava.lang.String;
at expressions.ArrayStoreExceptionClass.main(ArrayStoreExceptionClass.java:8)
If we closely look into the java lang api it states:
public class ArrayStoreException
extends RuntimeException
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0);
As said in my previous article Always remember The evaluation of the right-hand operand indeed occurs after the checks for a null array reference value and an out-of-bounds index value.
Can you predict the output for the example given in Java Language Specification please?
class ArrayReferenceThrow extends RuntimeException { }
class IndexThrow extends RuntimeException { }
class RightHandSideThrow extends RuntimeException { }
public class ArrayException {
static String[] strings = { "Simon", "Garfunkel" };
static double[] doubles = { Math.E, Math.PI };
static String[] stringsThrow() {
throw new ArrayReferenceThrow();
}
static double[] doublesThrow() {
throw new ArrayReferenceThrow();
}
static int indexThrow() { throw new IndexThrow(); }
static String stringThrow() {
throw new RightHandSideThrow();
}
static double doubleThrow() {
throw new RightHandSideThrow();
}
static String name(Object q) {
String sq = q.getClass().getName();
int k = sq.lastIndexOf('.');
return (k < 0) ? sq : sq.substring(k+1);
}
static void testEight(String[] x, double[] z, int j) {
try {
z[j] += doubleThrow();
System.out.println("Okay!");
} catch (Throwable e) { System.out.println(name(e)); }
try {
z[j] += 12345;
System.out.println("Okay!");
} catch (Throwable e) { System.out.println(name(e)); }
}
public static void main(String[] args) {
testEight(strings, doubles, 1);
testEight(strings, doubles, 9);
}
}
Output:
RightHandSideThrow
Okay!
ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException
Hence,They are the cases where a right-hand side that throws an exception actually gets to throw the exception; moreover, they are the only such cases in the lot. This demonstrates that the evaluation of the right-hand operand indeed occurs after the checks for a null array reference value and an out-of-bounds index value.
Hope this explanation helps.Any suggestions most welcomed.
Tuesday, 4 September 2007
Subscribe to:
Post Comments (Atom)
2 comments:
Yes Prasanth, this explanation helps.
Thanks Venu.
Post a Comment