KnowledgeBoat Logo
|

Computer Applications

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

Java

Java Iterative Stmts

12 Likes

Answer

JAVA
VA

The loop executes 2 times.

Working

  • The string x contains the value "JAVA", which has a length of 4.
  • The for loop initializes i to 0 and increments it by 2 in each iteration (i = 0, 2).
  • In the first iteration, when i is 0, x.substring(0) extracts the substring from index 0 to the end, which is "JAVA". This is printed.
  • In the second iteration, when i is 2, x.substring(2) extracts the substring from index 2 to the end, which is "VA". This is printed.
  • When i becomes 4, the condition i < 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".

Answered By

5 Likes


Related Questions