JAVA question
Consider the following:
1 class SnoopDogg { 2 int count; 3 } 4 class Test { 5 public static void main ( String [] args ) { 6 SnoopDogg myCount = new SnoopDogg (); 7 myCount.count = 0; 8 int times = 0; 9 increment( myCount, times ); 10 System.out.println( myCount.count ); 11 System.out.println( times ); 12 } 13 public static void increment (SnoopDogg sd, int times ) { 14 sd.count = sd.count + 1; 15 times = times + 1; 16 } 17 }
When run, what is the value of times displayed?
3
2
0
1
Solution:
In this code count and time both are printing when run this code output is 1 and 0.
So the value of times display when run is 0.
Reason:
initialize the value of count variable in MyCount object and
times variable as zero.
After calling the increment method, the value of count variable in
MyCount object gets changed as objects are passed by reference but
integer variables are by default passed by value, so the value of
times variable remains zero.
Output screenshot when run this code:
Get Answers For Free
Most questions answered within 1 hours.