Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array variable "might not have been initialized"

Tags:

java

I get the error:

TestCounter.java:115: variable counters might not have been initialized counters[i] = new Counter(i);

And I can't figure out how to fix it. I know that my class, Counter, works. Below is my code, if you could have a look at it I would be very happy. This code is wrapped in the main method of a TestCounter class.

  if(success) 
  {  
   Counter[] counters;

   for(int i=0; i<30; i++)
   {
       counters[i] = new Counter(i);
       System.out.println(counters[i].whatIsCounter());
   }
  }
like image 781
C. E. Avatar asked Nov 13 '10 11:11

C. E.


People also ask

Why does it say variable might not have been initialized?

If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

Why is my variable not initialized Java?

This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.). However, local variables need a default value because the Java compiler doesn't allow the use of uninitialized variables.

How do you initialize an array in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.


1 Answers

You haven't created the array, you've just declared the variable.

You need to do this:

Counter[] counters = new Counter[30];

or something similar

like image 173
skaffman Avatar answered Nov 02 '22 19:11

skaffman