Home »
Java »
Java find output programs
Java find output programs (Loops) | set 2
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.
Submitted by Nidhi, on January 30, 2021
Question 1
public class Main {
public static void main(String[] args) {
int val = 0;
for (;;) {
System.out.println("India");
}
}
}
Output
The above program will print "India" infinite times.
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.
Question 2
public class Main {
public static void main(String[] args) {
while ()
System.out.println("Hello World");
}
}
Output
Main.java:3: error: illegal start of expression
while ()
^
1 error
Explanation
The above program will generate syntax error because we cannot use the while loop without condition in Java.
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 )
}
}
Output
Main.java:8: error: ';' expected
} while ( val <= 10 )
^
1 error
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);
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);
}
}
Output
Main.java:4: error: cannot find symbol
var loop = 0;
^
symbol: class var
location: class Main
1 error
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.
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);
}
}
Output
0
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.