OutputModerate2 marks
Give the output of the following program segment and specify how many times the loop is executed. String s = "JAYA"; for(i = 0; i < s.length(); i += 2) System.out.println(s.substring(i));
Topic: substring() inside a loop
Previous-year question practice database
Answer
Exam answer
JAVA VA
The loop is executed 2 times.
Explanation
Dry-run the loop, listing the value of i at each pass. The string has length 4 and i grows by 2 each time. Pass 1: i = 0, condition 0 < 4 true, prints s.substring(0) — the whole string. Pass 2: i = 2, condition 2 < 4 true, prints s.substring(2) — from index 2 to the end. Pass 3: i = 4, condition 4 < 4 false, so the loop stops. That is 2 executions. Note the question asks for two things — the output AND the count — so give both. Careful: the string in the source paper reads "JAYA", which would print JAYA and YA; the printed key shows JAVA and VA. Use the string as given in your own paper.
More from String Manipulation
To extract the word NOW from the word "ACKNOWLEDGEMENT", the Java statement "ACKNOWLEDGEMENT".substring(3, ____) is used. Choose the correct number to fill in the blank.2026String a[] = {"Atasi", "Aditi", "Anant", "Amit", "Ahana"};
System.out.println(a[1].charAt(1) + "*" + a[2].charAt(2));
The output of the above statement is:2026Which of the following String methods returns a negative value?2026Assertion (A): The substring() method modifies the original String.
Reason (R): The substring() method can extract part of a String starting from a specific index.2026Give the output of the following program segment:
String S = "GRACIOUS".substring(4);
System.out.println(S);
System.out.println("GLAMOROUS".endsWith(S));2026Name the following:
(a) The return data type of the method equals().
(b) The String method which has no parameter and returns a String.2026