basickarl
basickarl

Reputation: 40454

Java: byte[1] vs byte[1024]

I've been trying to get some streams working via TCP however I seem to fail, probably due to the fact that I don't understand byte streams enough.

I know what a byte it, it's 8-bit. example: 0000 0001 (which would be "int 1")

When i define let's say:

Byte[] myByte = new byte[1];

What does the "1" do? Is myByte capable of carrying only one byte?

Upvotes: 1

Views: 1640

Answers (1)

user2864740
user2864740

Reputation: 61875

new type[x] is the syntax for an expression creating an array [object] (of type type[]1) with x elements.

See the Nuts & Bolts: Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array [object] is created (i.e. new byte[1]). After creation, its length is fixed ..

So, new byte[1] creates an array [object] for a single byte (length = 1), and new byte[1024] creates an array of 1024 byte elements (length = 1024).


1 The code in the post is a bit "funny" because it uses Byte[] as the array type but new byte[1] to create the actual array object; it should be byte in both places. I'm ignoring that as a typo because automatic boxing of a primitive array is not supported in Java.

Upvotes: 2

Related Questions