Algirdas Butkus Algirdas Butkus - 4 years ago 77
Java Question

Return Object[] in Java

I need to return integer and byte array, I found that I can return them using Object[], but I'm not sure how to get integer and byte array.

It returns Object with integer and byte array:

public static Object[] readVarInt(DataInputStream in) throws IOException {
int i = 0;
int j = 0;
byte[] byteArr = null;
byte b = 0;
while (true) {
int k = in.readByte();
i |= (k & 0x7F) << j++ * 7;
if (j > 5) {
throw new RuntimeException("VarInt too big");
if ((k & 0x80) != 128) {
byteArr = Arrays.copyOf(byteArr, b);
byteArr[b] = (byte) k;
return new Object[] {i, byteArr}; // <<---

I don't know how to get from Object[] my integer and byte array:

Object Object;
Object = Protocol.readVarInt(serv_input);
int intLength = Object[0]; // <<---
byte[] byteArray = Object[1]; // <<---

This won't work because it thinks it's array, but it's object...

(Sorry for my poor knowledge, I'm new in Java...)

Answer Source

You can use type casting to get data from Object[]

    int intLength = (int) result[0];
    byte[] byteArray = (byte[]) result[1];

But I would recommend to use wrapper object instead of Object[] as result of method:

class Result {
    private final int length;
    private final byte[] byteArr;

    Result(int length, byte[] byteArr) {
        this.length = length;
        this.byteArr = byteArr;

    public int getLength() {
        return length;

    public byte[] getByteArr() {
        return byteArr;

public static Result  readVarInt(DataInputStream in) throws IOException {
    return new Result(i, byteArr);


Result result = readVarInt(serv_input);

int intLength = result.getLength();
byte[] byteArray = result.getByteArr();

Also be aware that this part byteArr = Arrays.copyOf(byteArr, b); returns NPE in first step of execution because you are trying to copy data from null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download