File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Non static variable is incrementing for method call

 
venu gopal
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
can you please help me in understanding this question? This is from K&B Chapter3 Q 12.
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?
 
Prasad Kuppa
Ranch Hand
Posts: 151
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because, you are operating on same object..
[ July 30, 2003: Message edited by: Prasad Kuppa ]
 
venu gopal
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Prasad
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Venu,
answer is 3. right?
Barkat Mardhani
 
Ross Goldberg
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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. }
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic