• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Notrajon Mock Question 18

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Q18{
static int call(int x){
try{
System.out.println(x---x/0);
return x--;
}
catch(Exception e){
System.out.println(--x-x%0);
return x--;
}
finally{
return x--;
}
}
Output is 3; can anyone explain please. Thanks
public static void main(String[] args){
System.out.println(" value = "+ call(5));
}
}
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Albert Gray:

Hope this helps,
Siva
 
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's a very tricky question.Here goes...
1)When method call(int) is invoked,local variable x is assigned the value 5.Initially x=5.
2)The expression

is evaluated.Statement consists of unary as well as binary operators.The current value of x will be substitued.So now the expression looks like
5--x/0;
Now x will be decremented,since we have a post fix operator.Thus now the values are
x->4;
expr.-> 5--4/0.
4/0 will throw an ArithmeticException and control passes to catch block
3)Catch block contains expression

Now x will be decremented,since we are using a prefix operator.Thus values will be
x->3
expr.->3-3%0.
3%0 will throw an Arithmetic Exception and execution proceeds to finally block.
4)In the finally block,Current value of x will be returned,which is 3.Now x will be decremented,since a post fix operator is used.However,that value is lost as local variables go out of scope once method exits.
I just changed the code to

I hope that helps.
------------------
Udayan Naik
Sun Certified Java 2 Programmer
[This message has been edited by Udayan Naik (edited March 06, 2001).]
 
Albert Gray
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Siva & Udayan:
Thanks for your reply.
Albert
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic