Question:

Give the output of the following program segment:
\texttt{String S = "GRACIOUS".substring(4);}
\texttt{System.out.println(S);}
\texttt{System.out.println("GLAMOROUS".endsWith(S));}

Show Hint

In Java, \texttt{substring(n)} returns the string starting from index \(n\), and \texttt{endsWith()} checks whether a string ends with the given suffix.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Find the value of \texttt{S}.
The string is:
\[ \texttt{"GRACIOUS"} \] Its characters with index positions are:
\[ G(0)\; R(1)\; A(2)\; C(3)\; I(4)\; O(5)\; U(6)\; S(7) \] So, \texttt{substring(4)} gives the part of the string starting from index \(4\):
\[ \texttt{"IOUS"} \] Therefore,
\[ S = \texttt{"IOUS"} \] Step 2: Print the first output.
The first statement prints:
\[ \texttt{IOUS} \] Step 3: Check the \texttt{endsWith()} condition.
Now we check whether \texttt{"GLAMOROUS"} ends with \texttt{"IOUS"}.
The ending part of \texttt{"GLAMOROUS"} is \texttt{"ROUS"}, not \texttt{"IOUS"}.
So the result is:
\[ \texttt{false} \] Step 4: Write the final output.
Hence, the output is:
\texttt{IOUS}
\texttt{false}
Was this answer helpful?
0
0

Questions Asked in ICSE Class X board exam

View More Questions