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]; // each element of the array is initialised to 0
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]; // each element is initialised to null
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"};
🌐
W3Schools
w3schools.com › java › java_arrays.asp
Java Arrays
Java Examples Java Videos Java ... Q&A Java Certificate ... Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value....
🌐
Oracle
docs.oracle.com › javase › tutorial › java › nutsandbolts › arrays.html
Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)
See Java Language Changes for a ... enhancements, and removed or deprecated options for all JDK releases. An array is a container object that holds a fixed number of values of a single type....
Discussions

How do I declare and initialize an array in Java? - Stack Overflow
Both the outer arrays and the inner arrays (and those in between, if they exist) are just regular arrays. 2017-07-18T15:19:10.57Z+00:00 ... Perhaps worth noting that the second (less-preferred) form stems from C/C++. This might be the reason why it is supported in Java. More on stackoverflow.com
🌐 stackoverflow.com
How do I determine whether an array contains a particular value in Java? - Stack Overflow
Odd, NetBeans claims that ... the Contains doesn't work since it just has one element; the int array. 2010-11-13T13:15:59.703Z+00:00 ... Nyerguds: indeed, this does not work for primitives. In java primitive types can't be generic.... More on stackoverflow.com
🌐 stackoverflow.com
[JAVA] Arrays. ELI5 please.
Think of an array kind of like the cabinets in your kitchen, all in a line. Each cabinet has a specific location in your kitchen. If you were to tell someone where to find the cups when they're over at your house, you might say "They're in the cabinet over the stove, on the left". Your cabinets are used for storage of your dishes and other kitchen items, and they can be organized a certain way to make finding what you need easier. A one dimensional array is essentially a line of "cabinets" that you can store data in, where each cabinet has its own index, or location, that you reference it by. An array can be unsorted or sorted, and many algorithms exist to sort them, with some being fast, and some requiring very little extra memory. Something like .length or .size simply returns the amount of cabinets in your kitchen, or in programming terms, the number of spaces in your array. You can also make a two dimensional array, which you can think of like a grid of cubby holes at a pre-school, or more mathematically, as a matrix. These work exactly the same as a 1D array, but each element has two indexes instead of one, like an X and Y coordinate on graph paper. An array is stored linearly in memory and its indexes usually start at zero. The following example is how to create an array and fill it with numbers using Java. int[] myArray = new int[10]; //Creates an array of size 10 to store integers for(int i = 0; i < myArray.length; i++) { myArray[i] = i; } //myArray.length = 10, i = 0, loop until i > 9 //On each iteration, myArray at index i will contain the current value of i //When this loop finishes, myArray will contain 0,1,2,3,4,5,6,7,8,9 in that order Arrays are the simplest data structure you will be dealing with, but they are incredibly useful and have a huge amount of applications. Many complex data structures use arrays in some way. For example, you can represent a graph structure as a matrix, or two dimensional array, of connected edges. You can efficiently sort data without using any extra memory using a heap structure, which at its most basic form is just an array that can be sorted in place. Once you grasp arrays, you will be able to grasp the more complex structures much more easily. If there is anything else I can help you with, please let me know. More on reddit.com
🌐 r/learnprogramming
14
3
May 13, 2013
Java Arrays
Arrays are just a convenient way of storing multiple things. Think of arrays as sacks of balls - you could have just a single ball: int myBall = 42; Or five: int myBall1 = 42; int myBall2 = 43; int myBall3 = 44; int myBall4 = 45; int myBall5 = 46; But what if you want, say, a hundred balls? Things get out of hand rather quickly. Instead of having these loose balls lying around, we can have an array of balls: int[] balls1 = new int[100]; // Holds a hundred balls int[] balls2 = new int[5]; // Holds five balls But wait, there's more! Arrays work like lockers - each "slot" in an array has an index. The first one in an array is always at index 0, the second one at index 1 and so on. To populate the five-item array, we do this: int[] balls = new int[5]; balls[0] = 42; balls[1] = 43; balls[2] = 44; balls[3] = 45; balls[4] = 46; We can retrieve them just as well: int thirdBall = balls[2]; // Now thirdBall is 44 Why use arrays, then, if we can just declare as many variables as we need? Well, it makes life a lot easier. Say you want a hundred numbers and you want them to run from 1 to 100. You could do it like this: int num1 = 1; int num2 = 2; ... int num100 = 100; Or, you could do this: int[] nums = new int[100]; for(int i = 0; i < 100; ++i) nums[i] = i + 1; Now, after all this: what specifically you have trouble understanding? More on reddit.com
🌐 r/learnjava
11
10
March 29, 2017
🌐
GeeksforGeeks
geeksforgeeks.org › java › arrays-in-java
Arrays in Java - GeeksforGeeks
An array is a collection of elements of the same data type stored in contiguous memory locations. It allows multiple values to be stored under a single name and accessed using an index.
Published   3 weeks ago
🌐
Baeldung
baeldung.com › home › java › java array › arrays in java: a reference guide
Arrays in Java: A Reference Guide | Baeldung
July 24, 2024 - According to the Java documentation, an array is an object containing a fixed number of values of the same type. The elements of an array are indexed, which means we can access them with numbers (called indices).
Top answer
1 of 16
3264

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]; // each element of the array is initialised to 0
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]; // each element is initialised to null
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"};
2 of 16
336

