Array Length in Java

前端 未结 16 1386
忘了有多久
忘了有多久 2020-11-30 21:27

I declared an array as shown below:

int[] arr = new int[10];

Then I assigned following values to the array:

arr[0] = 1;
arr         


        
相关标签:
16条回答
  • 2020-11-30 22:02

    In this case, arr.length will return 10, the size of array you allocated. Logical size doesn't really apply here, as this is a fixed length array.

    When you initialize the array:

    int[] arr = new int[10];
    

    Java will create an array with 10 elements and initialize all of these to 0. See the Java language spec for details of initial values for this and other primitive types.

    0 讨论(0)
  • 2020-11-30 22:03

    To find length of an array A you should use the length property. It is as A.length, do not use A.length() its mainly used for size of string related objects.

    The length property will always show the total allocated space to the array during initialization.

    If you ever have any of these kind of problems the simple way is to run it. Happy Programming!

    0 讨论(0)
  • 2020-11-30 22:05

    `

    int array[]=new int[3]; array.length;

    so here we have created an array with a memory space of 3... this is how it looks actually

    0th 1st 2nd ...........> Index 2 4 5 ...........> Number

    So as u see the size of this array is 3 but the index of array is only up to 2 since any array starts with 0th index.

    second statement' output shall be 3 since the length of the array is 3... Please don't get confused between the index value and the length of the array....

    cheers!

    0 讨论(0)
  • 2020-11-30 22:09
      int arr[]={4,7,2,21321,657,12321};
      int length =arr.length;
      System.out.println(length); // will return 6
    
      int arr2[] = new int[10];
       arr2[3] = 4;
      int length2 =arr2.length;
      System.out.println(length2); // // will return 10. all other digits will be 0 initialize because staic memory initialization
    
    0 讨论(0)
  • 2020-11-30 22:14

    In Java, your "actual" and "logical" size are the same. The run-time fills all array slots with default values upon allocation. So, your a contains 10.

    0 讨论(0)
  • 2020-11-30 22:16

    It contains the allocated size, 10. The remaining indexes will contain the default value which is 0.

    0 讨论(0)
提交回复
热议问题