This week's book giveaways are in the iOS and Features new in Java 8 forums.
We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line!
See this thread and this one 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 Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 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: 19897

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
I agree. Here's the link:
subject: I am getting output as 0 but it must be 5 as i think