Creating an unreferenced array in Java? [duplicate] - java

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]; // 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"};

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

Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
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.

There 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[] {"a", "b"};
You can find more information in the Sun tutorial site and the JavaDoc.

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

The 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 = {1,2,3};
Now, the following also shows the declaration as well as initialization of the array:
int[] myIntArray = new int[]{1,2,3};
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:
int[] myIntArray;
this is not declaration of array, but the following statement makes the above declaration complete:
myIntArray=new int[3];

Alternatively,
// 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).

Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );

There 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 = {1,2,3,4 ...};
You can also make multidimensional arrays, like this:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};

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[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
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 = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
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 = *{a, b, c, d, etc}*, 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
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]

In Java 9
Using different IntStream.iterate and IntStream.takeWhile methods:
int[] a = IntStream.iterate(10, x -> x <= 100, 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]
In Java 10
Using the Local Variable Type Inference:
var letters = new String[]{"A", "B", "C"};

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);

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 );

If by "array" you meant using java.util.Arrays, you can do it with:
List<String> number = Arrays.asList("1", "2", "3");
// Out: ["1", "2", "3"]
This one is pretty simple and straightforward.

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();
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
}
}

Array 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({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
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
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ 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

Declaration
One Dimensional Array
int[] nums1; // best practice
int []nums2;
int nums3[];
Multidimensional array
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
Declaration and Initialization
One Dimensional Array
With default values
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
With array literal
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};
Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
With loop for
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
}
With loop for and Random
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
}
With Stream (since Java 8)
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 <= 3, 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);
With Random and Stream (since Java 8)
int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
Multidimensional array
With default value
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]]
With array literal
int[][] nums1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] nums2 = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Object[][] objects1 = {
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
With loop for
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
}
}

Declare 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();
Power-of-two sequence:
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));
Multidimensional arrays:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]

For creating arrays of class Objects you can use the java.util.ArrayList. to define an array:
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
Assign values to the array:
arrayName.add(new ClassName(class parameters go here);
Read from the array:
ClassName variableName = arrayName.get(index);
Note:
variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName
for loops:
//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
}

Another way to declare and initialize ArrayList:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};

There 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)
Declare and define an array
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
Using box brackets [] before the variable name
int[] intArray = new int[3];
intArray[0] = 1; // Array content is now {1, 0, 0}
Initialise and provide data to the array
int[] intArray = new int[]{1, 2, 3};
This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:
int[] intArray = {1, 2, 3, 4};
An array of length 0
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.
// { {0,0,0},{0,0,0} }
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]
Some examples
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
It's not mandatory that each inner element is of the same size.
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
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 = {1,2,3,4}; // 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.

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<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");

An 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];
For example,
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]);
Ref: Arrays in Java

With local variable type inference you only have to specify the type once:
var values = new int[] { 1, 2, 3 };
Or
int[] values = { 1, 2, 3 }

int[] x = new int[enter the size of array here];
Example:
int[] x = new int[10];
Or
int[] x = {enter the elements of array here];
Example:
int[] x = {10, 65, 40, 5, 48, 31};

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.

Declare 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.

