aspose file tools*
The moose likes Beginning Java and the fly likes Bytes of junk Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Bytes of junk" Watch "Bytes of junk" New topic
Author

Bytes of junk

Garann Means
Ranch Hand

Joined: Jan 28, 2002
Posts: 214
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.
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8829
    
    5
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.)
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
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)
Garann Means
Ranch Hand

Joined: Jan 28, 2002
Posts: 214
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.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
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.
 
 
subject: Bytes of junk