0

I am working on Java based COM program, when I send data in this format so it works:

serialPort.writeBytes( new byte[] { (byte)3, (byte)0, (byte)0, 
                                    (byte)0, (byte)4, (byte)5} );

but when I do following so it does not, where am I doing wrong?

byte[] bcode = null;
bcode[0] = (byte)3;
bcode[1] = (byte)0;
bcode[2] = (byte)0;
bcode[3] = (byte)0;
bcode[4] = (byte)4;
bcode[5] = (byte)5;
serialPort.writeBytes(bcode);
2
  • 2
    You have to initialize your array before assigning values to it. Commented Mar 8, 2013 at 0:32
  • 1
    you can't dereference null. Period. Commented Mar 8, 2013 at 0:32

1 Answer 1

6

On the second example, you did not create your array, you assigned it null. You can't reference an array element of an array that doesn't exist. You could do

byte[] bcode = new byte[6];

That will create your array with space for 6 bytes. Then assign your values individually.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.