I know I am probably over thinking this but I cannot seem to figure this out. I am trying to check if the value is null and if not to continue.

    public Item getItem(String theItem)
        Iterator iter = myItems.iterator();
        while(iter.hasNext()) {
            Item anItem = (Item) iter.next();
                if(anItem.getName().equals(theItem)) {
                    return anItem;
        if(anItem == null)
        return null;

Recommended Answers

All 4 Replies

why don t you use empty string instead of null?, and your method will always return null since is not return a variable state.

There is no need for the If statement to be there.

When you iterator through your Collection, you either find the desired item, or you don't. These are your only 2 outcomes.

  1. Item Found - Return the Item object, method stop executing when a value is returned

  2. Item not Found - While loop finishes, Code after is Executed. Regardless of the if statement, the return value is always null. So if the method does not find the desired item, it always returns null.

Because of this, there is no need to check if the item is null as the outcome will always be the same.

Hope this helps

castajiz_2: you may want to re-read the code snippet.
as ObSys points out: if the item is found during the iteration, it doesn't return null, so "always return null" is incorrect.

You can debugg your program and place the value ,or if you are using any framwork Then you will get the debug option . At the time of debugging you can put any value on the variable .

Be a part of the DaniWeb community

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