This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes I am getting output as 0 but it must be 5 as i think Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "I am getting output as 0 but it must be 5 as i think" Watch "I am getting output as 0 but it must be 5 as i think" New topic

I am getting output as 0 but it must be 5 as i think

Rakesh Bagaria

Joined: Sep 06, 2009
Posts: 14
//class with private constructor

class A
static int count =0;

private A()

//count function for object created
static void countfun(int n)

A ob[]=new A[n];
System.out.println("Number of Object created is "+count);


//main class

class PrivCons
public static void main(String args[])


Lester Burnham

Joined: Oct 14, 2008
Posts: 1337
I don't see any instances of class A being created. The only thing that's being created is an array that can hold instances of class A; that does not cause those object to be created, though.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

Welcome to javaRanch
Please use code tags while posting your Question.
it would be easier for other to read your post and also you will get a good response

SCJP6.0,My blog Ranchers from Delhi
Rob Spoor

Joined: Oct 27, 2005
Posts: 19649

Lester is right. If you create an array of objects, each element will remain null until explicitly set a value. Unless you use {} to set the values immediately that is:

How To Ask Questions How To Answer Questions
Vishal Kashyap
Ranch Hand

Joined: Aug 07, 2010
Posts: 73

First of all,
You have not created any instance of class A yet is the main reason and after all, you have made your default constructor as Private so it cant be accessible is different class that's why your code for count increment in the private default constructor would not work at all. Each and every time after creating your instance in this code will get count to be Zero as a result.

MCSA 2003 | Preparing For OCPJP/SCJP6
Don't get me started about those stupid light bulbs.
subject: I am getting output as 0 but it must be 5 as i think
Similar Threads
Finding Nth Largest element of an array without sorting
SoDuko puzzle
fibonacci program
Abstract Class doubt
static block and empty block inside any class.