package com.examplehub.basics;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
/*
* 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 = {"Google", "Facebook", "Amazon", "Microsoft"};
/*
* 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 = {
{1, 2, 3},
{4, 5, 6, 7},
{8, 9},
{10, 11, 12, 13, 14, 15}
};
/*
* 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));
}
}
Source from examplehub/java

One another full example with a movies class:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}

It's very easy to declare and initialize an array.
For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:
a)
int[] a = new int[5];
or
b)
int[] a = {1, 2, 3, 4, 5};
so the basic pattern is for initialization and declaration by method a) is:
datatype[] arrayname = new datatype[requiredarraysize];
datatype should be in lower case.
So the basic pattern is for initialization and declaration by method a is:
If it's a string array:
String[] a = {"as", "asd", "ssd"};
If it's a character array:
char[] a = {'a', 's', 'w'};
For float double, the format of array will be same as integer.
For example:
double[] a = {1.2, 1.3, 12.3};
but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.
But when you do it by "method b" you will not have to enter the values manually.

Related

creating an instance variable which is an array of references to an object [duplicate]

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]; // 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"};
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
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
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.
There 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[] {"a", "b"};
You can find more information in the Sun tutorial site and the JavaDoc.
I 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 = {1, 2, 3, 4, 5};
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.
The 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 = {1,2,3};
Now, the following also shows the declaration as well as initialization of the array:
int[] myIntArray = new int[]{1,2,3};
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:
int[] myIntArray;
this is not declaration of array, but the following statement makes the above declaration complete:
myIntArray=new int[3];
Alternatively,
// 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).
Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
There 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 = {1,2,3,4 ...};
You can also make multidimensional arrays, like this:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
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[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
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 = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
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 = *{a, b, c, d, etc}*, 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
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]
In Java 9
Using different IntStream.iterate and IntStream.takeWhile methods:
int[] a = IntStream.iterate(10, x -> x <= 100, 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]
In Java 10
Using the Local Variable Type Inference:
var letters = new String[]{"A", "B", "C"};
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);
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 );
If by "array" you meant using java.util.Arrays, you can do it with:
List<String> number = Arrays.asList("1", "2", "3");
// Out: ["1", "2", "3"]
This one is pretty simple and straightforward.
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();
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
}
}
Array 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({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
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
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ 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
Declaration
One Dimensional Array
int[] nums1; // best practice
int []nums2;
int nums3[];
Multidimensional array
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
Declaration and Initialization
One Dimensional Array
With default values
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
With array literal
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};
Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
With loop for
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
}
With loop for and Random
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
}
With Stream (since Java 8)
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 <= 3, 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);
With Random and Stream (since Java 8)
int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
Multidimensional array
With default value
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]]
With array literal
int[][] nums1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] nums2 = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Object[][] objects1 = {
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
With loop for
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
}
}
Declare 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();
Power-of-two sequence:
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));
Multidimensional arrays:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
For creating arrays of class Objects you can use the java.util.ArrayList. to define an array:
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
Assign values to the array:
arrayName.add(new ClassName(class parameters go here);
Read from the array:
ClassName variableName = arrayName.get(index);
Note:
variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName
for loops:
//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
}
Another way to declare and initialize ArrayList:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
There 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)
Declare and define an array
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
Using box brackets [] before the variable name
int[] intArray = new int[3];
intArray[0] = 1; // Array content is now {1, 0, 0}
Initialise and provide data to the array
int[] intArray = new int[]{1, 2, 3};
This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:
int[] intArray = {1, 2, 3, 4};
An array of length 0
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.
// { {0,0,0},{0,0,0} }
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]
Some examples
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
It's not mandatory that each inner element is of the same size.
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
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 = {1,2,3,4}; // 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.
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<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
An 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];
For example,
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]);
Ref: Arrays in Java
With local variable type inference you only have to specify the type once:
var values = new int[] { 1, 2, 3 };
Or
int[] values = { 1, 2, 3 }
int[] x = new int[enter the size of array here];
Example:
int[] x = new int[10];
Or
int[] x = {enter the elements of array here];
Example:
int[] x = {10, 65, 40, 5, 48, 31};
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.
Declare 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.
package com.examplehub.basics;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
/*
* 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 = {"Google", "Facebook", "Amazon", "Microsoft"};
/*
* 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 = {
{1, 2, 3},
{4, 5, 6, 7},
{8, 9},
{10, 11, 12, 13, 14, 15}
};
/*
* 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));
}
}
Source from examplehub/java
One another full example with a movies class:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}
It's very easy to declare and initialize an array.
For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:
a)
int[] a = new int[5];
or
b)
int[] a = {1, 2, 3, 4, 5};
so the basic pattern is for initialization and declaration by method a) is:
datatype[] arrayname = new datatype[requiredarraysize];
datatype should be in lower case.
So the basic pattern is for initialization and declaration by method a is:
If it's a string array:
String[] a = {"as", "asd", "ssd"};
If it's a character array:
char[] a = {'a', 's', 'w'};
For float double, the format of array will be same as integer.
For example:
double[] a = {1.2, 1.3, 12.3};
but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.
But when you do it by "method b" you will not have to enter the values manually.

Am I allowed to assign values to an array after declaring it, or do I have to do it in one line? [duplicate]

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]; // 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"};
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
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
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.
There 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[] {"a", "b"};
You can find more information in the Sun tutorial site and the JavaDoc.
I 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 = {1, 2, 3, 4, 5};
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.
The 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 = {1,2,3};
Now, the following also shows the declaration as well as initialization of the array:
int[] myIntArray = new int[]{1,2,3};
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:
int[] myIntArray;
this is not declaration of array, but the following statement makes the above declaration complete:
myIntArray=new int[3];
Alternatively,
// 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).
Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
There 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 = {1,2,3,4 ...};
You can also make multidimensional arrays, like this:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
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[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
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 = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
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 = *{a, b, c, d, etc}*, 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
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]
In Java 9
Using different IntStream.iterate and IntStream.takeWhile methods:
int[] a = IntStream.iterate(10, x -> x <= 100, 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]
In Java 10
Using the Local Variable Type Inference:
var letters = new String[]{"A", "B", "C"};
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);
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 );
If by "array" you meant using java.util.Arrays, you can do it with:
List<String> number = Arrays.asList("1", "2", "3");
// Out: ["1", "2", "3"]
This one is pretty simple and straightforward.
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();
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
}
}
Array 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({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
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
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ 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
Declaration
One Dimensional Array
int[] nums1; // best practice
int []nums2;
int nums3[];
Multidimensional array
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
Declaration and Initialization
One Dimensional Array
With default values
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
With array literal
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};
Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
With loop for
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
}
With loop for and Random
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
}
With Stream (since Java 8)
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 <= 3, 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);
With Random and Stream (since Java 8)
int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
Multidimensional array
With default value
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]]
With array literal
int[][] nums1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] nums2 = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Object[][] objects1 = {
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
With loop for
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
}
}
Declare 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();
Power-of-two sequence:
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));
Multidimensional arrays:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
For creating arrays of class Objects you can use the java.util.ArrayList. to define an array:
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
Assign values to the array:
arrayName.add(new ClassName(class parameters go here);
Read from the array:
ClassName variableName = arrayName.get(index);
Note:
variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName
for loops:
//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
}
Another way to declare and initialize ArrayList:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
There 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)
Declare and define an array
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
Using box brackets [] before the variable name
int[] intArray = new int[3];
intArray[0] = 1; // Array content is now {1, 0, 0}
Initialise and provide data to the array
int[] intArray = new int[]{1, 2, 3};
This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:
int[] intArray = {1, 2, 3, 4};
An array of length 0
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.
// { {0,0,0},{0,0,0} }
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]
Some examples
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
It's not mandatory that each inner element is of the same size.
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
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 = {1,2,3,4}; // 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.
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<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
An 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];
For example,
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]);
Ref: Arrays in Java
With local variable type inference you only have to specify the type once:
var values = new int[] { 1, 2, 3 };
Or
int[] values = { 1, 2, 3 }
int[] x = new int[enter the size of array here];
Example:
int[] x = new int[10];
Or
int[] x = {enter the elements of array here];
Example:
int[] x = {10, 65, 40, 5, 48, 31};
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.
Declare 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.
package com.examplehub.basics;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
/*
* 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 = {"Google", "Facebook", "Amazon", "Microsoft"};
/*
* 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 = {
{1, 2, 3},
{4, 5, 6, 7},
{8, 9},
{10, 11, 12, 13, 14, 15}
};
/*
* 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));
}
}
Source from examplehub/java
One another full example with a movies class:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}
It's very easy to declare and initialize an array.
For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:
a)
int[] a = new int[5];
or
b)
int[] a = {1, 2, 3, 4, 5};
so the basic pattern is for initialization and declaration by method a) is:
datatype[] arrayname = new datatype[requiredarraysize];
datatype should be in lower case.
So the basic pattern is for initialization and declaration by method a is:
If it's a string array:
String[] a = {"as", "asd", "ssd"};
If it's a character array:
char[] a = {'a', 's', 'w'};
For float double, the format of array will be same as integer.
For example:
double[] a = {1.2, 1.3, 12.3};
but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.
But when you do it by "method b" you will not have to enter the values manually.

Java NIO Selectors- multiple Selectors [duplicate]

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]; // 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"};
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
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
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.
There 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[] {"a", "b"};
You can find more information in the Sun tutorial site and the JavaDoc.
I 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 = {1, 2, 3, 4, 5};
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.
The 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 = {1,2,3};
Now, the following also shows the declaration as well as initialization of the array:
int[] myIntArray = new int[]{1,2,3};
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:
int[] myIntArray;
this is not declaration of array, but the following statement makes the above declaration complete:
myIntArray=new int[3];
Alternatively,
// 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).
Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
There 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 = {1,2,3,4 ...};
You can also make multidimensional arrays, like this:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
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[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
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 = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
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 = *{a, b, c, d, etc}*, 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
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]
In Java 9
Using different IntStream.iterate and IntStream.takeWhile methods:
int[] a = IntStream.iterate(10, x -> x <= 100, 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]
In Java 10
Using the Local Variable Type Inference:
var letters = new String[]{"A", "B", "C"};
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);
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 );
If by "array" you meant using java.util.Arrays, you can do it with:
List<String> number = Arrays.asList("1", "2", "3");
// Out: ["1", "2", "3"]
This one is pretty simple and straightforward.
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();
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
}
}
Array 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({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
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
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ 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
Declaration
One Dimensional Array
int[] nums1; // best practice
int []nums2;
int nums3[];
Multidimensional array
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
Declaration and Initialization
One Dimensional Array
With default values
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
With array literal
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};
Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
With loop for
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
}
With loop for and Random
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
}
With Stream (since Java 8)
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 <= 3, 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);
With Random and Stream (since Java 8)
int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
Multidimensional array
With default value
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]]
With array literal
int[][] nums1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] nums2 = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Object[][] objects1 = {
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
With loop for
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
}
}
Declare 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();
Power-of-two sequence:
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));
Multidimensional arrays:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
For creating arrays of class Objects you can use the java.util.ArrayList. to define an array:
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
Assign values to the array:
arrayName.add(new ClassName(class parameters go here);
Read from the array:
ClassName variableName = arrayName.get(index);
Note:
variableName is a reference to the array meaning that manipulating variableName will manipulate arrayName
for loops:
//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
}
Another way to declare and initialize ArrayList:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
There 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)
Declare and define an array
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
Using box brackets [] before the variable name
int[] intArray = new int[3];
intArray[0] = 1; // Array content is now {1, 0, 0}
Initialise and provide data to the array
int[] intArray = new int[]{1, 2, 3};
This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:
int[] intArray = {1, 2, 3, 4};
An array of length 0
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.
// { {0,0,0},{0,0,0} }
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]
Some examples
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
It's not mandatory that each inner element is of the same size.
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
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 = {1,2,3,4}; // 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.
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<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
An 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];
For example,
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]);
Ref: Arrays in Java
With local variable type inference you only have to specify the type once:
var values = new int[] { 1, 2, 3 };
Or
int[] values = { 1, 2, 3 }
int[] x = new int[enter the size of array here];
Example:
int[] x = new int[10];
Or
int[] x = {enter the elements of array here];
Example:
int[] x = {10, 65, 40, 5, 48, 31};
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.
Declare 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.
package com.examplehub.basics;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
/*
* 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 = {"Google", "Facebook", "Amazon", "Microsoft"};
/*
* 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 = {
{1, 2, 3},
{4, 5, 6, 7},
{8, 9},
{10, 11, 12, 13, 14, 15}
};
/*
* 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));
}
}
Source from examplehub/java
One another full example with a movies class:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}
It's very easy to declare and initialize an array.
For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:
a)
int[] a = new int[5];
or
b)
int[] a = {1, 2, 3, 4, 5};
so the basic pattern is for initialization and declaration by method a) is:
datatype[] arrayname = new datatype[requiredarraysize];
datatype should be in lower case.
So the basic pattern is for initialization and declaration by method a is:
If it's a string array:
String[] a = {"as", "asd", "ssd"};
If it's a character array:
char[] a = {'a', 's', 'w'};
For float double, the format of array will be same as integer.
For example:
double[] a = {1.2, 1.3, 12.3};
but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.
But when you do it by "method b" you will not have to enter the values manually.

Accessing Arrays via an identifier variable - JAVA

I am trying to access an array based on a number. Let me explain:
stringBuilder.append(array1[i]);
but I have 4 arrays, I would like to access the array like this:
int i;
int aNum;
stringBuilder.append(array(aNum)[i]);
so the array number selected depends on the value of aNum (1 - 4) where [i] being the location of the array (0 - n)
This code however doesn't work. Any ideas? Tried looking on google but can't find the correct code I need. It does seem simple but can't find the solution. Hope it makes sense!
You are referring to a two-dimensional array, which is an array of arrays. Here is an example:
/**
<P>{#code java TwoDArray}</P>
**/
public class TwoDArray {
public static final void main(String[] ignored) {
//Setup
int[][] intArrArr = new int[4][];
intArrArr[0] = new int[] {1, 2, 3, 4};
intArrArr[1] = new int[] {5, 6, 7, 8};
intArrArr[2] = new int[] {9, 10, 11, 12};
intArrArr[3] = new int[] {13, 14, 15, 16};
StringBuilder stringBuilder = new StringBuilder();
//Go
int indexOfIntInSelectedArray = 1; //The second element...
int indexOfArray = 2; //...in the third array.
stringBuilder.append(intArrArr[indexOfArray][indexOfIntInSelectedArray]);
//Output
System.out.println("stringBuilder.toString()=" + stringBuilder.toString());
}
}
Output:
[C:\java_code\]java TwoDArray
stringBuilder.toString()=10
Arrays can contain theoretically contain any number of dimensions:
https://www.google.com/search?q=multi+dimensional+array+java
https://www.google.com/search?q=three+dimensional+array+java
https://www.google.com/search?q=four+dimensional+array+java
Your array is a two dimensional array (array of arrays). You need to index using two pairs of brackets:
int rows = 4;
int cols = 5;
int[][] myArray = new int[rows][cols];
int row;
int col;
stringBuilder.append(myArray[row][col]);

