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));
Single Choice
Views 88
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:
-
s.startsWith(s.substring(5, n))s.length(): This returns the length of the strings. For the string"Examination",s.length()is11.s.substring(5, n): This extracts a substring fromsstarting at index5up to, but not including, indexn. Hence,s.substring(5, 11)extracts"nation".s.startsWith("nation"): This checks if the stringsstarts with the substring"nation". The string"Examination"does not start with"nation", so this will returnfalse.
So,
System.out.println(s.startsWith(s.substring(5, n)));will printfalse. -
s.charAt(2) == s.charAt(6)s.charAt(2): This retrieves the character at index2of the strings. For"Examination",s.charAt(2)is'a'.s.charAt(6): This retrieves the character at index6of the strings. For"Examination",s.charAt(6)is also'a'.'a' == 'a': This comparison istruebecause both characters are the same.
So,
System.out.println(s.charAt(2) == s.charAt(6));will printtrue.
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.