-1
class BadFoodException extends Exception{
    //Do something
}

class Reader {
    private String food1;
    private String food2;
    public static void main(String args[])
    {
        Reader m = new Reader(args);
        for (int i=0; i<args.length; i++){
            try
            {
            m.checkfood(args[i]);
            }
            catch(BadFoodException e){System.out.println(args[i]+ " caught");}

        }
    }
    private Reader(String [] args){
        food1=args[0];
        food2=args[1];
    }
    void checkfood(String food) throws BadFoodException
    {   if( food == "banana")
        throw new BadFoodException();
        System.out.println(food + " passed through.");
    }

}

I am passing two foods- banana and mango through command line. The checkfood method should throw an exception when the food is banana.. and the mango should pass through. However both are passing through instead? why?

zessx
  • 68,042
  • 28
  • 135
  • 158
user3659934
  • 15
  • 1
  • 1
  • 3
  • @Flow, I don't see this as duplicate, OP don't know where is the problem. After our answers only he/she may get to know these. – Abimaran Kugathasan May 26 '14 at 06:05
  • 1
    @AbimaranKugathasan: **The** answer is virtually identical to that found in the duplicate question. That's why it can be considered a duplicate; the issue is the comparison of `String` with `==`. – Makoto May 26 '14 at 06:08
  • @makoto : Yes, the issue is with comparing the Strings, but, OP don't know this until he/she got the answer. – Abimaran Kugathasan May 26 '14 at 06:09
  • Correct, but hat doesn't make it not a duplicate. – Flow May 26 '14 at 06:23

3 Answers3

6

Change if( food == "banana") to if("banana".equals(food)).

In java == operator checks both references refers same object or not. You should use .equals() if your intention is checking both objects are meaningfully equal.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
0

Strings are immutable in Java. You must use .equals(Object) method to compare String objects.

Note : == checks for the equality of the both references i.e. they point to same object or not. But, you should check the String instances are meaningfully equivalent.

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
0

if(food=="banana") replace it,

 if (food.intern() == "banana"){
 do your stuff here
 }

void checkfood(String food) throws BadFoodException
{   if( food.intern() == "banana")
    throw new BadFoodException();
    System.out.println(food + " passed through.");
}
hari
  • 1,874
  • 1
  • 16
  • 10