1Z0-803 · Question #138
Given the code fragment: class MySearch { public static void main(String[] args) { if (XXXX) { System.out.println("Found"); } } } Which code fragment, replace with XXXX, enables the code to print Foun
The correct answer is A. url.indexOf("com") != -1. To print 'Found' when the substring 'com' is present in the url string, the if condition must evaluate to true whenever 'com' is found.
Question
Given the code fragment:
class MySearch { public static void main(String[] args) { if (XXXX) { System.out.println("Found"); } } } Which code fragment, replace with XXXX, enables the code to print Found?
Options
- Aurl.indexOf("com") != -1
- Burl.indexOf("com")
- Curl.indexOf("com") == 19
- Durl.indexOf("com") != false
How the community answered
(27 responses)- A89% (24)
- B7% (2)
- D4% (1)
Why each option
To print 'Found' when the substring 'com' is present in the `url` string, the `if` condition must evaluate to true whenever 'com' is found.
The `indexOf("com")` method returns the starting index of the substring "com" or -1 if not found. Comparing this result with `!= -1` yields a boolean true if "com" is present at any index, correctly fulfilling the condition for printing "Found".
In Java, an integer value returned by `indexOf()` cannot be implicitly converted to a boolean for an `if` statement; this would result in a compile-time type mismatch error.
This condition specifically checks if "com" is found exactly at index 19. If "com" exists at a different index or not at all, the condition would be false, failing to print "Found" in those valid "found" scenarios.
This statement attempts to compare an integer (the result of `indexOf()`) with a boolean literal (`false`), which is a type mismatch and will cause a compile-time error in Java.
Concept tested: String indexOf method and boolean conditions
Source: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf-java.lang.String-
Topics
Community Discussion
No community discussion yet for this question.