Java Control (Looping) Statements Aptitude Questions and Answers.
This section contains Aptitude Questions and Answers on Java Control Statements (Looping) like for, do while, while and for each with explanation.
List of Control (Loop) Statements Aptitude Questions
2)
Is following code snippet is correct?
for(int i=1; i<=10; i++)
System.out.println(i);
- Yes
- No
Correct Answer: 1
Yes
Java allows block declaration of variables and we can declare a variable for single block only.
3)
What will be the output of following program?
public class temp
{
public static void main(String agrs[])
{
for(int i=1; i<=10; i++);
System.out.print(i);
}
}
- 12345678910
- 11
- Error
- 1 2 3 4 5 6 7 8 9 10
Correct Answer: 3
Error
Cannot find symbol – variable i,i is a block variable that can be used with in loop body only.
Statement
for(int i=1; i<=10; i++);
is terminated with semicolon (;) hence statement System.out.print(i); is not a part of loop.
4)
What will be the output of following program?
public class temp
{
public static void main(String agrs[])
{
int i;
for(i=1; i<=10; i++);
System.out.print(i);
}
}
- 12345678910
- 11
- Error
- 1 2 3 4 5 6 7 8 9 10
Correct Answer: 2
11
Consider the statement
for(i=1; i<=10; i++);
Since statement is terminated with semicolon (;), loop will be executed 10 times and then statement
System.out.print(i); will be executed.
5)
What will be the output of following program?
public class temp
{
public static void main(String agrs[])
{
int x[]={1,2,3,4,5};
for(int i=0; i<x.length;i++)
System.out.print(x[i]);
}
}
- Error – length is not a method of x.
- 6
- 1,2,3,4,5
- 12345
Correct Answer: 4
12345
length() method can be used with array, it returns total number of elements.