Before you post a new answer, consider there are already 25+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers.
Commented Feb 3, 2020 at 11:50 Commented Dec 22, 2020 at 9:03You 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]; // each element of the array is initialised to 0 int[] myIntArray = ; int[] myIntArray = new int[]; // 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]; // each element is initialised to null String[] myStringArray = ; String[] myStringArray = new String[];
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[];
community wiki
What's the purpose of having both the second and third way to do it?
Commented Apr 10, 2015 at 3:23
@iamcreasy It looks like the second way doesn't work with return statements. return <1,2,3>gives an error, while return new int[] <1,2,3>works fine (assuming of course that your function returns an integer array).1,2,3>
Commented Apr 16, 2015 at 17:44There are two types of array.
Syntax for default values:
int[] num = new int[5];
Or (less preferred)
int num[] = new int[5];
Syntax with values given (variable/field initialization):
int[] num = ;
Or (less preferred)
int num[] = ;
Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.
int[][] num = new int[5][2];
int num[][] = new int[5][2];
int[] num[] = new int[5][2];
num[0][0]=1; num[0][1]=2; num[1][0]=1; num[1][1]=2; num[2][0]=1; num[2][1]=2; num[3][0]=1; num[3][1]=2; num[4][0]=1; num[4][1]=2;
int[][] num=< , , , , >;
int[][] num = new int[5][]; num[0] = new int[1]; num[1] = new int[5]; num[2] = new int[2]; num[3] = new int[3];
So here we are defining columns explicitly.
Another Way:
int[][] num=< , , , , >;
for (int i=0; i
for (int[] a : num) < for (int i : a) < System.out.println(i); >>
Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials
I might argue with you on the point that a multidimensional array is a different "type" of array. It's simply a term used to describe an array that happens to contain other arrays. Both the outer arrays and the inner arrays (and those in between, if they exist) are just regular arrays.
Commented Jul 18, 2017 at 15:19Perhaps worth noting that the second (less-preferred) form stems from C/C++. This might be the reason why it is supported in Java.
Commented Feb 4 at 13:57Type[] variableName = new Type[capacity]; Type[] variableName = ; Type variableName[] = new Type[capacity]; Type variableName[] = ;
is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.
65.8k 38 38 gold badges 279 279 silver badges 399 399 bronze badges answered Jul 29, 2009 at 14:29 16.9k 5 5 gold badges 46 46 silver badges 59 59 bronze badgesI agree on that point. The type of the variable is not "TYPE", but actually a TYPE[], so it makes sense to write it that way for me.
Commented Jul 29, 2009 at 14:31 Google style suggest this too. Commented Mar 5, 2014 at 12:43Note that int[] a, b; will not be the same as int a[], b; , a mistake easy to make if you use the latter form.
Commented Mar 19, 2015 at 1:46There are various ways in which you can declare an array in Java:
float floatArray[]; // Initialize later int[] integerArray = new int[10]; String[] array = new String[] ;
You can find more information in the Sun tutorial site and the JavaDoc.
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges answered Jul 29, 2009 at 14:28 2,237 5 5 gold badges 25 25 silver badges 32 32 bronze badgesThis answer fails to properly address the question: "How do I declare and initialize an array in Java?" Other answers here show that it is simple to initialize float and int arrays when they are declared. There is no need to "Initialize later".
Commented Jan 18, 2023 at 23:36I find it is helpful if you understand each part:
Type[] name = new Type[5];
Type[] is the type of the variable called name ("name" is called the identifier). The literal "Type" is the base type, and the brackets mean this is the array type of that base. Array types are in turn types of their own, which allows you to make multidimensional arrays like Type[][] (the array type of Type[]). The keyword new says to allocate memory for the new array. The number between the bracket says how large the new array will be and how much memory to allocate. For instance, if Java knows that the base type Type takes 32 bytes, and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.
You can also create arrays with the values already there, such as
int[] name = ;
which not only creates the empty space but fills it with those values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.
732 7 7 silver badges 22 22 bronze badges answered Jul 29, 2009 at 14:29 21.9k 10 10 gold badges 42 42 silver badges 58 58 bronze badges So it is not necessary to include int[] name = new int[5] ? Commented Jun 28, 2018 at 10:26The following shows the declaration of an array, but the array is not initialized:
int[] myIntArray = new int[3];
The following shows the declaration as well as initialization of the array:
int[] myIntArray = ;
Now, the following also shows the declaration as well as initialization of the array:
int[] myIntArray = new int[];
But this third one shows the property of anonymous array-object creation which is pointed by a reference variable "myIntArray", so if we write just "new int[];" then this is how anonymous array-object can be created.
If we just write:
int[] myIntArray;
this is not declaration of array, but the following statement makes the above declaration complete:
myIntArray=new int[3];
5,536 4 4 gold badges 18 18 silver badges 37 37 bronze badges
answered Jun 4, 2013 at 6:02
Amit Bhandari Amit Bhandari
531 6 6 silver badges 8 8 bronze badges
There is absolutely no difference between the second and third approaches, other than that the second approach only works when you're also declaring a variable. It's not clear what you mean by "shows the property of anonymous array-object creation" but they really are equivalent pieces of code.
Commented Feb 21, 2015 at 23:08Also, the first snippet does initialize the array - it is guaranteed to have the value 0 for every array element.
Commented Feb 21, 2015 at 23:12 Is there really no difference between the second and the third one approaches? Commented Jan 15, 2020 at 6:28// Either method works String arrayName[] = new String[10]; String[] arrayName = new String[10];
That declares an array called arrayName of size 10 (you have elements 0 through 9 to use).
answered Jul 29, 2009 at 14:25 Thomas Owens Thomas Owens 116k 99 99 gold badges 317 317 silver badges 436 436 bronze badgesWhat is the standard for which to use? I've only just discovered the former, and I find it horrifically misleading :|
Commented Oct 3, 2012 at 4:20For what it's worth my prof said that the second way is more typical in Java and that it better conveys what is going on; as an array related to the type the variable was cast as.
Commented Aug 9, 2013 at 4:50Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
List listOfString = new ArrayList(); listOfString.add("foo"); listOfString.add("bar"); String value = listOfString.get(0); assertEquals( value, "foo" );
128k 71 71 gold badges 242 242 silver badges 295 295 bronze badges
answered Jul 29, 2009 at 15:56
14k 7 7 gold badges 45 45 silver badges 53 53 bronze badges
what is the "<>" called in the list that you created ?
Commented Aug 27, 2015 at 0:05
@CyprUS List is a generic class, it has a type as a parameter, enclosed in <> . That helps because you only need to define a generic type once and you can then use it with multiple different types. For a more detailed explanation look at docs.oracle.com/javase/tutorial/java/generics/types.html
Commented Nov 29, 2018 at 14:27There are two main ways to make an array:
This one, for an empty array:
int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
And this one, for an initialized array:
int[] array = ;
You can also make multidimensional arrays, like this:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions int[][] array2d = < , . >;
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges
answered Jan 28, 2016 at 19:19
780 7 7 silver badges 8 8 bronze badges
Using Arrays.setAll (similar to Arrays.fill , but takes the generator function, which accepts an index and produces the desired value for that position, which gives more flexibility):
int[] a = new int[5]; Arrays.setAll(a, index -> index + 1); Out: [1, 2, 3, 4, 5]
int[] a = IntStream.iterate(10, x -> x x + 10).toArray(); Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray(); Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var letters = new String[];
answered Feb 21, 2018 at 12:45
Oleksandr Pyrohov Oleksandr Pyrohov
15.8k 6 6 gold badges 70 70 silver badges 95 95 bronze badges
Take the primitive type int for example. There are several ways to declare and int array:
int[] i = new int[capacity]; int[] i = new int[] ; int[] i = ;
where in all of these, you can use int i[] instead of int[] i .
With reflection, you can use (Type[]) Array.newInstance(Type.class, capacity);
Note that in method parameters, . indicates variable arguments . Essentially, any number of parameters is fine. It's easier to explain with code:
public static void varargs(int fixed1, String fixed2, int. varargs) . varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = ;
Inside the method, varargs is treated as a normal int[] . Type. can only be used in method parameters, so int. i = new int[] <> will not compile.
Note that when passing an int[] to a method (or any other Type[] ), you cannot use the third way. In the statement int[] i = ** , the compiler assumes that the <. >means an int[] . But that is because you are declaring a variable. When passing an array to a method, the declaration must either be new Type[capacity] or new Type[] <. >.
Multidimensional arrays are much harder to deal with. Essentially, a 2D array is an array of arrays. int[][] means an array of int[] s. The key is that if an int[][] is declared as int[x][y] , the maximum index is i[x-1][y-1] . Essentially, a rectangular int[3][5] is:
[0, 0] [1, 0] [2, 0] [0, 1] [1, 1] [2, 1] [0, 2] [1, 2] [2, 2] [0, 3] [1, 3] [2, 3] [0, 4] [1, 4] [2, 4]
16.2k 193 193 gold badges 69 69 silver badges 98 98 bronze badges
answered May 23, 2015 at 19:56
hyper-neutrino hyper-neutrino
5,360 2 2 gold badges 30 30 silver badges 52 52 bronze badges
In Java 8 you can use something like this.
String[] strs = IntStream.range(0, 15) // 15 is the size .mapToObj(i -> Integer.toString(i)) .toArray(String[]::new);
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges
answered Mar 8, 2018 at 18:21
Chamly Idunil Chamly Idunil
1,888 1 1 gold badge 20 20 silver badges 34 34 bronze badges
If you want to create arrays using reflections then you can do like this:
int size = 3; int[] intArray = (int[]) Array.newInstance(int.class, size );
5,536 4 4 gold badges 18 18 silver badges 37 37 bronze badges
answered Jan 20, 2015 at 11:54
Muhammad Suleman Muhammad Suleman
2,902 2 2 gold badges 26 26 silver badges 33 33 bronze badges
Why would you want to create an array that way?
Commented Jan 8, 2020 at 19:38
your question applies to all variant of provided answers in this section. really question might be is why language having variety of declarations for one thing? and the answer what I assume can be that all variants helps us in several situations and hence language is supporting us to perform things as required.
Commented Feb 15, 2023 at 10:01Array is a sequential list of items
int item = value; int [] one_dimensional_array = < value, value, value, . value >; int [][] two_dimensional_array = < < value, value, value, .. value >, < value, value, value, .. value >, .. .. .. .. < value, value, value, .. value >>;
If it's an object, then it's the same concept
Object item = new Object(); Object [] one_dimensional_array = < new Object(), new Object(), .. new Object() >; Object [][] two_dimensional_array = < < new Object(), new Object(), .. new Object() >, < new Object(), new Object(), .. new Object() >, .. .. .. < new Object(), new Object(), .. new Object() >>;
In case of objects, you need to either assign it to null to initialize them using new Type(..) , classes like String and Integer are special cases that will be handled as following
String [] a = < "hello", "world" >; // is equivalent to String [] a = < new String(), new String() >; Integer [] b = < 1234, 5678 >; // is equivalent to Integer [] b = < new Integer(1234), new Integer(5678) >;
In general you can create arrays that's M dimensional
int [][]..[] array = // ^ M times [] brackets >..> // ^ M times > bracket ;
It's worthy to note that creating an M dimensional array is expensive in terms of Space. Since when you create an M dimensional array with N on all the dimensions, The total size of the array is bigger than N^M , since each array has a reference, and at the M-dimension there is an (M-1)-dimensional array of references. The total size is as following
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0 // ^ ^ array reference // ^ actual data
answered Oct 21, 2015 at 13:39
5,934 1 1 gold badge 34 34 silver badges 52 52 bronze badges
Declaring an array of object references:
class Animal <> class Horse extends Animal < public static void main(String[] args) < /* * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed) */ Animal[] a1 = new Animal[10]; a1[0] = new Animal(); a1[1] = new Horse(); /* * Array of Animal can hold Animal and Horse and all subtype of Horse */ Animal[] a2 = new Horse[10]; a2[0] = new Animal(); //Throws ArrayStoreException at runtime. no compilation error. a2[1] = new Horse(); /* * Array of Horse can hold only Horse and its subtype (if any) and not allowed supertype of Horse nor other subtype of Animal. */ Horse[] h1 = new Horse[10]; h1[0] = new Animal(); // Not allowed h1[1] = new Horse(); /* * This can not be declared. */ Horse[] h2 = new Animal[10]; // Not allowed >>
answered Oct 16, 2015 at 10:18
3,831 10 10 gold badges 48 48 silver badges 82 82 bronze badges
incorrect comment "Array of Animal can hold Animal" and example - a2[0] = new Animal(); throws ArrayStoreException - a2 even if declared as Animal[] but initialized with new Horse[10] will not be able to hold an instance of Animal or any subtype of Animal that is not an instance of Horse or a subtype of Horse -- an array knows its element type at runtime (error if doing like a2[0] = new Animal() or a2[0] = new Cat() )
Commented Jul 27 at 9:36Thanks @user85421 , updated comment a2[0] = new Animal(); //Throws ArrayStoreException at runtime. no compilation error.
Commented Aug 12 at 13:22int[] nums1; // best practice int []nums2; int nums3[];
int[][] nums1; // best practice int [][]nums2; int[] []nums3; int[] nums4[]; int nums5[][];
int[] nums = new int[3]; // [0, 0, 0] Object[] objects = new Object[3]; // [null, null, null]
int[] nums1 = ; int[] nums2 = new int[]; Object[] objects1 = ; Object[] objects2 = new Object[];
int[] nums = new int[3]; for (int i = 0; i < nums.length; i++) < nums[i] = i; // can contain any YOUR filling strategy >Object[] objects = new Object[3]; for (int i = 0; i < objects.length; i++) < objects[i] = new Object(); // can contain any YOUR filling strategy >
int[] nums = new int[10]; Random random = new Random(); for (int i = 0; i < nums.length; i++) < nums[i] = random.nextInt(10); // random int from 0 to 9 >
int[] nums1 = IntStream.range(0, 3) .toArray(); // [0, 1, 2] int[] nums2 = IntStream.rangeClosed(0, 3) .toArray(); // [0, 1, 2, 3] int[] nums3 = IntStream.of(10, 11, 12, 13) .toArray(); // [10, 11, 12, 13] int[] nums4 = IntStream.of(12, 11, 13, 10) .sorted() .toArray(); // [10, 11, 12, 13] int[] nums5 = IntStream.iterate(0, x -> x x + 1) .toArray(); // [0, 1, 2, 3] int[] nums6 = IntStream.iterate(0, x -> x + 1) .takeWhile(x -> x < 3) .toArray(); // [0, 1, 2] int size = 3; Object[] objects1 = IntStream.range(0, size) .mapToObj(i ->new Object()) // can contain any YOUR filling strategy .toArray(Object[]::new); Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy .limit(size) .toArray(Object[]::new);
int size = 3; int randomNumberOrigin = -10; int randomNumberBound = 10 int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]
int[][] nums1 = < , , >; int[][] nums2 = new int[][]< , , >; Object[][] objects1 = < , , >; Object[][] objects2 = new Object[][]< , , >;
int[][] nums = new int[3][3]; for (int i = 0; i < nums.length; i++) < for (int j = 0; j < nums[i].length; i++) < nums[i][j] = i + j; // can contain any YOUR filling strategy >> Object[][] objects = new Object[3][3]; for (int i = 0; i < objects.length; i++) < for (int j = 0; j < nums[i].length; i++) < objects[i][j] = new Object(); // can contain any YOUR filling strategy >>
answered Jul 1, 2022 at 4:52
Dmitry Rakovets Dmitry Rakovets
579 1 1 gold badge 6 6 silver badges 15 15 bronze badges
If by "array" you meant using java.util.Arrays , you can do it with:
List number = Arrays.asList("1", "2", "3"); // Out: ["1", "2", "3"]
This one is pretty simple and straightforward to create a List . (What is difference between List and Array?) Now if you really wanted an Array you may still get one using:
String[] numberArray = Arrays.asList("1", "2", "3").toArray(new String[0]);
answered Nov 14, 2018 at 19:59
6,791 8 8 gold badges 72 72 silver badges 84 84 bronze badges
A list is not an array
Commented Jan 8, 2020 at 16:25
Sometime people mean arrays, when they want a list.
Commented Jan 8, 2020 at 20:22
And sometimes the y do not understand the difference between those two, so a good answer would at least mention that a List object is similar to an array type instance, but not the same.
Commented Mar 10, 2023 at 7:55Declare and initialize for Java 8 and later. Create a simple integer array:
int [] a1 = IntStream.range(1, 20).toArray(); System.out.println(Arrays.toString(a1)); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Create a random array for integers between [-50, 50] and for doubles [0, 1E17]:
int [] a2 = new Random().ints(15, -50, 50).toArray(); double [] a3 = new Random().doubles(5, 0, 1e17).toArray();
double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray(); System.out.println(Arrays.toString(a4)); // Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]
For String[] you must specify a constructor:
String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new); System.out.println(Arrays.toString(a5));
String [][] a6 = List.of(new String[] , new String[]) .toArray(new String[0][]); System.out.println(Arrays.deepToString(a6)); // Output: [[a, b, c], [d, e, f, g]]
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges
answered Aug 25, 2017 at 13:27
Kirill Podlivaev Kirill Podlivaev
456 7 7 silver badges 11 11 bronze badges
Are -50 and/or +50 actually included? That is, is the internal open at one or both ends?
Commented Feb 21, 2018 at 22:38
-50 is included and +50 is excluded. This information from java api "given origin (inclusive) and bound (exclusive)." I use interval declaration from wiki . So I think it will be more correct [-50, 50)
Commented Mar 21, 2018 at 9:56For creating arrays of class Objects you can use the java.util.ArrayList . to define an array:
public ArrayList arrayName; arrayName = new ArrayList();
Assign values to the array:
arrayName.add(new ClassName(class parameters go here);
Read from the array:
ClassName variableName = arrayName.get(index);
variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName
//repeats for every value in the array for (ClassName variableName : arrayName) < >//Note that using this for loop prevents you from editing arrayName
for loop that allows you to edit arrayName (conventional for loop):
for (int i = 0; i < arrayName.size(); i++)< //manipulate array here >
answered Aug 8, 2016 at 10:01
Samuel Newport Samuel Newport
304 3 3 silver badges 13 13 bronze badges
An array has two basic types.
Static Array: Fixed size array (its size should be declared at the start and can not be changed later)
Dynamic Array: No size limit is considered for this. (Pure dynamic arrays do not exist in Java. Instead, List is most encouraged.)
To declare a static array of Integer, string, float, etc., use the below declaration and initialization statements.
int[] intArray = new int[10]; String[] intArray = new int[10]; float[] intArray = new int[10]; // Here you have 10 index starting from 0 to 9
To use dynamic features, you have to use List. List is pure dynamic Array and there is no need to declare size at beginning. Below is the proper way to declare a list in Java -
ArrayList myArray = new ArrayList(); myArray.add("Value 1: something"); myArray.add("Value 2: something more");
5,536 4 4 gold badges 18 18 silver badges 37 37 bronze badges
answered Feb 21, 2020 at 5:15
745 9 9 silver badges 11 11 bronze badges
Thank you @Matheus for improving my answers. I would request you to upvote this, so this can reach more users.
Commented Mar 19, 2020 at 6:49There are a lot of answers here. I am adding a few tricky ways to create arrays (from an exam point of view it's good to know this)
int intArray[] = new int[3];
This will create an array of length 3. As it holds a primitive type, int, all values are set to 0 by default. For example,
intArray[2]; // Will return 0
int[] intArray = new int[3]; intArray[0] = 1; // Array content is now
int[] intArray = new int[];
This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:
int[] intArray = ;
int[] intArray = new int[0]; int length = intArray.length; // Will return length 0
Similar for multi-dimensional arrays
int intArray[][] = new int[2][3]; // This will create an array of length 2 and //each element contains another array of length 3. // < , > int lenght1 = intArray.length; // Will return 2 int length2 = intArray[0].length; // Will return 3
Using box brackets before the variable:
int[][] intArray = new int[2][3];
It's absolutely fine if you put one box bracket at the end:
int[] intArray [] = new int[2][4]; int[] intArray[][] = new int[2][3][4]
int [] intArray [] = new int[][] ,>; int [] intArray1 [] = new int[][] , new int [] >; int [] intArray2 [] = new int[][] ,> // All the 3 arrays assignments are valid // Array looks like ,>
It's not mandatory that each inner element is of the same size.
int [][] intArray = new int[2][]; intArray[0] = ; intArray[1] = ; //array looks like <,> int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.
You have to make sure if you are using the above syntax, that the forward direction you have to specify the values in box brackets. Else it won't compile. Some examples:
int [][][] intArray = new int[1][][]; int [][][] intArray = new int[1][2][]; int [][][] intArray = new int[1][2][3];
Another important feature is covariant
Number[] numArray = ; // java.lang.Number numArray[0] = new Float(1.5f); // java.lang.Float numArray[1] = new Integer(1); // java.lang.Integer // You can store a subclass object in an array that is declared // to be of the type of its superclass. // Here 'Number' is the superclass for both Float and Integer. Number num[] = new Float[5]; // This is also valid
IMPORTANT: For referenced types, the default value stored in the array is null.
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges answered Mar 28, 2019 at 10:05 1,844 27 27 silver badges 24 24 bronze badgesmaybe important to note that multi-dimensional arrays are actually arrays of arrays, so int[][] array = new int[2][]; is creating an array with 2 positions (that can hold an int[] array each) initialized with null (e.g. array[1] returns null ; array[1][0] throws a NullPointerException)
Commented Jul 27 at 9:21int[] x = new int[enter the size of array here];
int[] x = new int[10];
int[] x =
int[] x = ;
5,536 4 4 gold badges 18 18 silver badges 37 37 bronze badges
answered Feb 21, 2020 at 18:13
149 1 1 silver badge 7 7 bronze badges
Another way to declare and initialize ArrayList:
private List list = new ArrayList()>;
answered Aug 4, 2017 at 7:42
1,298 2 2 gold badges 15 15 silver badges 24 24 bronze badges
array != ArrayList -- and -- double < is a bad pattern, it is actually creating an anonymous class with no additional functionality (but putting two values into the list); better ways Arrays.asList() and bit newer List.of()
Commented Jul 27 at 9:27An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in the heap segment.
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[]; OR type[] var-name;
Instantiating an Array in Java
var-name = new type [size];
int intArray[]; // Declaring an array intArray = new int[20]; // Allocating memory to the array // The below line is equal to line1 + line2 int[] intArray = new int[20]; // Combining both statements in one int[] intArray = new int[]< 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 >; // Accessing the elements of the specified array for (int i = 0; i < intArray.length; i++) System.out.println("Element at index " + i + ": "+ intArray[i]);
31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges
answered Jan 21, 2020 at 1:12
4,323 36 36 silver badges 34 34 bronze badges
BTW writing int[] array is preferred over int array[]
Commented Jul 27 at 8:44
With local variable type inference you only have to specify the type once:
var values = new int[] < 1, 2, 3 >;
int[] values =31.5k 22 22 gold badges 109 109 silver badges 132 132 bronze badges answered Oct 31, 2018 at 16:38 Konstantin Spirin Konstantin Spirin 21.1k 15 15 gold badges 73 73 silver badges 91 91 bronze badges @CameronHudson Java 10 has var openjdk.java.net/jeps/286 Commented Oct 23, 2019 at 15:17
Sometimes I use this for initializing String arrays:
private static final String[] PROPS = "lastStart,storetime,tstore".split(",");
It reduces the quoting clutter at the cost of a more expensive initialization.
answered Feb 14, 2022 at 14:30 13.2k 1 1 gold badge 47 47 silver badges 68 68 bronze badgesDeclare Array: int[] arr;
Initialize Array: int[] arr = new int[10]; 10 represents the number of elements allowed in the array
Declare Multidimensional Array: int[][] arr;
Initialize Multidimensional Array: int[][] arr = new int[10][17]; 10 rows and 17 columns and 170 elements because 10 times 17 is 170.
Initializing an array means specifying the size of it.
answered Jun 10, 2019 at 0:57 111 1 1 silver badge 6 6 bronze badgespackage com.examplehub.basics; import java.util.Arrays; public class Array < public static void main(String[] args) < int[] numbers = ; /* * numbers[0] = 1 * numbers[1] = 2 * numbers[2] = 3 * numbers[3] = 4 * numbers[4] = 5 */ System.out.println("numbers[0] = " + numbers[0]); System.out.println("numbers[1] = " + numbers[1]); System.out.println("numbers[2] = " + numbers[2]); System.out.println("numbers[3] = " + numbers[3]); System.out.println("numbers[4] = " + numbers[4]); /* * Array index is out of bounds */ //System.out.println(numbers[-1]); //System.out.println(numbers[5]); /* * numbers[0] = 1 * numbers[1] = 2 * numbers[2] = 3 * numbers[3] = 4 * numbers[4] = 5 */ for (int i = 0; i < 5; i++) < System.out.println("numbers[" + i + "] = " + numbers[i]); >/* * Length of numbers = 5 */ System.out.println("length of numbers = " + numbers.length); /* * numbers[0] = 1 * numbers[1] = 2 * numbers[2] = 3 * numbers[3] = 4 * numbers[4] = 5 */ for (int i = 0; i < numbers.length; i++) < System.out.println("numbers[" + i + "] = " + numbers[i]); >/* * numbers[4] = 5 * numbers[3] = 4 * numbers[2] = 3 * numbers[1] = 2 * numbers[0] = 1 */ for (int i = numbers.length - 1; i >= 0; i--) < System.out.println("numbers[" + i + "] = " + numbers[i]); >/* * 12345 */ for (int number : numbers) < System.out.print(number); >System.out.println(); /* * [1, 2, 3, 4, 5] */ System.out.println(Arrays.toString(numbers)); String[] company = ; /* * company[0] = Google * company[1] = Facebook * company[2] = Amazon * company[3] = Microsoft */ for (int i = 0; i < company.length; i++) < System.out.println("company[" + i + "] = " + company[i]); >/* * Google * Facebook * Amazon * Microsoft */ for (String c : company) < System.out.println(c); >/* * [Google, Facebook, Amazon, Microsoft] */ System.out.println(Arrays.toString(company)); int[][] twoDimensionalNumbers = < , , , >; /* * total rows = 4 */ System.out.println("total rows = " + twoDimensionalNumbers.length); /* * row 0 length = 3 * row 1 length = 4 * row 2 length = 2 * row 3 length = 6 */ for (int i = 0; i < twoDimensionalNumbers.length; i++) < System.out.println("row " + i + " length = " + twoDimensionalNumbers[i].length); >/* * row 0 = 1 2 3 * row 1 = 4 5 6 7 * row 2 = 8 9 * row 3 = 10 11 12 13 14 15 */ for (int i = 0; i < twoDimensionalNumbers.length; i++) < System.out.print("row " + i + " = "); for (int j = 0; j < twoDimensionalNumbers[i].length; j++) < System.out.print(twoDimensionalNumbers[i][j] + " "); >System.out.println(); > /* * row 0 = [1, 2, 3] * row 1 = [4, 5, 6, 7] * row 2 = [8, 9] * row 3 = [10, 11, 12, 13, 14, 15] */ for (int i = 0; i < twoDimensionalNumbers.length; i++) < System.out.println("row " + i + " = " + Arrays.toString(twoDimensionalNumbers[i])); >/* * 1 2 3 * 4 5 6 7 * 8 9 * 10 11 12 13 14 15 */ for (int[] ints : twoDimensionalNumbers) < for (int num : ints) < System.out.print(num + " "); >System.out.println(); > /* * [1, 2, 3] * [4, 5, 6, 7] * [8, 9] * [10, 11, 12, 13, 14, 15] */ for (int[] ints : twoDimensionalNumbers) < System.out.println(Arrays.toString(ints)); >int length = 5; int[] array = new int[length]; for (int i = 0; i < 5; i++) < array[i] = i + 1; >/* * [1, 2, 3, 4, 5] */ System.out.println(Arrays.toString(array)); > >