To determine the value of fname
after the given code fragment, we need to understand the indexOf()
method in Java and how it is used.
The indexOf()
method in Java returns the index of the first occurrence of a specified substring within a given string. It returns -1 if the substring is not found.
Now let's go through the code fragment and evaluate each line:
String str;
int fname;
str = ";Foolish boy.";
fname = str.indexOf("fool");
String str;
declares a variable str
of type String
.
int fname;
declares a variable fname
of type int
.
str = ";Foolish boy.";
assigns the string ";Foolish boy."
to the variable str
.
fname = str.indexOf("fool");
assigns the return value of indexOf("fool")
to the variable fname
.
Now, let's evaluate each option and explain why it is right or wrong:
A. 0: This option is incorrect. The indexOf("fool")
method call will return -1 because the substring "fool" is not found in the string str = ";Foolish boy."
. Therefore, fname
will be assigned the value -1, not 0.
B. 2: This option is incorrect. The indexOf("fool")
method call will return -1 because the substring "fool" is not found in the string str = ";Foolish boy."
. Therefore, fname
will be assigned the value -1, not 2.
C. -1: This option is correct. The indexOf("fool")
method call will return -1 because the substring "fool" is not found in the string str = ";Foolish boy."
. Therefore, fname
will be assigned the value -1.
D. 4: This option is incorrect. The indexOf("fool")
method call will return -1 because the substring "fool" is not found in the string str = ";Foolish boy."
. Therefore, fname
will be assigned the value -1, not 4.
Therefore, the correct answer is:
C. -1