Lee
Lee

Reputation: 23

Print Empty Message if Array is Empty

Assuming I want to print the array in reverse order. However if the array is empty it should print "The array is empty"

Why does this code Not Work:

Can we assume that if the array is empty a.length is 0 or is it null? What should a.length be == in the if() statement.what is wrong with the if statement in the for loop that doesn't allow it to work? Or did it never enter the for loop?

public class Test2 {

    public static void main(String[] args) {
        int[] a = {};

        for (int i = a.length - 1; i >= 0; i--) {
            System.out.print(a[i] + " ");
            if (a.length == 0)
                System.out.print("The array is empty");

        }
    }
}

This Code works:

if (a.length == 0)
    System.out.print("The array is empty");
else
{
    for(int i = a.length - 1 ; i >= 0 ; i--)
    {
        System.out.print (a[i] + " ");
    }
}

And this works too:

for(int i = a.length - 1 ; i >= 0 ; i--)
{
    System.out.print (a[i] + " ");
}
if (a.length == 0)
    System.out.print("The array is empty");

Upvotes: 2

Views: 465

Answers (1)

Number945
Number945

Reputation: 4940

See int[] a = {};creates an array of size 0. hence for loop does not even execute in the first case. Let's see the second case.

Here , if condition if (a.length == 0) gets executed and else part does not.

Lets see the third case. Again for loop does not execute. Next code moves to if statement which is outside the for loop. It gets executed.

I hope you understand why your for loop does not execute. See a.length=0. hence i =-1 but the condition that we give in for loop is i>=0

Upvotes: 3

Related Questions