I need to check if a "user" types in the word "if". Let me explain, i have this: String text;
Scanner read = new Scanner(System.in);
System.out.println("type text");
text=read.nextLine();
System.out.println("the text is " +text);
I need to make sure that what is typed in is a the word "if".
You need to use String API's contains() or equals() methods as shown below:
if(text.contains("if ") || text.contains(" if") || text.contains(" if ")) {
System.out.println(" Text contains if");
}
The above code works even if the word if is at the start or at the end of the input text.
If you are looking for the whole word match, then you need to use equals() as shown below:
if(text.equals("if")) {
System.out.println(" Text equals if");
}
You need to compare the value of text with the value if using equals() like this:
if(text.equals("if")){
//Do something
}
Or a better null safe solution would be:
if("if".equals(text)){}
This way if text is null your program won't crash
Thanks to @Tancho for the null safe sollution
Generally speaking to compare 2 string you need to use equals()
Using == you compare 2 objects references not the values
If you're looking for an exact match, you should use :
"if".equals(text)
Not the other way around, because a constant should always be compared to a variable, not the other way around. You will have : 1. readability 2. safety (as this will never throw a NullPointerException, even if text is null)