Creating a Java Array

This is a simple question and I cannot find the answer in the documentation!

String args[] = new String[0];
args[0] = "test";

It is right? Does this create an array with 1 element or 0 elements?

Thanks, I know, a stupid question, but I could not find the answer in the Java document.

+3
source share
10 answers

This creates an array with a length of 0. The second line will give ArrayIndexOutOfBoundsExpection.

+7
source

String[] arr = new String[]{"test"}

+8
source

. , 1

String args[] = new String[1];

myArray [0]

+3

PHP args [] = "new entry",

List<String> args = new ArrayList<String>();
args.add("test");
args.add("and some more");
args.add("and even more");

. , :

String[] argArray = args.toArray(new String[args.size()]);
+2

, - , , , 0 . , 0- , 1- ... , / .

+1

5 :

String myArray[] = new String[5];

0, 1, 2, 3, 4 - , 0, 1, ( - 1).

,

new String[0]

0. 0 - .

new String[1]

1 0, :

myArray[0] = "happy days";
0
String args[] = new String[0];

. , args[0], ArrayIndexOutOfBoundsException. args.length.

String args[] = new String[1];

1 . args[0]. 0. ArrayIndexOutOfBoundsException.

String args[] = new String[10];

10 . args[0], args[9]. .

:

0

new String[x] x. x = 0, , . , , , : new String[1] 1 .

, , , index. [] ( ), ( ), .

: >= 0, < .

0 <= index < size

, , , - .

0
source

String args[] = new String[0];

Creates a size array 0, also called an empty array. Since the array contains no elements, you cannot use an index on it, including 0. Using any index on it results in java.lang.ArrayIndexOutOfBoundsException.

0
source

here is a simple and official example .

-1
source

Source: https://habr.com/ru/post/1766229/


All Articles