Write the output of the following Java program and explain t

Write the output of the following Java program and explain the results. public class Test {public static void main(String [] args) {int i, j; outerloop: for(i = 1; i

Solution

The output of the given program is

Output:

stmt1 i=1 j=1
stmt2 i=1 j=1
stmt1 i=1 j=2
stmt1 i=2 j=1
stmt2 i=2 j=1
stmt1 i=2 j=2

Explanation:

Let us go through step by step

*Intialize i=1 and j=1

will print \"stml1 i=1 j=1\"
and j is not greater than or equal to 2 so skip it
and then it prints \"stmt2 i=1 j=1\"

*Now to the beginning of j for loop,increment j by 1
so i=1 and j=2
will print \"stmt1 i=1 j=2\"
and j is equal to 2 so it continues to outerloop and increments i by 1

*Now i=2 and j=1(Inialised again)
then it prints \"stmt1 i=2 j=1\"
and j is not greater than or equal to 2 so skip it
and then it prints \"stmt2 i=2 j=1\"

*Now to the beginning of j for loop,increment j by 1
so i=2 and j=2
will print \"stmt1 i=2 j=2\"
and j is equal to 2 so it continues to outerloop and increments i by 1

*but i will be 3 and according to the for loop i<3 so it exits the for loop

and if you gather all the outputs printed above,final output will be

stml1 i=1 j=1
stmt2 i=1 j=1
stmt1 i=1 j=2
stmt1 i=2 j=1
stmt2 i=2 j=1
stmt1 i=2 j=2

 Write the output of the following Java program and explain the results. public class Test {public static void main(String [] args) {int i, j; outerloop: for(i

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site