• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using static variable to count the number of instances  RSS feed

 
Saishradha Mohanty
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not getting why this code is not showing the desired output, it should show 2 and print New duck created 2 times, but the output is only zero.

package com.company;
class Ducks{
    private static int count = 0;
    public Ducks(){
        count++;
        System.out.println("New duck created");
    }
    public static int getCount() {
        return count;
    }
}
public class checkDucks {
    Ducks d = new Ducks();
    Ducks t = new Ducks();
    public static void main(String[] args) {
        System.out.println(Ducks.getCount());
    }
}
 
Pete Letkeman
Ranch Foreman
Posts: 918
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you move these two lines

inside of the main method then you will get the results that you expect.

Please use code tags (https://coderanch.com/wiki/659781/Code-Tags) when providing code.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the variables d and t in checkDucks are instance variables. They won't get initialized when you run main(), only when you instantiate a checkDucks object. BTW, the name "checkDucks" does not follow the naming convention for classes in Java, which should always start with a capital letter.
 
Saishradha Mohanty
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, I didn't realise that I was actually declaring an instance variable for the class checkDucks.
I will take care that I post a code in code blocks only in future.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!