Read Time:1 Minute, 0 Second
Write a Java program to check if the word ‘orange’ is present in the “This is orange juice”
public class CheckWordExample { public static void main(String[] args) { String sentence = "This is orange juice"; String word = "orange"; boolean containsWord = sentence.contains(word); if (containsWord) { System.out.println("The sentence \"" + sentence + "\" contains the word \"" + word + "\""); } else { System.out.println("The sentence \"" + sentence + "\" does not contain the word \"" + word + "\""); } } }
Output:
The sentence "This is orange juice" contains the word "orange"
In this program, we first declare a String
variable sentence
and assign it the value “This is orange juice”. We also declare a String
variable word
and assign it the value “orange”. Then, we use the contains()
method of the String
class to check if the sentence contains the word. The contains()
method returns true
if the string contains the specified character or sequence of characters, and false
otherwise. We store the result in a boolean
variable containsWord
.
Finally, we use an if
statement to check the value of containsWord
. If it’s true
, we print out a message saying that the sentence contains the word. If it’s false
, we print out a message saying that the sentence does not contain the word.
Average Rating