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));

Views 17

Answer:

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

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.