There are two types of array.

One Dimensional 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 = {1,2,3,4,5};

Or (less preferred)

int num[] = {1, 2, 3, 4, 5};

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

int[][] num = new int[5][2];

Or

int num[][] = new int[5][2];

Or

int[] num[] = new int[5][2];

Initialization

 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;

Or

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

Ragged Array (or Non-rectangular Array)

 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={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };

For Accessing:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}

Alternatively:

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

🌐
Programiz
programiz.com › java-programming › arrays
Java Array (With Examples)
Become a certified Java programmer. Try Programiz PRO! ... An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. ... Here, the above array cannot store more than 100 names.
Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › java › java_arrays.htm
Java - Arrays
Java provides a data structure called the array, which stores a fixed-size sequential collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection ...
Top answer
1 of 16
3430
Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


Since java-8 you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
2 of 16
465

Concise update for Java SE 9

Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.

private static final Set<String> VALUES = Set.of(
    "AB","BC","CD","AE"
);

"Given String s, is there a good way of testing whether VALUES contains s?"

VALUES.contains(s)

O(1).

The right type, immutable, O(1) and concise. Beautiful.*

Original answer details

Just to clear the code up to start with. We have (corrected):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

Reference arrays are still bad and we want a set:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)

(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)

🌐
Simplilearn
simplilearn.com › home › resources › software development › java tutorial for beginners › arrays in java: declare, define, and access array
Arrays in Java: Declare, Define, and Access Array [Updated]
January 26, 2025 - The article gives a clear insight into the basics of arrays in java, how to define and declare an array in java, type of arrays with an example. So, click here to learn more
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Arrays.html
Arrays (Java Platform SE 8 )
3 weeks ago - Java™ Platform Standard Ed. 8 ... This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The methods in this class all throw a NullPointerException, if the specified array ...
🌐
Oracle
docs.oracle.com › javase › specs › jls › se7 › html › jls-10.html
Chapter 10. Arrays
3 weeks ago - In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2).
🌐
DataCamp
datacamp.com › doc › java › defining-and-initializing-arrays
Java Defining and Initializing Arrays
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... In Java, arrays are a fundamental data structure that allows you to store multiple values of the same type in a single variable.
🌐
Sentry
sentry.io › sentry answers › java › how do i declare and initialize an array in java?
How do I declare and initialize an array in Java? | Sentry
The int[] myArray says that we want to declare a new variable called myArray that has the type of an array of integers.
🌐
Jenkov
jenkov.com › tutorials › java › arrays.html
Java Arrays
A Java array is a collection of variables of the same data type. Each variable in a Java Array is called an element. You can iterate over all elements of a Java array, or access each element individually via its array index.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-create-an-array-in-java
How to Create an Array in Java – Array Declaration Example
March 16, 2023 - In Java, you can create multi-dimensional arrays with two or more dimensions. A two-dimensional array is an array of arrays, while a three-dimensional array is an array of arrays of arrays, and so on. To create a two-dimensional array in Java, you first declare the array variable using the syntax datatype[][] arrayName, where datatype is the type of data the array will hold, and arrayName is the name of the array.
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit7-Arrays › topic-7-1-array-basics.html
7.1. Array Creation and Access — CS Java
An array is a block of memory that stores a collection of data items (elements) of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don’t need to name each one. Instead you use the array name and ...
🌐
Runestone Academy
runestone.academy › ns › books › published › apcsareview › ArrayBasics › abasics.html
8.1. Arrays in Java — AP CSA Java Review - Obsolete
An array is consecutive storage for multiple items of the same type. You can store a value in an array using an index (location in the array). You can get a value from an array using an index. An array is like a row of lockers, except that you can’t cram lots of stuff into it.
🌐
Princeton CS
introcs.cs.princeton.edu › java › 14array
1.4 Arrays
April 8, 2020 - We refer to an array element by putting its index in square brackets after the array name: the code a[i] refers to element i of array a[]. For example, the following code makes an array of n numbers of type double, all initialized to 0: ArrayExamples.java contains typical examples of using ...
🌐
CodeChef
codechef.com › blogs › arrays-in-java
Arrays in Java (With Examples and Practice)
August 7, 2024 - Learn about Arrays, the most common data structure in Java. Understand how to write code using examples and practice problems.