Home / Questions / (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
Explanatory Question

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

👁 50 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Understanding the Code

The given Java program prints substrings of the string "JAVA" based on the loop conditions.


String s = "JAVA";
for(i=0; i<s.length(); i+=2)
    System.out.println(s.substring(i));

Step-by-Step Execution

  1. Initialization: i = 0

  2. Loop Condition: i < s.length(), i.e., i < 4 (since "JAVA" has 4 characters).

  3. Increment: i += 2 (i.e., i increases by 2 in each iteration).

  4. Printing: System.out.println(s.substring(i)) prints the substring starting from index i.

Iteration Breakdown

  • First Iteration (i = 0): s.substring(0)"JAVA"

  • Second Iteration (i = 2): s.substring(2)"VA"

  • Loop Stops (i = 4 is out of bounds)

Final Output


JAVA
VA

Number of Loop Executions

  • The loop runs 2 times (i = 0 and i = 2).

Final Answer

  • Output:


JAVA
VA

Number of times loop executes: 2