00 Votes

Java: How to create an Array

Question by Guest | 2016-08-06 at 18:10

What can I do to just create a simple array using the programming language Java? I am coming from other languages and I have tried a lot, but I cannot make it work.

Can someone give me an easy example?

ReplyPositiveNegative
0Best Answer0 Votes

In Java, there are several possibilities to create an array.

One-Dimensional Arrays

Here is an example for an integer array:

int[] intArr1 = {1,2,3};

int[] intArr2 = new int[3];
intArr2[0] = 1;
intArr2[1] = 2;
intArr2[2] = 3

And here accordingly for a string array:

String[] strArr1 = {"a","b","c"};

String[] strArr2 = new String[3];
strArr2[0] = "a";
strArr2[1] = "b";
strArr2[2] = "c";

In each case, the first array (intArr1 respectively strArr1) is directly filled with initial values at creation time. Apart from that, the second array is created as an empty array of defined length that is filled with values later. Afterwards, both integer arrays as well as both string arrays are containing the same values among themselves.

Multidimensional Arrays

Multidimensional Arrays can be created like that:

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

int[][] mdIntArr2 = new int[3][2];
mdIntArr2[0][0] = 1;
mdIntArr2[0][1] = 2;
mdIntArr2[1][0] = 3;
mdIntArr2[1][1] = 4;
mdIntArr2[2][0] = 5;
mdIntArr2[2][1] = 6;

As you can see, again, we can use those methods - the array mdIntArr1 is immediately initialized with default values, the array mdIntArr2 is filled later.
2016-08-06 at 18:43

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.