Find the output of Java programs | Loops | Set 2: Enhance the knowledge of Java Loops concepts by solving and finding the output of some Java programs.
Question 1:
public class Main {
public static void main(String[] args) {
int val = 0;
for (;;) {
System.out.println("India");
}
}
}
Question 2:
public class Main {
public static void main(String[] args) {
while ()
System.out.println("Hello World");
}
}
Question 3:
public class Main {
public static void main(String[] args) {
int num = 7;
int val = 0;
do {
System.out.println(num * val);
} while ( val <= 10 )
}
}
Question 4:
public class Main {
public static void main(String[] args) {
int val = 1235;
var loop = 0;
while (val > 0) {
val = val / 10;
loop++;
}
System.out.println(val);
}
}
Question 5:
public class Main {
public static void main(String[] args) {
int val = 1235;
int loop = 0;
while (val > 0) {
val = val / 10;
loop++;
}
System.out.println(val);
}
}
Answer Question 1:
Output:
Explanation:
In the above program, we did not use condition in the for loop, if we do not use loop condition in the for loop, then the condition will be considered as true in Java, that's why it will print "India" infinite times on the console screen.
Answer Question 2:
Output:
Explanation:
The above program will generate syntax error because we cannot use the while loop without condition in Java.
Answer Question 3:
Output:
Explanation:
The above program will generate syntax error because of missed semicolon after loop condition. The correct code is given below:
do { System.out.println(num*val); }while(val<=10);
Answer Question 4:
Output:
Explanation:
In the above program, we created a variable loop using var, in the Java we cannot use var type to declare a variable. That's why the compilation error will be generated by the above program.
Answer Question 5:
Output:
Explanation:
In the above program, we created two local variables Val and loop initialized with 1235 and 0 respectively.
Now look to the iteration,
Iteration1: Val=1235, loop=0 condition is true. Val = val/10; Val = 1235/10; Val = 123; And loop will 1. Iteration2: Val=123, loop=1 condition is true. Val = val/10; Val = 123/10; Val = 12; And loop will 2. Iteration3: Val=12, loop=2 condition is true. Val = val/10; Val = 12/10; Val = 1; And loop will 3. Iteration4: Val=1, loop=3 condition is true. Val = val/10; Val = 1/10; Val = 0; And loop will 4. And condition is false because the value of variable 'val' is not greater than 0 Then we value of "val" will be printed on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer