Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Non static variable is incrementing for method call

venu gopal
Ranch Hand
Posts: 40
Hi All,
1. class BoolArray {
2. boolean [] b = new boolean[3];
3. int count = 0;
4.
5. void set(boolean [] x, int i) {
6. x[i] = true;
7. ++count;
8. }
9.
10. public static void main(String [] args) {
11. BoolArray ba = new BoolArray();
12. ba.set(ba.b, 0);
13. ba.set(ba.b, 2);
14. ba.test();
15. }
16.
17. void test() {
18. if ( b[0] && b[1] | b[2] )
19. count++;
20. if ( b[1] && b[(++count - 2)] )
21. count += 7;
22. System.out.println("count = " + count);
23. }
24. }
what is the result?
A. count = 0
B. count = 2
C. count = 3
D. count = 4
E. count = 10
F. count = 11
Here count is not static variable. How it is incrementing for each call to set() method?

Ranch Hand
Posts: 151
Because, you are operating on same object..
[ July 30, 2003: Message edited by: Prasad Kuppa ]

venu gopal
Ranch Hand
Posts: 40

Barkat Mardhani
Ranch Hand
Posts: 787
Hi Venu,
Barkat Mardhani

Ross Goldberg
Ranch Hand
Posts: 63
I got (c) for a value of c, like Barkat:
lines 12 and 13 increment count in line 7 by 1 each (total of 2)
The first if in line 18 brings count to 13 after resulting to true
(true and (false or true)) (remember && has precedence over || so it goes in there and no short-circuiting occurs), thus ending in a value of 3.
The next if in line 20 gets short-circuited after the first operand results in false.
1. class BoolArray {
2. boolean [] b = new boolean[3];
3. int count = 0;
4.
5. void set(boolean [] x, int i) {
6. x[i] = true;
7. ++count;
8. }
9.
10. public static void main(String [] args) {
11. BoolArray ba = new BoolArray();
12. ba.set(ba.b, 0);
13. ba.set(ba.b, 2);
14. ba.test();
15. }
16.
17. void test() {
18. if ( b[0] && b[1] | b[2] )
19. count++;
20. if ( b[1] && b[(++count - 2)] )
21. count += 7;
22. System.out.println("count = " + count);
23. }
24. }