After the following code fragment, what is the value in fname?String str;int fname;str = ";Foolish boy.";fname = str.indexOf("fool");
-
A. 0
-
B. 2
-
C. -1
-
D. 4
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 variablestrof typeString.int fname;declares a variablefnameof typeint.str = ";Foolish boy.";assigns the string";Foolish boy."to the variablestr.fname = str.indexOf("fool");assigns the return value ofindexOf("fool")to the variablefname.
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