public class Solution {
public static void main(String[] args) {
Cat cat1 = new Cat();
Cat.count++;
Cat cat2 = new Cat();
Cat.count++;
System.out.println("The cat count is " + Cat.count);
}
public static class Cat {
public static int count = 0;
}
}
I am just trying to understand the code better.
The solution is 2. So does it mean, cat1 object is getting added to the cat2 object and the result is 2 as cat1+ cat2 = 2 ?
Where can we see that exactly?
Because when I check the line 4, I can see 1 item is added ontop of cat1, so it makes 2.
Then line 7 , cat2 has also ++, so then the value must be also 2.
So in total it should be 4 and not 2?
Perhaps I just messed it up.
Can someone kindly explain how this whole program is working? Thanks in advance.How comes the result in the display is 2 and not 4?
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Vincenzo Seggio
8 December 2020, 05:59useful
This
has the same output.
Here an explanation about static variables:
https://www.guru99.com/java-static-variable-methods.html#:~:text=Static%20variable%20in%20Java%20is,the%20start%20of%20the%20execution. +1
Ahu
8 December 2020, 10:54
Thanks, just checked it, yeah it has the same output.
0