Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static problem  RSS feed

 
Padmaja Balaji
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A question from JQ+ - Question ID :957921513300
What will be the output of the following program ?
class Test
{
static int i1, i2, i3;
public static void main(String[] args)
{
try
{
test(i1 = 1, oops(i2=2), i3 = 3);
} catch (Exception e)
{
System.out.println(i1+" "+i2+" "+i3);
}
}
static int oops(int i) throws Exception
{
throw new Exception("oops");
}
static int test(int a, int b, int c) { return a + b + c; }
}
The options are :
1 0 0
1 2 0
1 2 3
0 0 0
It will not compile
The correct answer is 1 2 0
The explanation for the same is given as :
i1 and i2 will be assigned the new values but i3 will not be because oops() throws an exception.
If evaluation of an argument expression completes abruptly, no part of any argument expression to its right is evaluated.
Can someone further explain on the above. I am not clear.
- Padmaja
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Padmaja,
The code compiles correctly using JDK 1.3 and print 1, 2, 0.
During the call to <code>test( i1=1, oops( i2=2 ), i3=3 )</code>
(1) i1=1 is evaluated and the variable 'i1' is set to '1'
(2) i2=2 is evaluated and the variable 'i2' is set to '2'. The result is then passed to <code>oops()</code> which throws an Exception.
(3) The Exception is caught, the code in the <code>catch</code> block is executed and the program continues. It does not return to the <code>test()</code> method so the variable 'i3' is not set to '3'.
The Exception disrupts the normal flow of <code>test()</code> invocation.
Hope that helps.
PS When you post code it is easier to read if you use UBB Codes

------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Padmaja Balaji
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot. I was stuck with i3 value. Now it is clear.
Henceforth, I'll use UBB code.
- Padmaja
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!