LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 11

Reversing an array with two pointers Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        char[] c = "LEARN".toCharArray();
        for (int i = 0, j = c.length - 1; i < j; i++, j--) {
            char t = c[i];
            c[i] = c[j];
            c[j] = t;
        }
        System.out.println(Arrays.toString(c) + " " + new String(c));
    }
}
  • A [N, R, A, E, L] NRAEL Correct
  • B [L, E, A, R, N] LEARN
  • C [N, R, A, E, L] LEARN
  • D [N, E, A, R, L] NEARL
Correct Answer: Option A

Swapping the ends and moving inwards reverses the array; new String(char[]) builds a String from it.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links