The Local Variable May Not Have Been Initialized
Hi all;
There is a problem that i didnt understand..?Java assigns the initial value of defined variables.isnt it?I have a merge sort algorithm below but for C array the error is:
The local variable C may not have been initialized
in one of if and else statement C[ ] have to get a value...So i didnt understand whats the problem...Please dont say only,give an initial value to C[ ] :)
code is below; thanks for any suggestions
publicstaticvoid MergeSirala(int[] A,int[] B){
int i=1,j=1;
int n,m;
int[] C;
n=A.length;
m=B.length;
A[n]=B[m-1];
B[m]=A[n-1];
for(int k=0;k<n+m;k++)
{
if(A[i]>B[j])
{
C[k]=A[i];
i++;
}
else
{
C[k]=B[j];
j++;
}
}
}
[1418 byte] By [
netsonicca] at [2007-10-2 14:44:39]

You will initialize C[0], C[1], ...
But, you didn't create C as an array. You just declared it. You need:
int [] C = new int[n+m]; // whatever number you need
You need to check these lines:
A[n]=B[m-1];
B[m]=A[n-1];
A[n] and B[m] will cause ArrayIndexOutOfBoundsExceptions. The largest index in A is "n-1", the largest index in B is "m-1".
Your loop will also break with an ArrayIndexOutOfBoundsException when you get to the smaller of the lengths of A or B.
MLRona at 2007-7-13 13:16:46 >

The statement int[] C; declares a reference variable. In the posted code, this is declared inside a method. As was previously posted, there is no default value for a variable declared inside a method.
The if/else does not assign a value to C. The if/else tries to assign a value to an element in the array.You must have a new statement to create an array such as C=new int[5];
If C was an instance variable, its value would default to null so you would get a null pointer exception in the if/else.
Arrays elements always get intialized to their default values. But you are just declaring it, you need to give some memory to (construct) it cause an Array is an Object.The Java Turorial at http://java.sun.com/docs/books/tutorial/java/data/arrays.html will help you.
> ok, i got it!> i've declared the local variable and then initialize> it and eclipse doesnt bother me any more (or anymore?> i never know which is correct!).It's one word, not two. anymore.
MLRona at 2007-7-13 13:16:46 >
