Read Also: int to Integer in Java
[Fixed] incompatible types: int cannot be converted to int[] error
Example 1: Producing the error by assigning an int to a variable whose type is int[]
We can easily produce this error by assigning an int to a variable whose type is int[] as shown below:
public class IntCanNotBeConvertedToIntArray { static int[] array; static int count; public static void printArray(int size) {array = size;count = size; for (int i=0; i<count ; i++) { array[i] = i; System.out.print(array[i]+" "); } } public static void main(String args[]) { printArray(13); } }
Output:
IntCanNotBeConvertedToIntArray.java:7: error: incompatible types: int cannot be converted to int[]
array = size;
^
1 error
Explanation:
The cause of this error is by assigning an int to a variable whose type is int[]. In the above code, we need to initialize the array variable to an array, not to an integer. We can use a new keyword to initialize the array.Solution:
In Java, we need to initialize the array variable not to an integer but an array. We can use the new keyword to solve this issue as shown below:public class IntCanNotBeConvertedToIntArray { static int[] array; static int count; public static void printArray(int size) {array = new int[size];count = size; for (int i=0; i<count ; i++) { array[i] = i; System.out.print(array[i]+" "); } } public static void main(String args[]) { printArray(13); } }
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12
Example 2: Producing the error by returning an int instead of int[] in the method
We can easily produce this error by returning an int instead of int[] as shown below:
public class IntCanNotBeConvertedToIntArray2 { static int[] array; public static int[] displayArray(int size) { array = new int[size]; for (int i=0; i < size ; i++) { System.out.print(array[i]+" "); }return size;} public static void main(String args[]) { displayArray(3); } }
Output:
IntCanNotBeConvertedToIntArray2.java:9: error: incompatible types: int cannot be converted to int[]
return size;
^
1 error
Explanation:
The cause of this error is by returning an int instead of int[] in the displayArray method.Solution:
In the displayArray method, we need to return an int[] instead of int. Just replace size which is an int with an int[] array in the return type of the displayArray method as shown below:public class IntCanNotBeConvertedToIntArray2 { static int[] array; public static int[] displayArray(int size) { array = new int[size]; for (int i=0; i < size ; i++) { System.out.print(array[i]+" "); }return array;} public static void main(String args[]) { displayArray(3); } }
Output:
0 0 0
That's all for today. Please mention in the comments in case you are still facing the error incompatible types: int cannot be converted to int[] in Java.