Related Questions
Sponsored Content
45 Answered Questions
[SOLVED] How do I check if an array includes an object in JavaScript?
- 2008-10-25 22:14:40
- brad
- 2253472 View
- 3461 Score
- 45 Answer
- Tags: javascript arrays browser javascript-objects
30 Answered Questions
[SOLVED] How to append something to an array?
- 2008-12-09 00:20:05
- interstar
- 2486898 View
- 2895 Score
- 30 Answer
- Tags: javascript arrays append
23 Answered Questions
[SOLVED] Why is it faster to process a sorted array than an unsorted array?
- 2012-06-27 13:51:36
- GManNickG
- 1311764 View
- 22615 Score
- 23 Answer
- Tags: java c++ performance optimization branch-prediction
76 Answered Questions
[SOLVED] How do I remove a particular element from an array in JavaScript?
- 2011-04-23 22:17:18
- Walker
- 5510221 View
- 6835 Score
- 76 Answer
- Tags: javascript arrays
39 Answered Questions
[SOLVED] Loop through an array in JavaScript
- 2010-06-10 00:04:27
- Mark Szymanski
- 3154959 View
- 2641 Score
- 39 Answer
- Tags: javascript arrays loops for-loop
33 Answered Questions
[SOLVED] Create ArrayList from array
- 2008-10-01 14:38:32
- Ron Tuffin
- 1339782 View
- 3202 Score
- 33 Answer
- Tags: java arrays arraylist type-conversion
9 Answered Questions
31 Answered Questions
[SOLVED] For-each over an array in JavaScript?
- 2012-02-17 13:51:48
- Dante1986
- 3570898 View
- 4061 Score
- 31 Answer
- Tags: javascript arrays loops foreach iteration
78 Answered Questions
[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?
- 2008-09-02 20:14:29
- user4315
- 1735008 View
- 5750 Score
- 78 Answer
- Tags: java methods parameter-passing pass-by-reference pass-by-value
18 Answered Questions
[SOLVED] How do I empty an array in JavaScript?
- 2009-08-05 09:08:39
- akano1
- 2115137 View
- 2199 Score
- 18 Answer
- Tags: javascript arrays
21 comments
@Sylhare 2018-11-14 19:59:02
You can also do it with
java.util.Arrays
:This one is pretty simple and straightforward. I didn't see it in other answers so I thought I could add it.
@Konstantin Spirin 2018-10-31 16:38:04
With local variable type inference you only have to specify type once:
or
@Oleksandr 2018-02-21 12:45:00
In Java 9
Using different
IntStream.iterate
andIntStream.takeWhile
methods:In Java 10
Using the Local Variable Type Inference:
@Chamly Idunil 2018-03-08 18:21:39
In Java 8 you can use like this.
@Kirill Podlivaev 2017-08-25 13:27:27
Declare and initialize for Java 8 and later. Create a simple integer array:
Create a random array for integers between [-50, 50] and for doubles [0, 1E17]:
Power-of-two sequence:
For String[] you must specify a constructor:
Multidimensional arrays:
@Peter Mortensen 2018-02-21 22:38:19
Are -50 and/or +50 actually included? That is, is the internal open at one or both ends?
@Kirill Podlivaev 2018-03-21 09:56:34
-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)
@glmxndr 2009-07-29 14:25:23
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:
For classes, for example
String
, it's the same:The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.
@Quazi Irfan 2015-04-10 03:23:18
What's the purpose of having both the second and third way to do it?
@Skylar Ittner 2015-04-16 17:44:44
@iamcreasy It looks like the second way doesn't work with return statements.
return {1,2,3}
gives an error, whilereturn new int[]{1,2,3}
works fine (assuming of course that your function returns an integer array).@Quazi Irfan 2015-04-18 04:41:45
@SkylarMT But we can still use the first way to use with return statement.
@Skylar Ittner 2015-04-20 06:09:02
@iamcreasy I recently wrote a function that returned an array of ints. If an error happened inside the function, I wanted it to return a certain value, but the function needed to return an array. Which way works for a one-liner return statement? Only the third one.
@peterflynn 2015-06-03 19:18:17
It's not true that "array literals cannot be used for re-assigning an array" - the third syntax can be used to re-assign an array at any time.
@Jezzamon 2015-07-26 11:43:43
The contents of an array cannot be set using an array literal. Array literals will create a new array each time as opposed to modifying the contents of the previous one. You can store this in an existing variable if you want, so the new array will replace the previous array.
@Khaled.K 2015-10-21 12:22:56
This answer seem incomplete to me, it is missing the part on Array of classes\objects, using
String
or primitive-datatype-autoboxing to demonstrate the case of classes is misleading.@M. Usman Khan 2016-01-11 13:53:02
what if i have a parameter in the constructor? e.g. I have constructor public MyClass(int something){}; and I want to initialize array MyClass[] objs = new MyClass[3] (88);
@apadana 2016-05-20 20:49:41
The 2nd form also can't be used to pass into a function. It gives an error. The 3rd form is fine. But I am not sure why the 2nd form can't be used for return or passing to a function? I would like to understand what happens behind the scene.
@teukkam 2016-10-18 09:55:57
@apadana In the second case you are creating an anonymous object which is only defined in the enclosing scope (function or whatever). After returning it to the caller, it is no longer valid. Using the new keyword you allocate the new object from the heap and it is valid outside the defining scope.
@MrAP 2017-04-06 21:47:03
What do you mean by: "but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array"?
@djangofan 2017-05-29 17:54:52
Why does this work? public class Test { public static void main(String args[]) { final double[] doubles = {2.3, 2.4}; final long[] longs = {2,4L,6,8}; }}
@Habeeb Perwad 2018-02-15 10:52:23
The vote shows 2012. who will make it 2018?
@www-0av-Com 2018-04-04 12:06:05
For newbies, state why you are giving triplicate answers. As a newbie, I thought I needed all 3 lines! Not impressed that first answer gets all the votes, even tho misleading. @codecubed has a much better simple answer.
@Anirudh 2009-07-29 14:28:14
There are various ways in which you can declare an array in Java:
You can find more information in the Sun tutorial site and the JavaDoc.
@Clement.Xu 2017-08-04 07:42:26
Another way to declare and initialize ArrayList:
@Samuel Newport 2016-08-08 10:01:28
For creating arrays of class Objects you can use the
java.util.ArrayList
. to define an array:Assign values to the array:
Read from the array:
Note:
variableName
is a reference to the array meaning that manipulatingvariableName
will manipulatearrayName
for loops:
for loop that allows you to edit
arrayName
(conventional for loop):@codecubed 2016-01-28 19:19:41
There are two main ways to make an array:
This one, for an empty array:
And this one, for an initialized array:
You can also make multidimensional arrays, like this:
@ravi 2015-10-16 10:18:50
Declaring an array of object references:
@Isabella Engineer 2013-07-09 21:59:39
There are two types of array.
One Dimensional Array
Syntax for default values:
Or (less preferred)
Syntax with values given (variable/field initialization):
Or (less preferred)
Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.
Multidimensional array
Declaration
Or
Or
Initialization
Or
Ragged Array (or Non-rectangular Array)
So here we are defining columns explicitly.
Another Way:
For Accessing:
Alternatively:
Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials
@vipin8169 2017-02-19 00:25:01
Won't the first one lead to a null/empty array, instead of array with default values?
@AdamIJK 2017-04-26 11:26:38
I agree on that point, and we can add one more feature, we can change the size dynamically.
@Tim M. 2017-07-18 15:19:10
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.
@TreyMcGowan 2015-11-19 17:43:49
@Bono 2015-11-19 19:24:16
While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run.
@Khaled.K 2015-10-21 13:39:47
Array is a sequential list of items
If it's an object, then it's the same concept
In case of objects, you need to either assign it to
null
to initialize them usingnew Type(..)
, classes likeString
andInteger
are special cases that will be handled as followingIn general you can create arrays that's
M
dimensionalIt's worthy to note that creating an
M
dimensional array is expensive in terms of Space. Since when you create anM
dimensional array withN
on all the dimensions, The total size of the array is bigger thanN^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@HyperNeutrino 2015-05-23 19:56:19
Take the primitive type
int
for example. There are several ways to declare andint
array:where in all of these, you can use
int i[]
instead ofint[] i
.With reflection, you can use
(Type[]) Array.newInstance(Type.class, capacity);
Note that in method parameters,
...
indicatesvariable arguments
. Essentially, any number of parameters is fine. It's easier to explain with code:Inside the method,
varargs
is treated as a normalint[]
.Type...
can only be used in method parameters, soint... i = new int[] {}
will not compile.Note that when passing an
int[]
to a method (or any otherType[]
), you cannot use the third way. In the statementint[] i = *{a, b, c, d, etc}*
, the compiler assumes that the{...}
means anint[]
. But that is because you are declaring a variable. When passing an array to a method, the declaration must either benew Type[capacity]
ornew Type[] {...}
.Multidimensional Arrays
Multidimensional arrays are much harder to deal with. Essentially, a 2D array is an array of arrays.
int[][]
means an array ofint[]
s. The key is that if anint[][]
is declared asint[x][y]
, the maximum index isi[x-1][y-1]
. Essentially, a rectangularint[3][5]
is:@Muhammad Suleman 2015-01-20 11:54:02
If you want to create arrays using reflections then you can do like this:
@Nate 2009-07-29 14:29:17
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.
@Chet 2009-07-29 14:31:04
I 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.
@wener 2014-03-05 12:43:42
Google style suggest this too.
@Jeroen Vannevel 2015-03-19 01:46:01
Note that
int[] a, b;
will not be the same asint a[], b;
, a mistake easy to make if you use the latter form.@Amit Bhandari 2013-06-04 06:02:49
The following shows the declaration of an array, but the array is not initialized:
The following shows the declaration as well as initialization of the array:
Now, the following also shows the declaration as well as initialization of the array:
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[]{1,2,3};" then this is how anonymous array-object can be created.
If we just write:
this is not declaration of array, but the following statement makes the above declaration complete:
@Jon Skeet 2015-02-21 23:08:38
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.
@Jon Skeet 2015-02-21 23:12:24
Also, the first snippet does initialize the array - it is guaranteed to have the value 0 for every array element.
@Chet 2009-07-29 14:29:56
I find it is helpful if you understand each part:
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 likeType[][]
(the array type of Type[]). The keywordnew
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 typeType
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
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.
@Cookie Monster 2018-06-28 10:26:01
So it is not necessary to include
int[] name = new int[5]
?@Dave 2009-07-29 15:56:20
Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
@CyprUS 2015-08-27 00:05:03
what is the "<>" called in the list that you created ?
@Heimdall 2018-11-29 14:27:51
@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@Thomas Owens 2009-07-29 14:25:31
Alternatively,
That declares an array called
arrayName
of size 10 (you have elements 0 through 9 to use).@Anti Earth 2012-10-03 04:20:25
What is the standard for which to use? I've only just discovered the former, and I find it horrifically misleading :|
@Celeritas 2013-08-09 04:50:59
For 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.
@Muhammad Suleman 2015-05-05 11:17:28
For a side note: A language having more than one semantics for declaring one thing meaning bad language design.