2(x)
Give the output of the following program segment and specify how many times the loop is executed.
String s = "JAVA";
for(i = 0; i < s.length(); i += 2)
System.out.println(s.substring(i));Show SolutionHide Solution↓
JAVA
VA
The loop executes 2 times.
- The string
xcontains the value"JAVA", which has a length of 4. - The
forloop initializesito 0 and increments it by 2 in each iteration (i = 0, 2). - In the first iteration, when
iis 0,x.substring(0)extracts the substring from index 0 to the end, which is"JAVA". This is printed. - In the second iteration, when
iis 2,x.substring(2)extracts the substring from index 2 to the end, which is"VA". This is printed. - When
ibecomes 4, the conditioni < x.length()(i.e.,4 < 4) becomes false, so the loop terminates. - Therefore, the loop executes exactly 2 times, printing the substrings
"JAVA"and"VA".