0

Why is this coming out as false?

public class practice 
{
   public static void main(String [] args) 
   {
      System.out.println(startHi("hi "));
   }

   public static boolean  startHi(String str) 
   {
       System.out.println(str.substring(0,2));
       if(str.length() < 2) 
       {
          return false;
       }
       else if(str.substring(0,2) ==("hi")) 
       {
          return true;
       }
       else 
       {
         return false;
       }
   }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

1 Answers1

1

You should use the .equals method to check for equality of strings, not ==. See here.

Using == is checking to see if the objects have the same address in memory. That's not usually what you're looking for when checking if the value of two strings are the same.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Mark Leiber
  • 3,118
  • 2
  • 13
  • 22