How do i return a boolean array?

i get an error stating that i can't cast from boolean[] to boolean.

I have something like below.

method logic...

boolean [] information = {true, false};
return information; // this line does not work.

Thanks sj

Dani AI

Generated

As discovered, the compile error happens when the method’s declared return type does not match what you actually return. A method declared to return a single boolean cannot return a boolean[]. If the goal is to return an array, declare the method to return boolean[]; if you want one value, return a single boolean (for example, one element from the array).

Example pattern (defensive copy to avoid exposing internal state):

public boolean[] getFlags() {
    boolean[] flags = computeFlagsSomehow();
    return flags == null ? new boolean[0] : flags.clone(); // safe: caller can modify result without touching internal state
}

If you intended a single boolean, return an element explicitly:

public boolean isFirstFlagSet() {
    boolean[] flags = computeFlagsSomehow();
    return flags.length > 0 && flags[0];
}

Other practical tips: prefer returning an empty array instead of null to avoid NPEs; use Arrays.toString(flags) when printing arrays for debugging; consider List<Boolean> or BitSet if you need collection semantics or memory-efficient bit storage (note List<Boolean> uses boxed Boolean objects and has boxing overhead). Remember Java does not allow two methods that differ only by return type — overloading must differ by parameters — so be careful where similar method names exist.

Forgot to update the method definition from boolean to boolean []

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.