This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Hi, I'd like to create a byte array of a specified size and fill it with noise/junk characters/nonsense/whatever. I'm acting under the assumption that if I don't initialize the array, it will hold null at all positions and throw an exception as soon as I try to do anything with it. If that's true, can someone help me figure out how to fill the array? Thanks, g.
Hey there - The good news is that arrays come 'out of the box' with default values! The integer primitives (byte short int long) come pre-loaded with 0's , the floating points w/ 0.0's, boolean arrays with false, chars w/ '\u0000' and objects with null.
Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
When you say byte arr = new byte[size]; (assuming "size" is an integer defined somewhere) you initially get an array of all 0 bytes. This is perfectly valid, and you won't get any exception when you access the array elements. But if you still really want to fill the array with random junk, take a look at Math.random(). It returns a random double between 0.0 and 1.0 (including 0.0 but not including 1.0). You'll need to multiply the result by 256 and cast it to a byte before putting it in an array element. [ October 17, 2002: Message edited by: Ron Newman ]
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Joined: Jan 28, 2002
Thanks, Bert and Ron. I guess I was looking for something a little closer to C (I think it's C.. been a long time), where if you don't initialize it, you can use the random junk already already existing in the memory allocated to your new array. 0's will have to do, since I don't want to waste time giving all those bytes random values. Thanks for the suggestions, though! g.
Joined: Jun 06, 2002
Even in C, there's absolutely no guarantee that the contents of your uninitialized array will be random. They could well be all 0, or all 0xFF, or anything else. You want random, you need to use a random number generator.