+ 1

IN THIS JAVA CODE WHY THE OUTPUT IS COMING ONLY FOR ONE CLASS ?

public class Counter { public static int COUNT=0; Counter() { COUNT++; } } public class yClass { public static void main(String[ ] args) { Counter g = new Counter(); Counter ga = new Counter(); System.out.println(Counter.COUNT); } } public class hero { public static void main(String[ ] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter s3 = new Counter(); System.out.println(Counter.COUNT); } } THE OUTPUT COMING IS //2 BUT THE OUTPUT EXPECTING IS //2 3

9th Jan 2018, 8:58 PM
Venkatesh Chintala
Venkatesh Chintala - avatar
5 Respostas
+ 1
you have 2 main methods in different classes. the first one found will be called to start ur program aka the one with 2 Counter objects
9th Jan 2018, 9:15 PM
Jeremy
Jeremy - avatar
0
but bro if suppose to to write the code using eclipse in such a way that by making 2 seperate files in each with one main method. And after that if i run the whole package then what will be the Output. Same single answer(2) or two different answers(2 & 3) .
9th Jan 2018, 9:37 PM
Venkatesh Chintala
Venkatesh Chintala - avatar
0
whatever jvm finds first you are not supposed to write multiple main's
9th Jan 2018, 9:38 PM
Jeremy
Jeremy - avatar
0
ok thanks bro #Jeremy
9th Jan 2018, 9:56 PM
Venkatesh Chintala
Venkatesh Chintala - avatar
- 1
Only one main will run. Given your output, the yClass one was picked.
9th Jan 2018, 9:14 PM
John Wells
John Wells - avatar