LearnFrenzy
Sign in Take a free test

Java Programming · Topic 4 of 28

Arrays in Java

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Arrays in Java · Study material

Classic array algorithms

Two-pointer reversal, rotation with three reversals (O(n) time, O(1) space) and Kadane's maximum-subarray algorithm are three of the most frequently asked array techniques.

import java.util.Arrays;

public class Main {
    static void reverse(int[] a) {
        for (int i = 0, j = a.length - 1; i < j; i++, j--) { int t = a[i]; a[i] = a[j]; a[j] = t; }
    }

    static void rotateLeft(int[] a, int k) {          // reversal algorithm: O(n) time, O(1) extra space
        int n = a.length;
        k %= n;
        reverseRange(a, 0, k - 1);
        reverseRange(a, k, n - 1);
        reverseRange(a, 0, n - 1);
    }

    static void reverseRange(int[] a, int i, int j) {
        for (; i < j; i++, j--) { int t = a[i]; a[i] = a[j]; a[j] = t; }
    }

    static int maxSubarray(int[] a) {                 // Kadane's algorithm
        int best = a[0], current = a[0];
        for (int i = 1; i < a.length; i++) {
            current = Math.max(a[i], current + a[i]);
            best = Math.max(best, current);
        }
        return best;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7};
        reverse(a);
        System.out.println(Arrays.toString(a));
        int[] b = {1, 2, 3, 4, 5, 6, 7};
        rotateLeft(b, 3);
        System.out.println(Arrays.toString(b));
        System.out.println(maxSubarray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4}));
    }
}

Output

[7, 6, 5, 4, 3, 2, 1]
[4, 5, 6, 7, 1, 2, 3]
6

Copying arrays the right way

int[] src = {1, 2, 3, 4, 5};

int[] alias = src;                              // ✘ not a copy – same array
int[] a = src.clone();                          // ✔ full copy
int[] b = Arrays.copyOf(src, 8);                // ✔ copy and resize (pads with 0)
int[] c = Arrays.copyOfRange(src, 1, 4);        // ✔ part: [2, 3, 4]
int[] d = new int[5];
System.arraycopy(src, 0, d, 0, src.length);     // ✔ fastest, copies into an existing array

int[][] grid = {{1, 2}, {3, 4}};
int[][] shallow = grid.clone();                 // ✘ rows are shared!
int[][] deep = new int[grid.length][];
for (int i = 0; i < grid.length; i++) deep[i] = grid[i].clone();   // ✔ deep copy

Frequency counting with an array

// Counting values in a small known range: an int array beats a HashMap
int[] marks = {7, 3, 7, 9, 3, 7, 1};
int[] count = new int[11];                       // marks are 0..10
for (int m : marks) count[m]++;
// count[7] == 3, count[3] == 2

// Counting letters
int[] letters = new int[26];
for (char ch : "banana".toCharArray()) letters[ch - 'a']++;
// letters['a' - 'a'] == 3, letters['n' - 'a'] == 2

Array checklist

  • Loop with i < a.length.
  • Use for-each when you do not need the index.
  • Print with Arrays.toString / deepToString.
  • Copy explicitly; deep-copy nested arrays.
  • Compare with Arrays.equals / deepEquals.
  • Sort before binarySearch.
  • Prefer ArrayList when the size changes.
  • Check for empty arrays before reading a[0].

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links