How does this java code work?

public static void main(String[] args)
{
    int [][]shatner = new int[1][1];
    int []rat = new int[4];
    shatner[0] = rat;
    System.out.println(shatner[0][3]);
}    

surprised, exit 0, why Java does not check for such an indexOutOfBound error?

+3
source share
7 answers

Do not be surprised. shatner [0] is an array (rat) and has a length of 4. So shartner [0] [3] is a rat [3], which turns out to be 0 ..

+6
source

Where do you see the "indexOutOfBound error"? The code performs the following actions:

  • Initialize an array (size 1) of arrays int(size 1), i.e. 2D array, content indexed with 0
  • Initialize array int, size 4, content will be indexed with 0
  • set a single element of a 2D array to an array of size 4 1D
  • 2D-, 0
+5

.

0- shatner int[4].

+4

. shatner - . 4. , shatner [0] [3] .

+3

, Java IndexOutOfBoundsException. , .

shatner[0] = rat;

, 0- shatner 4, shatner[0][4] .

+3

, java , . shatner [1] [1], - {{0},{0}} .

However, then you assign an integer to the first element, turning it {{0,0,0,0},{0}}into memory, so Java resolves the newly assigned index.

0
source

Arrays should not be rectangular in Java. It is a jagged array and works great.

0
source

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


All Articles