Static Methods - Please help! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Static Methods - Please help!

I'm having trouble figuring out why these two codes do NOT give the same output. They look exactly the same to me - I'm so confused. For context, these examples were given under the 'static' topic in java. You can find them below. Java > Classes and Objects > Static > First "Try it your self" example. vs Java > Classes and Objects > Static > Last Question /* public class DemoStaticVariables { public static int pCount; public static void main(String[ ] args) { DemoStaticVariables.pCount=0; DemoStaticVariables.pCount++; System.out.println(DemoStaticVariables.pCount); } } //Outputs 1 */ /* class Counter{ public static int COUNT=0; Counter(){ COUNT++; } } public class DemoStaticVariables { public static void main(String[ ] args) { System.out.println(Counter.COUNT); } } //Outputs 0 */

6th Oct 2020, 1:44 AM
Joshua Olorunleye
Joshua Olorunleye - avatar
1 Answer
+ 2
In the second code Counter() is never called because you didn't initialize any Counter object. Thus COUNT is 0.
6th Oct 2020, 2:03 AM
你知道規則,我也是
你知道規則,我也是 - avatar