Home / Questions / State the output of the following program segment: String s = "Examination"; int n = s.length(); System.out.println(s.startsWith(s.substring(5, n))); System.out.println(s.charAt(2) == s.charAt(6));
Explanatory Question

State the output of the following program segment:

String s = "Examination";
int n = s.length();
System.out.println(s.startsWith(s.substring(5, n)));
System.out.println(s.charAt(2) == s.charAt(6));

👁 97 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Explanation

Putting the value of n in s.substring(5, n), it becomes s.substring(5, 11). This gives "nation". As s does not start with "nation" so s.startsWith(s.substring(5, n)) returns false.

s.charAt(2) is a and s.charAt(6) is also a so both are equal

Breakdown:

  1. s.startsWith(s.substring(5, n))

    • s.length(): This returns the length of the string s. For the string "Examination", s.length() is 11.
    • s.substring(5, n): This extracts a substring from s starting at index 5 up to, but not including, index n. Hence, s.substring(5, 11) extracts "nation".
    • s.startsWith("nation"): This checks if the string s starts with the substring "nation". The string "Examination" does not start with "nation", so this will return false.

    So, System.out.println(s.startsWith(s.substring(5, n))); will print false.

  2. s.charAt(2) == s.charAt(6)

    • s.charAt(2): This retrieves the character at index 2 of the string s. For "Examination", s.charAt(2) is 'a'.
    • s.charAt(6): This retrieves the character at index 6 of the string s. For "Examination", s.charAt(6) is also 'a'.
    • 'a' == 'a': This comparison is true because both characters are the same.

    So, System.out.println(s.charAt(2) == s.charAt(6)); will print true.

Summary of Output:


false
true