new byte always initialized to 0?

3

34stunts

Consider the following code:
byte b[] = new byte[34];
for (int x = 0; x < b.length; x++)
{
System.out.println((int) b[x] );
}

Java compiles it and runs it. This prints a bunch of "0".

So my question is this correct code? Or should/must I have a loop to
assign it to 0. Is it a rule that a newly created byte is 0 or is this
merly a coincidence?

-
Fred
 
A

Andrew Thompson

Sorry for the spam :-(

Posting a single post 3 times to one group may be overkill,
but it is not spam. I think the term is 'reposting'.

The term spam generally refers to advertising of products.

Noting that you are posting through Google groups, I
think I can guess the basic reason ..the Google groups
server told you it 'could not complete that action' (or
similar words)?

A tip is to keep a second browser open, pointing to the group.
After posting, or when you get a message like that - wait
a few seconds and refresh the page showing the group
'titles' list - the podt will often make it through - depsite
what the server claimed.

(I am not sure on your technical query - I'll leave that for
the JLS gurus)

Andrew T.
 
I

Ian Shef

(e-mail address removed) wrote in @b28g2000cwb.googlegroups.com:
Consider the following code:
byte b[] = new byte[34];
for (int x = 0; x < b.length; x++)
{
System.out.println((int) b[x] );
}

Java compiles it and runs it. This prints a bunch of "0".

So my question is this correct code? Or should/must I have a loop to
assign it to 0. Is it a rule that a newly created byte is 0 or is this
merly a coincidence?
The JLS (3rd edition) at paragraph 4.12.5 says:

4.12.5 Initial Value of Variables

Every variable in a program must have a value before its value is used:
• Each class variable, instance variable, or array component is
initialized with a default value when it is created (§15.9, §15.10):
 For type byte, the default value is zero, that is,
the value of (byte)0.

.... so the answer is that this is a rule and not a coincidence.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top