How do I declare and initialize an array in Java?
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).
For primitive types:
int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
For classes, for example String
, it's the same:
String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
How to initialize an array in Java?
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.
Initialize part of an array in java
You can do something like this, it will create array with new size based on provided.
String[] temp = new String[] {"water", "shovel", "berries", "stick", "stone", "seed", "axe"};
String[] val = Arrays.copyOf(temp, 20);
System.out.println(val.length);
System.out.println(Arrays.toString(val));
The output will be:
20
[water, shovel, berries, stick, stone, seed, axe, null, null, null, null, null, null, null, null, null, null, null, null, null]
Declare and initialize an array in Java
Initialize it in a static block, of course:
static {
str st[] = new str[10];
for (int i = 0; i < st.length; ++i) {
st[i] = new str();
}
}
Everyone else is assuming that your str
means java.lang.String
. I'm not.
I'll point out that your naming and coding conventions are rather poor. I'd recommend following the Java coding standards and thinking harder about good names for things.
Any shortcut to initialize all array elements to zero?
A default value of 0 for arrays of integral types is guaranteed by the language spec:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type
int
, the default value is zero, that is,0
.
If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).
In Java, initializing and accessing array inside a method?
You would need an initialization block to do it the second way,
int[] quiz = new int[2];
{
quiz[0] = 10;
quiz[1] = 20;
}
How to declare an array without having to give a fixed initial size in java?
Do it as follows:
- Declare
arr
without any size and as an instance variable. - Initialize
arr
in the constructor with size entered by the user.
Also, it's better to have the condition for the for
loop inside perform()
as j < arr.length
so that it depends purely on the size of arr
and not on the value of i
which might change in some other part of the program. For the same reason, I have declared i
as a local variable inside the constructor so that its scope is limited to the constructor only (where it is required) and nowhere else.
Code:
import java.util.Scanner;
class Example {
Scanner in = new Scanner(System.in);
int[] arr;
Example() {
System.out.println("in constructor");
System.out.println("enter array size: ");
int i = in.nextInt();
if (i >= 0) {
arr = new int[i];
}
}
void perform() {
System.out.println("Enter " + arr.length + " integers");
for (int j = 0; j < arr.length; j++)
arr[j] = in.nextInt();
for (int j = 0; j < arr.length; j++)
System.out.println(arr[j]);
}
}
public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.perform();
}
}
A sample run:
in constructor
enter array size:
2
Enter 2 integers
10
20
10
20
Related Topics
Why Does My Function That Calls an API or Launches a Coroutine Return an Empty or Null Value
Nullpointerexception Accessing Views in Oncreate()
Android - Get Real Path of a .Txt File Selected from the File Explorer
How to Get Url from Firebase Storage Getdownloadurl
What's the Best Way to Share Data Between Activities
Why Doesn't Recyclerview Have Onitemclicklistener()
Android, Getting Resource Id from String
Firebase Ui Authentication With Google Fails With Message (Code:10 Message:10)
Gson Throwing "Expected Begin_Object But Was Begin_Array"
Singletons Vs. Application Context in Android
Firebaselistadapter Not Pushing Individual Items For Chat App - Firebase-Ui 3.1
Inner Class Can Access But Not Update Values - Asynctask
How to Redirect Multiple Types of Users to Their Respective Activities