How to add an element to Array and shift indexes?

I need to add an element to Array specifying position and value.
For example, I have Array
int []a = {1, 2, 3, 4, 5, 6};
after applying addPos(int 4, int 87) it should be
int []a = {1, 2, 3, 4, 87, 5};
I understand that here should be a shift of Array's indexes, but don't see how to implement it in code.
The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
// Now, we will insert the number
list.add(4, 87);
This should do the trick:
public static int[] addPos(int[] a, int pos, int num) {
int[] result = new int[a.length];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = num;
for(int i = pos + 1; i < a.length; i++)
result[i] = a[i - 1];
return result;
}
Where a is the original array, pos is the position of insertion, and num is the number to be inserted.
Jrad solution is good but I don't like that he doesn't use array copy. Internally System.arraycopy() does a native call so you will a get faster results.
public static int[] addPos(int[] a, int index, int num) {
int[] result = new int[a.length];
System.arraycopy(a, 0, result, 0, index);
System.arraycopy(a, index, result, index + 1, a.length - index - 1);
result[index] = num;
return result;
}
You must make a new array, use System.arraycopy to copy the prefix and suffix, and set that one slot to the new value.
If you prefer to use Apache Commons instead of reinventing the wheel, the current approach is this:
a = ArrayUtils.insert(4, a, 87);
It used to be ArrayUtils.add(...) but that was deprecated a while ago. More info here: 1
I smell homework, so probably an ArrayList won't be allowed (?)
Instead of looking for a way to "shift indexes", maybe just build a new array:
int[] b = new int[a.length +1];
Then
copy indexes form array a counting from zero up to insert position
...
...
//edit: copy values of course, not indexes
Unless I'm missing something, the question is not about increasing the array size. In the example the array size remains the same. (Like a bit shift.)
In this case, there is really no reason to create a new array or to copy it. This should do the trick:
static void addPos(int[] array, int pos, int value) {
// initially set to value parameter so the first iteration, the value is replaced by it
int prevValue = value;
// Shift all elements to the right, starting at pos
for (int i = pos; i < array.length; i++) {
int tmp = prevValue;
prevValue = array[i];
array[i] = tmp;
}
}
int[] a = {1, 2, 3, 4, 5, 6};
addPos(a, 4, 87);
// output: {1, 2, 3, 4, 87, 5}
Here is a quasi-oneliner that does it:
String[] prependedArray = new ArrayList<String>() {
{
add("newElement");
addAll(Arrays.asList(originalArray));
}
}.toArray(new String[0]);
org.apache.commons.lang3.ArrayUtils#add(T[], int, T) is deprecated in newest commons lang3, you can use org.apache.commons.lang3.ArrayUtils#insert(int, T[], T...) instead.
Deprecated this method has been superseded by insert(int, T[], T...) and may be removed in a future release. Please note the handling of null input arrays differs in the new method: inserting X into a null array results in null not X
Sample code:
Assert.assertArrayEquals
(org.apache.commons.lang3.ArrayUtils.insert
(4, new int[]{1, 2, 3, 4, 5, 6}, 87), new int[]{1, 2, 3, 4, 87, 5, 6});
Have a look at commons. It uses arrayCopy(), but has nicer syntax. To those answering with the element-by-element code: if this isn't homework, that's trivial and the interesting answer is the one that promotes reuse. To those who propose lists: probably readers know about that too and performance issues should be mentioned.
int[] b = new int[a.length +1];
System.arraycopy(a,0,b,0,4);
//System.arraycopy(srcArray, srcPosition, destnArray, destnPosition, length)
b[4]=87;
System.arraycopy(a,4,b,5,2);
b array would be created as {1, 2, 3, 4, 87, 5,6};
Try this
public static int [] insertArry (int inputArray[], int index, int value){
for(int i=0; i< inputArray.length-1; i++) {
if (i == index){
for (int j = inputArray.length-1; j >= index; j-- ){
inputArray[j]= inputArray[j-1];
}
inputArray[index]=value;
}
}
return inputArray;
}
System.arraycopy is more performant but tricky to get right due to indexes calculations. Better stick with jrad answer or ArrayList if you don't have performance requirements.
public static int[] insert(
int[] array, int elementToInsert, int index) {
int[] result = new int[array.length + 1];
// copies first part of the array from the start up until the index
System.arraycopy(
array /* src */,
0 /* srcPos */,
result /* dest */,
0 /* destPos */,
index /* length */);
// copies second part from the index up until the end shifting by 1 to the right
System.arraycopy(
array /* src */,
index /* srcPos */,
result /* dest */,
index + 1 /* destPos */,
array.length - index /* length */);
result[index] = elementToInsert;
return result;
}
And JUnit4 test to check it works as expected.
#Test
public void shouldInsertCorrectly() {
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
Assert.assertArrayEquals(
new int[]{1}, insert(new int[]{}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}
public class HelloWorld{
public static void main(String[] args){
int[] LA = {1,2,4,5};
int k = 2;
int item = 3;
int j = LA.length;
int[] LA_NEW = new int[LA.length+1];
while(j >k){
LA_NEW[j] = LA[j-1];
j = j-1;
}
LA_NEW[k] = item;
for(int i = 0;i<k;i++){
LA_NEW[i] = LA[i];
}
for(int i : LA_NEW){
System.out.println(i);
}
}
}
Following code will insert the element at specified position and shift the existing elements to move next to new element.
public class InsertNumInArray {
public static void main(String[] args) {
int[] inputArray = new int[] { 10, 20, 30, 40 };
int inputArraylength = inputArray.length;
int tempArrayLength = inputArraylength + 1;
int num = 50, position = 2;
int[] tempArray = new int[tempArrayLength];
for (int i = 0; i < tempArrayLength; i++) {
if (i != position && i < position)
tempArray[i] = inputArray[i];
else if (i == position)
tempArray[i] = num;
else
tempArray[i] = inputArray[i-1];
}
inputArray = tempArray;
for (int number : inputArray) {
System.out.println("Number is: " + number);
}
}
}

Categories