1

Im trying to find if the first two letters of a string are "hi". If it does it shold return true, and if not it should return false. I used substring to find the values of the given string, but when the condition comes up true it isn't returning true. I must not be understanding something about Java, which Im new to.

Here is my code:

class Main {
    public boolean startHi(String str) {


        String str1 = str.substring(0,1);
        String str2 = str.substring(1,2);

        if(str1=="h" && str2=="i"){
            return true;
        }
        if(str!="hi" || str.length()<=2){
            return false;
        }
        else{
            return false;
        }
    }
    public static void main(String[] args) {
        System.out.println(new Main().startHi("hi ho"));
        System.out.println(new Main().startHi("hi"));
        System.out.println(new Main().startHi("howhi"));
    }
}

The string starts with "hi" and it sees that, but it returns false.

JonnyDoeInWisco
  • 233
  • 1
  • 4
  • 12

3 Answers3

2

You could use String.startsWith(String prefix)

public boolean startHi(String str) {
    return str.startsWith("hi");
}

So after all you probably don't need your own startHi() method, but can use standard Java API.

flavio.donze
  • 7,432
  • 9
  • 58
  • 91
1

Try this...

 if(str1.equals("h") && str2.equals("i")) //equals use instead of (==) Operator.

instead Of

if(str1 =="h"  && str2 == "i")

OR

if(str.startsWith("hi") // this will also works
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
1

It's not returning true because you have to compare strings with the equals() method.

    if("h".equals(str1) && "i".equals(str2)){
        return true;
    }

If you use == to compare objects it will check if it's the same object so it checks if the memory addresses of the objects are the same.

The string class overrides the equals() method to check for content.

If you're creating a string like this

String s1 = "Hi";

Java will put "Hi" in the so called string literal pool so if you are creating a second string

 String s2 = "Hi"; 

Java will not create a second Object but will refer to the "Hi" in the string literal pool.

Now you could do compare the two strings like s1 == s2 and it would be true because the two references s1 and s2 point to the same object.

But what the substring() method does is new String("xyz") and if you declare a string like this a new object will be created and the comparison with == will return false because the two references obviously don't point on the same object.

Dimitrios Begnis
  • 823
  • 6
  • 16