Java Control Statements and Loops

Last Updated :
Discuss
Comments

Question 1

What will be the output of the following code?

Java
int x = 5;
if (x > 2)
    if (x > 4)
        System.out.println("A");
    else
        System.out.println("B");


  • A

    A

  • B

    B

  • C

    Compilation Error

  • D

    No Output


Question 2

How many times will the following loop execute?

Java
int i = 1;
while (i <= 5) {
    System.out.println("Hello");
}


  • A

    5 times

  • B

    6 times

  • C

    Infinite times


  • D

    Compilation Error

Question 3

What is the output of the following Java code?

Java
for (int i = 0; i < 5; i++) {
    if (i == 2)
        break;
    System.out.print(i + " ");
}


  • A

    0 1 2 3 4

  • B

    0 1


  • C

    0 1 2

  • D

    No Output

Question 4

What is the correct syntax for a do-while loop in Java?

  • A

    do { } while (condition);


  • B

    while (condition) { }


  • C

    do (condition) { }


  • D

    while { condition };

Question 5

What will be the output of the following nested loop?

Java
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.print(i + "," + j + " ");
    }
}


  • A

    1,1 1,2 2,1 2,2 3,1 3,2

  • B

    1,1 2,1 3,1 1,2 2,2 3,2

  • C

    1,1 1,2 1,3 2,1 2,2 2,3

  • D

    Compilation Error

Question 6

What happens if the condition in an if statement is false?


  • A

    It throws an error

  • B

    Else block runs (if available)

  • C

    Code inside if runs

  • D

    Program exits

Question 7

Which loop guarantees execution at least once?


  • A

    for

  • B

    while


  • C

    do-while

  • D

    foreach

Question 8

Which keyword is used to skip the current iteration in a loop?


  • A

    break

  • B

    exit

  • C

    continue

  • D

    skip

Question 9

What is the correct structure for a switch-case block?

  • A

    switch {}

  • B

    switch:

  • C

    switch() {}

  • D

    switch[]

Question 10

Which loop is the best suited for traversing arrays directly?

  • A

    for

  • B

    while

  • C

    do-while

  • D

    for-each

There are 10 questions to complete.

Take a part in the ongoing discussion