51918

Do we need to initialize an array in Java? [duplicate]

<div class="question-status question-originals-of-duplicate">

This question already has an answer here:

    <li> What is the default initialization of an array in Java? <span class="question-originals-answer-count"> 7 answers </span> </li> </ul>

    I noticed that if I declare an array as:

    int[] myarr = new int[10];

    I can directly use myarr[1] ++; so that myarr[1] = 1. Does it mean that in Java, we <strong>do not</strong> need to initialize the array and set each value as 0 by the following method?

    for (int i = 0; i < myarr.length; i++) { myarr[i] = 0; }

    I saw from some comments that the array may contain garbage values. If the array is an integer array, will it contain any garbage other than 0?

    Answer1:

    In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0. For booleans, that's false. For objects, that's null.

    In other languages such as C++, the values in an uninitialized array are undefined. Some compilers may initialize to 0/null similarly for security, and it's very bad practice to rely on this. However, this behavior is well defined in Java and so it's perfectly okay to create a primitive array and trust that the values are 0.

    Answer2:

    A newly-initialized int[] will be filled with zeros, by language specification.

    Referring to JLS §10.6 (Array Initializers):

    A one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).

    Referring to §4.12.5:

      <li>Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
        <li>For type byte, the default value is zero, that is, the value of (byte)0.</li> <li>For type short, the default value is zero, that is, the value of (short)0.</li> <li>For type int, the default value is zero, that is, 0.</li> <li>For type long, the default value is zero, that is, 0L.</li> <li>For type float, the default value is positive zero, that is, 0.0f.</li> <li>For type double, the default value is positive zero, that is, 0.0d.</li> <li>For type char, the default value is the null character, that is, '\u0000'.</li> <li>For type boolean, the default value is false.</li> <li>For all reference types (§4.3), the default value is null.</li> </ul></li> </ul>

        Answer3:

        no, all java arrays are filled with the appropriates type default value (0 for ints, 0.0 for doubles, null for references, ...)

        Answer4:

        You can't skip the array initialization but you don't have to initialize each element of the array. If you don't initialize an element in an array it works exactly like it would if you weren't initializing a member variable of that specific type: Java will initialize it with the type default value which is 0 for numerical primitive types (int, double, float...), false for booleans and null for objects (String included).

        Answer5:

        No, it is compulsory to initialize an array in java.. When I was writing my programs, I didn't initialize my array and my compiler (jdk7) gave me an error like:

        ArrayOne.java:4: Variable myArray may not have been initialized.

        Thus failing my compilation.

Recommend

  • Heroku rake task uninitialized constant for MongoMapper model
  • Bit arrays usage and filtering in Elasticsearch
  • How to use three different keys e.g. (Ctrl Shift O) to open a form in vb.net?
  • What is this javascript code doing?
  • Will volatile protect me from all behind-the-scenes multi-threading hazards?
  • Does using package generics require the package to be in Depends or Imports?
  • Is there a pre-defined built-in function to convert a number to its binary format in C++?
  • Const variable in C++ function body
  • Obtain access token for both Microsoft Graph and individual service API endpoints (Outlook REST APIs
  • Array resizing and realloc function
  • How to make a div appear under button
  • Invoke another constructor in the same class
  • Maven archetype generate with custom properties
  • C# Application Relative Paths
  • QObject::findChild() returns None without obvious reason
  • Collect HostCPU utilisation and disk I/O speed using XenServer Java API
  • Show message when Tform2 is created?
  • Fortran 90 function return pointer
  • Flex/AS3 very strange simple Number operation issue
  • Why I can't use uniform1f instead of uniform4f for setting a vec4 uniform?
  • Stitching 2 images (OpenCV)
  • Why can't I use non-integral types with switch [duplicate]
  • How to resolve this packager error on react native Android
  • HttpListener.IsSupported is false on XP SP3
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • Installing PHP 7 on digitalocean
  • Enabling DTD support in Sql Server
  • GAE: Way to get reference to an HttpSession from its ID?
  • Object and struct member access and address offset calculation
  • Does Mobilefirst provide a provision to access web services directly?
  • Problems installing Yesod for Haskell
  • Assign variable to the value in HTML
  • Mysterious problem with floating point in LISP - time axis generation
  • Bad request using file_get_contents for PUT request in PHP
  • Accessing IRQ description array within a module and displaying action names
  • Javascript Callbacks with Object constructor
  • Where to put my custom functions in Wordpress?
  • Linker errors when using intrinsic function via function pointer
  • Android Studio and gradle
  • SQL merge duplicate rows and join values that are different