How can I make `new[]` default-initialize the array of primitive types?
int* p = new int[10]()
should do.
However, as Michael points out, using std::vector
would be better.
What is the default initialization of an array in Java?
Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.
- For references (anything that holds an object) that is
null
. - For int/short/byte/long that is a
0
. - For float/double that is a
0.0
- For booleans that is a
false
. - For char that is the null character
'\u0000'
(whose decimal equivalent is 0).
When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new
.
Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.
How do I declare and initialize an array in Java?
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).
For primitive types:
int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
For classes, for example String
, it's the same:
String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required.
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
Can array of primitive data type be instantiated?
In Java , when we instantiate a primitive array (like new int[10]
), items in the array are initialized with default value of that primitive. (Default value for int
is 0
, default value for boolean
is false
etc.)
When we instantiate an object array (e.g. String
array), items in the array are initialized with null
.
See below program and its output.
public class PrimitiveArray
{
public static void main(String[] args)
{
int[] intArray = new int[10];
boolean[] booleanArray = new boolean[10];
String[] stringArray = new String[10];
System.out.println("intArray[3] = " + intArray[3]);
System.out.println("booleanArray[3] = " + booleanArray[3]);
System.out.println("stringArray[3] = " + stringArray[3]);
}
}
Output is:intArray[3] = 0
booleanArray[3] = false
stringArray[3] = null
Any shortcut to initialize all array elements to zero?
A default value of 0 for arrays of integral types is guaranteed by the language spec:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type
int
, the default value is zero, that is,0
.
If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).
default array values
Array.prototype.repeat= function(what, L){
while(L) this[--L]= what;
return this;
}
var A= [].repeat(0, 24);
alert(A)
How do I initialize a byte array in Java?
You can use an utility function to convert from the familiar hexa string to a byte[]
.
When used to define a final static
constant, the performance cost is irrelevant.
Since Java 17
There's now java.util.HexFormat
which lets you do
byte[] CDRIVES = HexFormat.of().parseHex("e04fd020ea3a6910a2d808002b30309d");
This utility class lets you specify a format which is handy if you find other formats easier to read or when you're copy-pasting from a reference source:
byte[] CDRIVES = HexFormat.ofDelimiter(":")
.parseHex("e0:4f:d0:20:ea:3a:69:10:a2:d8:08:00:2b:30:30:9d");
Before Java 17
I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?
byte[] CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");
I insert it here for maximum readability :
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
What’s the difference between Array() and [] while declaring a JavaScript array?
There is a difference, but there is no difference in that example.
Using the more verbose method: new Array()
does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
Another difference is that when using new Array()
you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array()
because you can prevent the overflow from happening.
As pointed out in this answer, new Array(5)
will not actually add five undefined
items to the array. It simply adds space for five items. Be aware that using Array
this way makes it difficult to rely on array.length
for calculations.
Related Topics
How to Enable C++17 Support in VScode C++ Extension
Error: Could Not Resolve Sdk Path for 'Macosx10.8'
Thread Safe Implementation of Circular Buffer
Convert String to Mathematical Evaluation
Error: Member Access into Incomplete Type:Forward Declaration Of
Debugging Information Cannot Be Found or Does Not Match Visual Studio'S
How to Read Groups of Integers from a File, Line by Line in C++
Details of Std::Make_Index_Sequence and Std::Index_Sequence
How Does Malloc Understand Alignment
Returning to Beginning of File After Getline
Prefix/Postfix Increment Operators
How to Access Private Data Members Outside the Class Without Making "Friend"S
Is Volatile Bool for Thread Control Considered Wrong
Convert C++ Function Pointer to C Function Pointer
How to Get a List of Video Capture Devices (Web Cameras) on Windows? (C++)