📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following Java code: public class

    SubstringDryRun {     public static void main(String[] args) {         String s = "Programming";         String s1 = s.substring(3, 7);         String s2 = s.substring(s.indexOf('g') + 1);         System.out.println(s1 + s2);     } } What will be the output of this program?
    A gramramming Correct Answer Incorrect Answer
    B gramming Correct Answer Incorrect Answer
    C programming Correct Answer Incorrect Answer
    D ming Correct Answer Incorrect Answer
    E ramming Correct Answer Incorrect Answer

    Solution

    Correct Answer: A s = "Programming" s1 = s.substring(3, 7): P-0, r-1, o-2, g-3, r-4, a-5, m-6, m-7, i-8, n-9, g-10. substring(3, 7) extracts characters from index 3 up to (but not including) 7. So, s[3]s[4]s[5]s[6] which is "gram". s.indexOf('g') is 3. s2 = s.substring(s.indexOf('g') + 1) is s.substring(3 + 1) which is s.substring(4). s.substring(4) extracts characters from index 4 to the end. So, s[4]s[5]s[6]s[7]s[8]s[9]s[10] which is "ramming". s1 + s2 = "gram" + "ramming" = "gramramming".

    Practice Next
    ask-question