Tuesday, October 21, 2008

Simple One but ....

In the past 5+ years of my experience as a Jave Panelist for the recuritment drives in company, most regular question by me is this

What is static? What does it mean when a method is declared static - Ofcourse the most obvious answers would be - Static means only one instance per class. And when method is static, only one instance exists for that class. - Immediately my reaction would be a sharp smile as the candidate fell into trap.

My next question is - Then i have a method called add as below.

public static void add (int a, int b) {
int sum = 0;
sum = a + b;
System.out.println("Sum equals -- " + sum);

What is the result when two concurrent threads access the same method with inputs (3,4) and (4,5).

Will the execution gives right results or wrong results? if so why?
about 99% of cases have this wrong by first saying right results and when i point back to their definition of having a single instance and stressing on 2 concurrent threads, answer changes to defining the method syncronized. Then to further test his reasoning, i would say, so do you mean every method declared static should have syncronized as mandatory. Bowled!!!!!

Any tries are welcome..will exlain later...

Note: this is just to explain/test a simple java basic, not that i am saddist with the candidates. Having got bored asking typical questions as listed in many websites - java intervew questions etc., try asking un-orthodox questions.

1 comment:

  1. I would like to thank a "anonymous" guest who read my blog and posted a comment for me. And i would like to say, i am impressed with your tech knowledge. But i am sorry to say, your inability to read the post properly. May be i didnt present properly. Indeed your answer is absoultely right and that is what i wanted to explain which i explained in my later post on Heap vs Stack. I was not saying what you understood.

    Anyway, i am always open for any suggestions and ready to correct. Please do log openly next time. Good Luck to you. Wish you a very happy and successful New Year.