public class Question16 { public static void main(String[] args) { int i = 2; try { if((i/=(int)Math.floor(Math.random())) > 1) System.out.println("No arithmetic exception"); } catch (ArithmeticException ae){ System.err.println("Arithmetic exception caught"); } System.out.println(i); } } the ans is iis 2. my question is. why is the value of i printed as 2, the value of i got changed in the try block did it not ?, and since i is not local to try, there is no reason why the initial value of i be maintained. PLs explain jui
-----jui<br />scjp1.4
Hanna Habashy
Ranch Hand
Joined: Aug 20, 2003
Posts: 532
posted
0
hi Jui: The <if statement> will throw ArthimeticException, so that the body of <if statement> will not be excuted. Then <the catch block> will be excuted printing "Arthimetic Exception cought". After that, the <println statement> will be excuted printing the value of <i>, which has not been changed. If <if statement> wouldn't throw an exception, then the value of <i> would have been changed, and then the catch block would not have been excuted. I hope that will help Hanna
SCJD 1.4<br />SCJP 1.4<br />-----------------------------------<br />"With regard to excellence, it is not enough to know, but we must try to have and use it.<br />" Aristotle
Priyanka Chopda
Ranch Hand
Joined: Jul 22, 2003
Posts: 112
posted
0
Jui, in this case line if((i/=(int)Math.floor(Math.random())) > 1) is thrwoing an exception and when it happens that line won't get evaluated. So value of i is never changing and what getting printed is 2 (declared in line 3. i.e. int i = 2 which is instance variable and have class scope. -PC
Dhanashree Mankar
Ranch Hand
Joined: Aug 25, 2003
Posts: 123
posted
0
Originally posted by Jui Mahajan: public class Question16 { public static void main(String[] args) { int i = 2; try { if((i/=(int)Math.floor(Math.random())) > 1) System.out.println("No arithmetic exception"); } catch (ArithmeticException ae){ System.err.println("Arithmetic exception caught"); } System.out.println(i); } } the ans is iis 2. my question is. why is the value of i printed as 2, the value of i got changed in the try block did it not ?, and since i is not local to try, there is no reason why the initial value of i be maintained. PLs explain jui
--------------------------------------------------------------------------- Value of i is not getting changed. After solving (int)Math.floor(Math.random()) we are getting 0 Now i/=0 will result into ArithmaticException which will be caught.And so value of i remains 2
Jui Mahajan
Ranch Hand
Joined: Jun 02, 2003
Posts: 62
posted
0
Thank u all. Just wanted to know what mock exams you guys think r important and what methods do we have to study for collection classes? The Kathy-sierra book does not mention any methods for colection classes.