Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array in Java?

I am initializing an array like this:

public class Array {      int data[] = new int[10];      /** Creates a new instance of Array */     public Array() {         data[10] = {10,20,30,40,50,60,71,80,90,91};     }      } 

NetBeans points to an error at this line:

data[10] = {10,20,30,40,50,60,71,80,90,91}; 

How can I solve the problem?

like image 768
chatty Avatar asked Dec 21 '09 03:12

chatty


People also ask

How do you initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

How many ways arrays can be initialized in Java?

There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

How arrays are defined and initialized in Java explain with an example?

In Java, we can initialize arrays during declaration. For example, //declare and initialize and array int[] age = {12, 4, 5, 2, 5}; Here, we have created an array named age and initialized it with the values inside the curly brackets.

Do you have to initialize array in Java?

no, all java arrays are filled with the appropriates type default value (0 for ints, 0.0 for doubles, null for references, ...) Show activity on this post. You can't skip the array initialization but you don't have to initialize each element of the array.


2 Answers

data[10] = {10,20,30,40,50,60,71,80,90,91}; 

The above is not correct (syntax error). It means you are assigning an array to data[10] which can hold just an element.

If you want to initialize an array, try using Array Initializer:

int[] data = {10,20,30,40,50,60,71,80,90,91};  // or  int[] data; data = new int[] {10,20,30,40,50,60,71,80,90,91}; 

Notice the difference between the two declarations. When assigning a new array to a declared variable, new must be used.

Even if you correct the syntax, accessing data[10] is still incorrect (You can only access data[0] to data[9] because index of arrays in Java is 0-based). Accessing data[10] will throw an ArrayIndexOutOfBoundsException.

like image 144
Prasoon Saurav Avatar answered Sep 22 '22 07:09

Prasoon Saurav


Try

data = new int[] {10,20,30,40,50,60,71,80,90,91 }; 
like image 35
Dean Povey Avatar answered Sep 20 '22 07:09

Dean Povey