Author: saqibkhan

  • Arrays Class in Java

    In Java, the Arrays class is a utility class that is a member of the Java collection framework. It belongs to java.util package. The class provides various static methods for manipulating arrays efficiently. It simplifies common operations (like searching, sorting, copying and comparison) on the arrays.

    To read more Java Arrays

    Why Use the Java Arrays Class?

    The main reason for using the Java Arrays class is that it provides ready-made methods for complex logic. Here are some reasons why developers use it often.

    1. Convenience: The Arrays class is convenience for array manipulation because it provides various ready-made static methods to perform complex logic. It eliminates the need to write complex code for array operations.
    2. Efficiency: Methods in this class provide highly optimized algorithms (Dual-Pivot Quicksort for primitives and TimSort for objects). It offers better performance that increases efficiency.
    3. Readability: The methods of the Arrays class follow intuitive names (names that are easy to pronounce, spell, and understand, often having a straightforward and familiar sound) and behaviors that make code easier to read, understand, and maintain.
    4. Streamlining Code: By using the Arrays class, the code becomes cleaner and more concise. We can use the Arrays.toString() method to convert arrays into a String instead of writing a loop.
    5. Enhanced Functionality: The class provides advance capabilities like deep comparison by using the Arrays.deepEquals() method, filling arrays efficiently by using the Arrays,fill() method, and working with streams by using the Arrays.stream() method.
    6. Collection Compatibility: The class allows seamless conversion of arrays to lists, which makes it easier to work with the collection framework.

    Java Arrays Class Methods

    ManipulationMethod SignatureDescription
    Sortingsort(byte[] a)  Sorts the specified array into ascending numerical order.
    sort(byte[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(char[] a)  Sorts the specified array into ascending numerical order.
    sort(char[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(double[] a)Sorts the specified array into ascending numerical order.
    sort(double[] a, int fromIndex, int toIndex)
    Sorts the specified range of the array into ascending order.
    sort(float[] a)Sorts the specified array into ascending numerical order.
    sort(float[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(int[] a)Sorts the specified array into ascending numerical order.
    sort(int[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(long[] a)Sorts the specified array into ascending numerical order.
    sort(long[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(short[] a)Sorts the specified array into ascending numerical order.
    sort(short[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending order.
    sort(Object[] a)  Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
    sort(Object[] a, int fromIndex, int toIndex)  Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.
    sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
    sort(T[] a, Comparator<? super T> c)  Sorts the specified array of objects according to the order induced by the specified comparator.
    SearchingbinarySearch(byte[] a, byte key)Searches the specified array of bytes for the specified value using the binary search algorithm.
    binarySearch(byte[] a, int fromIndex, int toIndex, byte key)Searches a range of the specified array of bytes for the specified value using the binary search algorithm.
    binarySearch(char[] a, char key)Searches the specified array of chars for the specified value using the binary search algorithm.
    binarySearch(char[] a, int fromIndex, int toIndex, char key)Searches a range of the specified array of chars for the specified value using the binary search algorithm.
    binarySearch(double[] a, double key)Searches the specified array of doubles for the specified value using the binary search algorithm.
    binarySearch(double[] a, int fromIndex, int toIndex, double key)Searches a range of the specified array of doubles for the specified value using the binary search algorithm.
    binarySearch(float[] a, float key)  Searches the specified array of floats for the specified value using the binary search algorithm.
    binarySearch(float[] a, int fromIndex, int toIndex, float key)Searches a range of the specified array of floats for the specified value using the binary search algorithm.
    binarySearch(int[] a, int key)Searches the specified array of ints for the specified value using the binary search algorithm.
    binarySearch(int[] a, int fromIndex, int toIndex, int key)Searches a range of the specified array of ints for the specified value using the binary search algorithm.
    binarySearch(long[] a, int fromIndex, int toIndex, long key)Searches a range of the specified array of longs for the specified value using the binary search algorithm.
    binarySearch(long[] a, long key)  Searches the specified array of longs for the specified value using the binary search algorithm.
    binarySearch(short[] a, int fromIndex, int toIndex, short key)  Searches a range of the specified array of shorts for the specified value using the binary search algorithm.
    binarySearch(short[] a, short key)  Searches the specified array of shorts for the specified value using the binary search algorithm.
    binarySearch(Object[] a, int fromIndex, int toIndex, Object key)  Searches a range of the specified array for the specified object using the binary search algorithm.
    binarySearch(Object[] a, Object key)  Searches the specified array for the specified object using the binary search algorithm.
    binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)Searches a range of the specified array for the specified object using the binary search algorithm.
    binarySearch(T[] a, T key, Comparator<? super T> c)Searches the specified array for the specified object using the binary search algorithm.
    ComparisondeepEquals(Object[] a1, Object[] a2)Returns true if the two specified arrays are deeply equal to one another.
    deepHashCode(Object[] a)  Returns a hash code based on the “deep contents” of the specified array.
    deepToString(Object[] a)Returns a string representation of the “deep contents” of the specified array.
    equals(boolean[] a, boolean[] a2)  
    Returns true if the two specified arrays of booleans are equal to one another.
    equals(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of booleans, over the specified ranges, are equal to one another.
    equals(byte[] a, byte[] a2)Returns true if the two specified arrays of bytes are equal to one another.
    equals(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of bytes, over the specified ranges, are equal to one another.
    equals(char[] a, char[] a2)Returns true if the two specified arrays of chars are equal to one another.
    equals(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of chars, over the specified ranges, are equal to one another.
    equals(double[] a, double[] a2)Returns true if the two specified arrays of doubles are equal to one another.
    equals(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of doubles, over the specified ranges, are equal to one another.
    equals(float[] a, float[] a2)Returns true if the two specified arrays of floats are equal to one another.
    equals(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of floats, over the specified ranges, are equal to one another.
    equals(int[] a, int[] a2)Returns true if the two specified arrays of ints are equal to one another.
    equals(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of ints, over the specified ranges, are equal to one another.
    equals(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of longs, over the specified ranges, are equal to one another.
    equals(long[] a, long[] a2)Returns true if the two specified arrays of longs are equal to one another.
    equals(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of shorts, over the specified ranges, are equal to one another.

    equals(short[] a, short[] a2)  
    Returns true if the two specified arrays of shorts are equal to one another.
    equals(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)Returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.

    equals(Object[] a, Object[] a2)  
    Returns true if the two specified arrays of Objects are equal to one another.
    equals(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Returns true if the two specified arrays of Objects, over the specified ranges, are equal to one another.
    equals(T[] a, T[] a2, Comparator<? super T> cmp)Returns true if the two specified arrays of Objects are equal to one another.
    compare(boolean[] a, boolean[] b)Compares two boolean arrays lexicographically.
    compare(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Compares two boolean arrays lexicographically over the specified ranges.
    compare(byte[] a, byte[] b)Compares two byte arrays lexicographically.
    compare(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Compares two byte arrays lexicographically over the specified ranges.
    compare(char[] a, char[] b)Compares two char arrays lexicographically.
    compare(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Compares two char arrays lexicographically over the specified ranges.
    compare(double[] a, double[] b)Compares two double arrays lexicographically.
    compare(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Compares two double arrays lexicographically over the specified ranges.
    compare(float[] a, float[] b)Compares two float arrays lexicographically.
    compare(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Compares two float arrays lexicographically over the specified ranges.
    compare(int[] a, int[] b)Compares two int arrays lexicographically.
    compare(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Compares two int arrays lexicographically over the specified ranges.
    compare(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Compares two long arrays lexicographically over the specified ranges.
    compare(long[] a, long[] b)Compares two long arrays lexicographically.
    compare(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Compares two short arrays lexicographically over the specified ranges.
    compare(short[] a, short[] b)Compares two short arrays lexicographically.
    compare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex)Compares two Object arrays lexicographically over the specified ranges.
    compare(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Compares two Object arrays lexicographically over the specified ranges.
    compare(T[] a, T[] b)Compares two Object arrays, within comparable elements, lexicographically.
    compare(T[] a, T[] b, Comparator<? super T> cmp)Compares two Object arrays lexicographically using a specified comparator.
    compareUnsigned(byte[] a, byte[] b)Compares two byte arrays lexicographically, numerically treating elements as unsigned.
    compareUnsigned(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Compares two byte arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(int[] a, int[] b)Compares two int arrays lexicographically, numerically treating elements as unsigned.
    compareUnsigned(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Compares two int arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Compares two long arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(long[] a, long[] b)Compares two long arrays lexicographically, numerically treating elements as unsigned.
    compareUnsigned(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Compares two short arrays lexicographically over the specified ranges, numerically treating elements as unsigned.
    compareUnsigned(short[] a, short[] b)Compares two short arrays lexicographically, numerically treating elements as unsigned.
    CopyingcopyOf(boolean[] original, int newLength)Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
    copyOf(byte[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(char[] original, int newLength)Copies the specified array, truncating or padding with null characters (if necessary) so the copy has the specified length.
    copyOf(double[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(float[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(int[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(long[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(short[] original, int newLength)Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
    copyOf(T[] original, int newLength)Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
    copyOf(U[] original, int newLength, Class<? extends T[]> newType)Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length.
    copyOfRange(boolean[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(byte[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(char[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(double[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(float[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(int[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(long[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(short[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(T[] original, int from, int to)Copies the specified range of the specified array into a new array.
    copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)Copies the specified range of the specified array into a new array.
    Fillfill(boolean[] a, boolean val)Assigns the specified boolean value to each element of the specified array of booleans.
    fill(boolean[] a, int fromIndex, int toIndex, boolean val)Assigns the specified boolean value to each element of the specified range of the specified array of booleans.
    fill(byte[] a, byte val)Assigns the specified byte value to each element of the specified array of bytes.
    fill(byte[] a, int fromIndex, int toIndex, byte val)Assigns the specified byte value to each element of the specified range of the specified array of bytes.
    fill(char[] a, char val)Assigns the specified char value to each element of the specified array of chars.
    fill(char[] a, int fromIndex, int toIndex, char val)Assigns the specified char value to each element of the specified range of the specified array of chars.
    fill(double[] a, double val)Assigns the specified double value to each element of the specified array of doubles.
    fill(double[] a, int fromIndex, int toIndex, double val)Assigns the specified double value to each element of the specified range of the specified array of doubles.
    fill(float[] a, float val)Assigns the specified float value to each element of the specified array of floats.
    fill(float[] a, int fromIndex, int toIndex, float val)Assigns the specified float value to each element of the specified range of the specified array of floats.
    fill(int[] a, int val)Assigns the specified int value to each element of the specified array of ints.
    fill(int[] a, int fromIndex, int toIndex, int val)Assigns the specified int value to each element of the specified range of the specified array of ints.
    fill(long[] a, int fromIndex, int toIndex, long val)Assigns the specified long value to each element of the specified range of the specified array of longs.
    fill(long[] a, long val)Assigns the specified long value to each element of the specified array of longs.
    fill(short[] a, int fromIndex, int toIndex, short val)Assigns the specified short value to each element of the specified range of the specified array of shorts.
    fill(short[] a, short val)Assigns the specified short value to each element of the specified array of shorts.
    fill(Object[] a, int fromIndex, int toIndex, Object val)Assigns the specified Object reference to each element of the specified range of the specified array of Objects.
    fill(Object[] a, Object val)Assigns the specified Object reference to each element of the specified array of Objects.
    Streamstream(double[] array)Returns a sequential DoubleStream with the specified array as its source.
    stream(double[] array, int startInclusive, int endExclusive)Returns a sequential DoubleStream with the specified range of the specified array as its source.
    stream(int[] array)Returns a sequential IntStream with the specified array as its source.
    stream(int[] array, int startInclusive, int endExclusive)Returns a sequential IntStream with the specified range of the specified array as its source.
    stream(long[] array)Returns a sequential LongStream with the specified array as its source.
    stream(long[] array, int startInclusive, int endExclusive)Returns a sequential LongStream with the specified range of the specified array as its source.
    stream(T[] array)  Returns a sequential Stream with the specified array as its source.
    stream(T[] array, int startInclusive, int endExclusive)Returns a sequential Stream with the specified range of the specified array as its source.
    ConversiontoString(boolean[] a)Returns a string representation of the contents of the specified array.
    toString(byte[] a)Returns a string representation of the contents of the specified array.
    toString(char[] a)Returns a string representation of the contents of the specified array.
    toString(double[] a)Returns a string representation of the contents of the specified array.
    toString(float[] a)Returns a string representation of the contents of the specified array.
    toString(int[] a)Returns a string representation of the contents of the specified array.
    toString(long[] a)  Returns a string representation of the contents of the specified array.
    toString(short[] a)  Returns a string representation of the contents of the specified array.
    toString(Object[] a)Returns a string representation of the contents of the specified array.
     asList(T… a)Returns a fixed-size list backed by the specified array.
    UtilityhashCode(boolean[] a)Returns a hash code based on the contents of the specified array.
    hashCode(byte[] a)Returns a hash code based on the contents of the specified array.
    hashCode(char[] a)Returns a hash code based on the contents of the specified array.
    hashCode(double[] a)Returns a hash code based on the contents of the specified array.
    hashCode(float[] a)Returns a hash code based on the contents of the specified array.
    hashCode(int[] a)Returns a hash code based on the contents of the specified array.
    hashCode(long[] a)Returns a hash code based on the contents of the specified array.
    hashCode(short[] a)Returns a hash code based on the contents of the specified array.
    hashCode(Object[] a)Returns a hash code based on the contents of the specified array.
    mismatch(boolean[] a, boolean[] b)Finds and returns the index of the first mismatch between two boolean arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two boolean arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(byte[] a, byte[] b)Finds and returns the index of the first mismatch between two-byte arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two-byte arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(char[] a, char[] b)Finds and returns the index of the first mismatch between two char arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(char[] a, int aFromIndex, int aToIndex, char[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two char arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(double[] a, double[] b)Finds and returns the index of the first mismatch between two double arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(double[] a, int aFromIndex, int aToIndex, double[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two double arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(float[] a, float[] b)Finds and returns the index of the first mismatch between two float arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(float[] a, int aFromIndex, int aToIndex, float[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two float arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(int[] a, int[] b)Finds and returns the index of the first mismatch between two int arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two int arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two long arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(long[] a, long[] b)Finds and returns the index of the first mismatch between two long arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(short[] a, int aFromIndex, int aToIndex, short[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two short arrays over the specified ranges; otherwise, returns -1 if no mismatch is found.
    mismatch(short[] a, short[] b)Finds and returns the index of the first mismatch between two short arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(Object[] a, int aFromIndex, int aToIndex, Object[] b, int bFromIndex, int bToIndex)Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(Object[] a, Object[] b)Finds and returns the index of the first mismatch between two Object arrays; otherwise, returns -1 if no mismatch is found.
    mismatch(T[] a, int aFromIndex, int aToIndex, T[] b, int bFromIndex, int bToIndex, Comparator<? super T> cmp)Finds and returns the relative index of the first mismatch between two Object arrays over the specified ranges, otherwise returns -1 if no mismatch is found.
    mismatch(T[] a, T[] b, Comparator<? super T> cmp)Finds and returns the index of the first mismatch between two Object arrays; otherwise, returns -1 if no mismatch is found.
    Parallel ArrayparallelPrefix(double[] array, int fromIndex, int toIndex, DoubleBinaryOperator op)Performs parallelPrefix(double[], DoubleBinaryOperator) for the given subrange of the array.
    parallelPrefix(double[] array, DoubleBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelPrefix(int[] array, int fromIndex, int toIndex, IntBinaryOperator op)Performs parallelPrefix(int[], IntBinaryOperator) for the given subrange of the array.
    parallelPrefix(int[] array, IntBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelPrefix(long[] array, int fromIndex, int toIndex, LongBinaryOperator op)Performs parallelPrefix(long[], LongBinaryOperator) for the given subrange of the array.
    parallelPrefix(long[] array, LongBinaryOperator op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelPrefix(T[] array, int fromIndex, int toIndex, BinaryOperator<T> op)Performs parallelPrefix(Object[], BinaryOperator) for the given subrange of the array.
    parallelPrefix(T[] array, BinaryOperator<T> op)Cumulates, in parallel, each element of the given array in place, using the supplied function.
    parallelSetAll(double[] array, IntToDoubleFunction generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSetAll(int[] array, IntUnaryOperator generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSetAll(long[] array, IntToLongFunction generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSetAll(T[] array, IntFunction<? extends T> generator)Set all elements of the specified array, in parallel, using the provided generator function to compute each element.
    parallelSort(byte[] a)Sorts the specified array into ascending numerical order.
    parallelSort(byte[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(char[] a)Sorts the specified array into ascending numerical order.
    parallelSort(char[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(double[] a)Sorts the specified array into ascending numerical order.
    parallelSort(double[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(float[] a)Sorts the specified array into ascending numerical order.
    parallelSort(float[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(int[] a)Sorts the specified array into ascending numerical order.
    parallelSort(int[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(long[] a)Sorts the specified array into ascending numerical order.
    parallelSort(long[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(short[] a)Sorts the specified array into ascending numerical order.
    parallelSort(short[] a, int fromIndex, int toIndex)Sorts the specified range of the array into ascending numerical order.
    parallelSort(T[] a)Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.
    parallelSort(T[] a, int fromIndex, int toIndex)Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.
    parallelSort(T[] a, int fromIndex, int toIndex, Comparator<? super T> cmp)Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
    parallelSort(T[] a, Comparator<? super T> cmp)Sorts the specified array of objects according to the order induced by the specified comparator.
    SetsetAll(double[] array, IntToDoubleFunction generator)Set all elements of the specified array, using the provided generator function to compute each element.
    setAll(int[] array, IntUnaryOperator generator)Set all elements of the specified array, using the provided generator function to compute each element.
    setAll(long[] array, IntToLongFunction generator)Set all elements of the specified array, using the provided generator function to compute each element.
    setAll(T[] array, IntFunction<? extends T> generator)Set all elements of the specified array, using the provided generator function to compute each element.

    Arrays Class Method Example

    Let’s see some commonly used methods of the Java Arrays class.

    1. Sorting an Array by Using the sort() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int[] numbers = {5, 2, 8, 1, 3};         
    5.         Arrays.sort(numbers);         
    6.         System.out.println(“Sorted Array: ” + Arrays.toString(numbers));  
    7.     }  
    8. }  

    Compile and Run

    Output:

    Sorted Array: [1, 2, 3, 5, 8]

    When sorting in descending order, apply Arrays.sort() along with Collections.reverseOrder() treatment to Integer[] arrays.

    2. Comparing Two Arrays by Using the equals() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.    public static void main(String[] args) {  
    4.        int[] num1 = {6, 7, 8};  
    5.        int[] num2 = {6, 7, 8};  
    6.        System.out.println(Arrays.equals(num1, num2));  
    7.    }  
    8. }  

    Compile and Run

    Output:

    true

    3. Searching an Array by Using the binarySearch() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int[] numbers = {1, 3, 5, 7, 9};  
    5.         int index = Arrays.binarySearch(numbers, 5);  
    6.         System.out.println(“Index of 5 is: ” + index);  
    7.     }  
    8. }  

    Compile and Run

    Output:

    Index of 5 is: 2

    Note: The array must be sorted before using the binarySearch() method; otherwise, the results will be unpredictable.

    4. Filling an Array by Using the fill() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int[] arr = new int[5];  
    5.         Arrays.fill(arr, 10)  
    6.         System.out.println(“Filled Array: ” + Arrays.toString(arr));  
    7.     }  
    8. }  

    Output:

    Filled Array: [10, 10, 10, 10, 10]

    5. Copying an Array by Using the copyOf() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main{  
    3.     public static void main(String[] args) {  
    4.         int[] original = {1, 2, 3, 4, 5};  
    5.         int[] copied = Arrays.copyOf(original, 3);  
    6.         System.out.println(“Copied Array: ” + Arrays.toString(copied));  
    7.     }  
    8. }  

    Compile and Run

    Output:

    Copied Array: [1, 2, 3]

    6. Converting an Array by Using the toString() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         String[] names = {“Alice”, “Bob”, “Charlie”}  
    5.         System.out.println(“Array as String: ” + Arrays.toString(names));  
    6.     }  
    7. }  

    Output:

    Array as String: [Alice, Bob, Charlie]

    7. Comparing Two-Dimensional Arrays by Using the deepEquals() Method

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.    public static void main(String[] args) {  
    4.        int[][] numbers = {{4, 8, 0}, {9, 5, 1}, {7, 2, 6}};  
    5.        int[][] numbersCopy = Arrays.copyOf(numbers, numbers.length);  
    6.        System.out.println(“Are the given arrays equal to each other?”);  
    7.        System.out.println(Arrays.deepEquals(numbers, numbersCopy));  
    8.        System.out.println(Arrays.deepToString(numbersCopy));  
    9.    }  
    10. }  

    Compile and Run

    Output:

    Are the given arrays equal to each other?
    true
    [[4, 8, 0], [9, 5, 1], [7, 2, 6]]
    
  • Array Programs in Java

    In Java, an array is a linear data structure that has a collection of the same data type. These elements are stored in a contiguous memory location. In this section, we will discuss a variety of array programs, including array operations, manipulation, sorting, searching, etc.

    1. Java program to find the sum of the array elements.

    To find the sum of the array’s elements, first we have defined and declared an array. After that, we have defined a sum() method that adds array elements. Inside this method, the loop iterates over each element of the array and adds an element to the sum variable, repeatedly. In the main() method, we have called the sum() method that returns the sum of the array elements.

    Example

    1. class Main {  
    2.     static int arr[] = { 7, 4, 10, 9, 13, 26 };  
    3.     // method for the sum of elements   
    4.     static int sum()  
    5.     {  
    6.         int i, sum = 0;   
    7.         // Iterate through all elements and add them to the sum  
    8.         for (i = 0; i < arr.length; i++)  
    9.             sum += arr[i];  
    10.         return sum;  
    11.     }  
    12.     public static void main(String[] args)  
    13.     {  
    14.         System.out.println(“The sum of the given array is: “+ sum());  
    15.     }  
    16. }  

    Compile and Run

    Output:

    The sum of the given array is: 69

    2. Java program to find the reverse of an array.

    Reversing an array means writing an array from the last element to the first element. First, we have initializead an array. The loop iterates over the array until the array is reversed. We swap the first element with the last, the second with the second last, and so on. At last, we convert the array into a string and print the reversed array.

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {       
    4.         int[] arr = {1, 2, 3, 4, 5};  
    5.         // Swap elements from start to end  
    6.         for (int i = 0; i < arr.length / 2; i++) {  
    7.             int t = arr[i];  
    8.             arr[i] = arr[arr.length – 1 – i];  
    9.             arr[arr.length – 1 – i] = t;  
    10.         }  
    11.         System.out.println(“” + Arrays.toString(arr));  
    12.     }  
    13. }  

    Compile and Run

    Output:

    [5, 4, 3, 2, 1]

    3. Java program to merge two arrays.

    There are various ways to merge two arrays. But in this program, we have used user-defined logic to merge two arrays. This method is useful when we need full control over the merging process without relying on built-in functions. It directly merges the arrays.

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         int arr1[] = { 23, 45, 56, 78, 90};  
    5.         int arr2[] = { 3, 4, 6, 8, 9, 0, 7};  
    6.         // determining the length of both arrays  
    7.         int sizearr1 = arr1.length;  
    8.         int sizearr2 = arr2.length;  
    9.         // resultant array size  
    10.         int sizearr3 = sizearr1 + sizearr2;  
    11.         // Creating a new array   
    12.         int[] arr3 = new int[sizearr3];  
    13.         // Loop to store the elements of the first array into the resultant array  
    14.         for (int i = 0; i < sizearr1; i = i + 1) {    
    15.             // Storing the elements in the resultant array  
    16.             arr3[i] = arr1[i];  
    17.         }  
    18.         // Loop to concatenate the elements of the second array into the resultant array  
    19.         for (int i = 0; i < sizearr2; i = i + 1) {  
    20.             // Storing the elements in the resultant array  
    21.             arr3[sizearr1 + i] = arr2[i];  
    22.         }  
    23.         System.out.println(“” + Arrays.toString(arr3));  
    24.     }  
    25. }  

    Compile and Run

    Output:

    [23, 45, 56, 78, 90, 3, 4, 6, 8, 9, 0, 7]

    4. Java program to find the second most significant element in a sorted matrix.

    In a sorted matrix, the rows and columns of the elements are placed in ascending order. We can navigate the matrix and note the largest and second-largest elements to determine the second-largest element. The second-largest element will have been stored when the traverse is complete.

    The program uses a simple approach to find the second-largest element in a sorted matrix. It applies a nested loop to traverse the matrix in reverse order and compares each element with the largest and second-largest elements found so far. The program updates the largest and second-largest variables accordingly. Finally, it prints the value of the second-largest element.

    Example

    1. public class Main  
    2. {    
    3.     public static void main(String[] args)     
    4.     {    
    5.         int[][] matrix =     
    6.         {    
    7.             {1,2,3},    
    8.             {4,5,6},    
    9.             {7,8,9}    
    10.         };    
    11.         int rows=matrix.length;    
    12.         int cols=matrix[0].length;    
    13.         int largest=matrix[rows-1][cols-1]; // Initialize largest with the bottom-right element    
    14.         int secondLargest=matrix[rows-1][cols-2]; // Initialize secondLargest with the element before largest    
    15.             
    16.         // Traverse the matrix in reverse order    
    17.         for (int i=rows-1;i>=0;i–)     
    18.         {    
    19.             for (int j=cols-1;j>=0;j–)     
    20.             {    
    21.                 if (matrix[i][j]>largest)     
    22.                 {    
    23.                     secondLargest=largest; // Update secondLargest to the previous largest    
    24.                     largest=matrix[i][j]; // Update largest to the new largest element    
    25.                 }     
    26.               else if(matrix[i][j]>secondLargest&&matrix[i][j]<largest)     
    27.                 {    
    28.                     secondLargest=matrix[i][j];     
    29.                 }    
    30.             }    
    31.         }    
    32.         System.out.println(“Second largest element in the sorted matrix is: “+secondLargest);    
    33.     }    
    34. }    

    Compile and Run

    Output:

    Second largest element in the sorted matrix is: 8

    Complexity Analysis

    Time Complexity: O(rows * cols), where rows and cols are the dimensions of the matrix.

    Space Complexity: O(1), as we use constant additional space.

    5. Java program to find the k-th smallest element in a sorted matrix.

    In a sorted matrix, elements are arranged in ascending order, both row-wise and column-wise. The task is to find the kth smallest element in the matrix.

    The program uses a min-heap implemented with a PriorityQueue to find the kth smallest element in a sorted matrix. The findKthSmallest() method initializes the minHeap and adds the elements from the first column. It then performs k-1 iterations, extracting the minimum element, finding its indices, and adding the next element from the same row to the minHeap. Finally, the method returns the kth smallest element. The main function showcases the method by providing a sample matrix and k value.

    Example

    1. import java.util.*;    
    2. public class Main    
    3. {    
    4.     public static int findKthSmallest(int[][] matrix,int k)     
    5.     {    
    6.         int rows=matrix.length;    
    7.         int cols=matrix[0].length;    
    8.         PriorityQueue<Integer> minHeap=new PriorityQueue<>();    
    9.         for (int i=0;i<rows;i++) {    
    10.             minHeap.add(matrix[i][0]);    
    11.         }    
    12.         // Perform k-1 iterations    
    13.         for (int i=0;i<k-1;i++)     
    14.         {    
    15.             int minElement=minHeap.poll(); // Extract the minimum element    
    16.             // Get the row and column index of the extracted element    
    17.             int rowIndex=-1;    
    18.             int colIndex=-1;    
    19.             for (int j=0;j<rows;j++)     
    20.             {    
    21.                 for (int p=0;p<cols;p++)     
    22.                 {    
    23.                     if (matrix[j][p]==minElement)     
    24.                     {    
    25.                         rowIndex=j;    
    26.                         colIndex=p+1;    
    27.                         break;    
    28.                     }    
    29.                 }    
    30.             }    
    31.             // Add the next element from the same row to the min-heap    
    32.             if (colIndex<cols) {    
    33.                 minHeap.add(matrix[rowIndex][colIndex]);    
    34.             }    
    35.         }    
    36.         return minHeap.peek(); // Return the kth smallest element    
    37.     }    
    38.     public static void main(String[] args)     
    39.     {    
    40.         int[][] matrix={    
    41.             {1,3,5},    
    42.             {6,7,12},    
    43.             {11,14,14}    
    44.         };    
    45.         int k=4;    
    46.         int kthSmallest=findKthSmallest(matrix,k);    
    47.         System.out.println(“The “+ k+”-th smallest element in the sorted matrix is: “+kthSmallest);    
    48.     }    
    49. }    

    Compile and Run

    Output:

    The 4-th smallest element in the sorted matrix is: 6

    Complexity Analysis

    Time Complexity: The time complexity is O(k * log(rows)).

    Space Complexity: The space complexity is O(rows) for storing the elements in the min-heap.

    6. Java program to remove duplicate elements from a sorted array.

    In a sorted array, duplicate elements may occur consecutively. To put off duplicates from a looked-after array, we need to adjust the array in-place, making sure that each detail appears as effective as soon as. The Java program removes duplicates from a sorted array using the “RemoveDuplicates” class. The method “removeDuplicates” returns the new length of the modified array without duplicates. It checks if the array is empty, initializes “nextUnique” to 1, and traverses the array starting from the second element. It assigns unique elements to the position of “nextUnique” and increments it. After the loop, “nextUnique” represents the new length. The “main” function showcases the method by printing the modified array.

    Example

    1. import java.util.*;    
    2. public class Main    
    3. {    
    4.     public static int removeDuplicates(int[] nums)     
    5.     {    
    6.         int n=nums.length;    
    7.         if (n==0)     
    8.         {    
    9.             return 0;     
    10.         }    
    11.         int nextUnique=1;     
    12.         // Pointer to track the position of the next unique element    
    13.         // Traverse the array starting from the second element    
    14.         for (int current=1;current<n;current++)     
    15.         {    
    16.             // Compare the current element with the element at the next unique – 1    
    17.             if (nums[current]!=nums[nextUnique-1])     
    18.             {    
    19.    nums[nextUnique]=nums[current]; // Assign current element to nextUnique position    
    20.                 nextUnique++; // Increment nextUnique    
    21.             }    
    22.         }    
    23.         return nextUnique;     
    24.     }    
    25.     public static void main(String[] args)     
    26.     {    
    27.         int[] nums={1,1,2,2,3,4,4,5};    
    28.         int length=removeDuplicates(nums);    
    29.         System.out.print(“Modified Array: “);    
    30.         for (int i=0;i<length;i++)     
    31.         {    
    32.             System.out.print(nums[i]+” “);    
    33.         }    
    34.     }    
    35. }    

    Compile and Run

    Output:

    Modified Array: 1 2 3 4 5

    Complexity Analysis

    Time Complexity is O(n), where n is the array’s element count.

    Space complexity is O(1) since the array is modified directly without additional data structures.

    7. Java program to find the frequency of each word in a string array.

    We shall calculate the frequency of each word in a string array using a Java program. In a list of strings, we want to know how frequently each word appears. To calculate the frequency of each word in a string array, the program employs a hash map.

    A simple approach separates each string into words, and the number of each word is then saved in the hash map. After initializing a blank HashMap, the program loops through each string in the array. It determines if a word is present in the HashMap for each one it encounters.

    If it does, the frequency increases; if not, it is set to 1, and the word is added to the hash map. Finally, the program prints the word-frequency pairs stored in the HashMap. The approach efficiently tracks and counts the occurrences of each word, allowing for accurate frequency analysis of the words in the string array.

    Example

    1. import java.util.*;    
    2. public class Main   
    3. {    
    4.     public static void main(String[] args)     
    5.     {    
    6.         String[] strings={“Hello world”,”Hello Java”,”Java is great”,”Java is powerful”};         // Create a HashMap to store word-frequency pairs    
    7.         Map<String,Integer> frequencyMap=new HashMap<>();    
    8.         for (String str:strings)     
    9.         {    
    10.             // Split the string into words using whitespace as the delimiter    
    11.             String[] words=str.split(“\\s+”);    
    12.             // Count the occurrences of each word    
    13.             for (String word:words)     
    14.             {    
    15.                 // Check if the word already exists in the HashMap    
    16.                 if (frequencyMap.containsKey(word))     
    17.                 {    
    18.                     // If it exists, increment its frequency by 1    
    19.                     frequencyMap.put(word,frequencyMap.get(word)+1);    
    20.                 } else {    
    21.                     // If it does not exist, add it to the HashMap with a frequency of 1    
    22.                     frequencyMap.put(word,1);    
    23.                 }    
    24.             }    
    25.         }    
    26.         // Print the word-frequency pairs    
    27.         for (Map.Entry<String, Integer> entry : frequencyMap.entrySet()) {    
    28.             System.out.println(“Word: ” + entry.getKey() + “, Frequency: ” + entry.getValue());    
    29.         }    
    30.     }    
    31. }    

    Compile and Run

    Output:

    Word: Java, Frequency: 3
    Word: world, Frequency: 1
    Word: Hello, Frequency: 2
    Word: powerful, Frequency: 1
    Word: is, Frequency: 2
    Word: great, Frequency: 1
    

    Complexity Analysis

    The time complexity is O(n*m), where n represents the number of strings within the array and m is the maximum common sort of phrase in every string.

    The space complexity of the program is O(n), where n is the total wide variety of words inside the array.

    8. Java program to find the missing number in a sorted array of consecutive integers.

    Using the binary search method, we locate the missing integer in a sorted array of succeeding integers. The first detail’s index is low, and the remaining is high. We determine whether or not the missing integer is on the left or proper side of the array by computing the expected value for the middle element, which ought to be the same as the first element plus the centre index. The operation is repeated until there is only one element left in the search space, at which point we update low or high as necessary. The missing number will be the expected value at the index low.

    Example

    1. public class Main   
    2. {    
    3.     public static int findMissingNumber(int[] nums)     
    4.     {    
    5.         int low=0;    
    6.         int high=nums.length-1;    
    7.         // Perform binary search    
    8.         while (low<=high)     
    9.         {    
    10.             int mid=low+(high-low)/2;    
    11.             int expectedValue=nums[0]+mid;    
    12.             if (nums[mid]==expectedValue)     
    13.             {    
    14.                 // Missing number lies in the right half    
    15.                 low=mid+1;    
    16.             } else     
    17.             {    
    18.                 // Missing number lies in the left half    
    19.                 high=mid-1;    
    20.             }    
    21.         }    
    22.         // Return the missing number    
    23.         return nums[0]+low;    
    24.     }    
    25.     public static void main(String[] args)     
    26.     {    
    27.         int[] nums={1,2,3,4,6,7,8,9};    
    28.         int missingNumber=findMissingNumber(nums);    
    29.         System.out.println(“Missing number: “+missingNumber);    
    30.     }    
    31. }    

    Compile and Run

    Output:

    Missing number: 5

    Complexity Analysis

    Time Complexity: The binary search approach has a time complexity of O(log n), where n is the size of the array

    Space Complexity: The program has a space complexity of O(1), only using a few variables to track the low, high, and mid indices and the expected value.

    9. Java program to find the element that appears only once in an array.

    The technique used to find the element that appears most effectively at least once in an array is primarily based on the XOR operation. By XORing all the factors within the array, the factors that seem a fair number of instances will cancel out, leaving only the detail that appears best once. To enforce this approach, we initialize a variable ‘unique’ to zero. Then, we iterate through each detail inside the array and XOR it with the ‘particular’ variable. The result is stored back in ‘unique.’ At the end of the iteration, ‘unique’ will hold the element’s value that appears only once.

    Example

    1. public class Main     
    2. {    
    3.     public static int findUnique(int[] nums)     
    4.     {    
    5.         int unique=0;    
    6.         for (int num:nums)     
    7.         {    
    8.             unique^=num; // XOR the current element with ‘unique’    
    9.         }    
    10.         return unique;    
    11.     }    
    12.     
    13.     public static void main(String[] args)     
    14.     {    
    15.         int[] nums = {1,2,3,4,3,2,1};    
    16.         int uniqueElement=findUnique(nums);    
    17.         System.out.println(“The element that appears only once: ” + uniqueElement);    
    18.     }    
    19. }    

    Compile and Run

    Output:

    The element that appears only once: 4

    Complexity Analysis

    Time Complexity: The time complexity of this technique is O(n), where n is the length of the array.

    Space Complexity: The Space complexity is O(1) because we simplest use a single variable to keep the result.

    10. Java program to check if an array is a palindrome.

    To check if an array is a palindrome, we will use a pointer method where one pointer starts evolving at the start of the array and the alternative at the end. The elements are as compared to those suggestions, and we move them closer and nearer collectively until they meet at the centre. We conclude that the array is not a palindrome if the elements at any point at the pointers are not equal. Otherwise, if the loop completes without finding any unequal elements, then the array is a palindrome. The two-pointer approach allows us to efficiently check for palindromicity by eliminating the need for additional space.

    Example

    1. public class Main  
    2. {    
    3.     public static boolean isPalindrome(int[] nums)     
    4.     {    
    5.         int left=0;                     // Initialize the left pointer at the beginning of the array    
    6.         int right=nums.length-1;      // Initialize the right pointer at the end of the array    
    7. while (left<=right) {      // Continue the loop until the pointers meet or cross each other    
    8.  if (nums[left]!=nums[right])     
    9. {    
    10.    return false;             // If the elements at the pointers are not equal, the array is not a palindrome    
    11.             }    
    12.             left++;                           
    13.             right–;                          
    14.         }    
    15.  return true;    // If the loop completes without finding unequal elements, the array is a palindrome    
    16.     }    
    17.     public static void main(String[] args) {    
    18.         int[] nums={1,2,3,2,1};       
    19.         boolean isPalindrome=isPalindrome(nums);      
    20.         if (isPalindrome)     
    21.        {    
    22.             System.out.println(“The array is a palindrome.”);    
    23.         }     
    24.        else     
    25.        {    
    26.             System.out.println(“The array is not a palindrome.”);    
    27.         }    
    28.     }    
    29. }  

    Compile and Run

    Output:

    The array is a palindrome.

    Complexity Analysis

    The time complexity of the above approach is O(n), where n is the length of the array.

    The space complexity is O(1) as we are not using any extra space.

    11. Java program to shuffle elements of an array.

    To shuffle the elements of an array, we use the Fisher-Yates shuffle algorithm is commonly used. The procedure ensures that each array’s item is randomly permuted. Starting with the final entry in the array, the process iterates through the array in reverse order to get started. Each time, the current element is added to the range of the remaining unshrunk elements to create a random index. The element at the current index is then swapped with the element at the randomly generated index. The swapping continues until the first element is reached, resulting in a shuffled array with elements in random order.

    Example

    1. import java.util.Random;    
    2. public class Main     
    3. {    
    4.     public static void shuffle(int[] nums)     
    5.     {    
    6.         Random rand=new Random();    
    7.         for (int i=nums.length-1;i>=1;i–)     
    8.         {    
    9.             int j=rand.nextInt(i+1);    
    10.             // Swap the current element with the randomly selected element    
    11.             int temp=nums[i];    
    12.             nums[i]=nums[j];    
    13.             nums[j]=temp;    
    14.         }    
    15.     }    
    16.     public static void main(String[] args)     
    17.     {    
    18.         int[] nums = {1,2,3,4,5};    
    19.         System.out.println(“Original array: “);    
    20.         for (int num:nums)     
    21.       {    
    22.             System.out.print(num + ” “);    
    23.         }    
    24.         shuffle(nums);    
    25.         System.out.println(“\nShuffled array: “);    
    26.         for (int num:nums)     
    27.       {    
    28.             System.out.print(num + ” “);    
    29.         }    
    30.     }    
    31. }    

    Compile and Run

    Output:

    Original array:
    1 2 3 4 5
    Shuffled array:
    5 2 1 3 4
    

    Complexity Analysis

    The time complexity of this technique is O(N), where N is the size of the array.

    The space complexity is O(1) since we use a consistent quantity of extra space for the random variety.

    12. Java program to check if two matrices are orthogonal.

    To examine if two matrices are orthogonal, we evaluate the dot manufactured of corresponding rows or columns of the matrices. The matrices are said to be orthogonal if the dot product is 0 for all pairs. The algorithm iterates through the rows or columns, then calculates the dot product and returns false if any dot product is non-zero. It then checks for appropriate dimensions. If all dot products are zero, it returns true to indicate that the matrices are orthogonal.

    Example

    1. public class Main    
    2. {    
    3.     public static boolean areMatricesOrthogonal(int[][] matrix1,int[][] matrix2)     
    4. {    
    5.         int rows1=matrix1.length;    
    6.         int cols1=matrix1[0].length;    
    7.         int rows2=matrix2.length;    
    8.         int cols2=matrix2[0].length;    
    9.         // Check if matrices have compatible dimensions    
    10.         if (rows1 != rows2 || cols1 != cols2) {    
    11.             return false;    
    12.         }    
    13.         // Check the dot product for each row/column pair    
    14.         for (int i=0;i<rows1;i++) {    
    15.             int dotProduct = 0;    
    16.             for (int j=0;j<cols1;j++) {    
    17.                 dotProduct += matrix1[i][j] * matrix2[i][j];    
    18.             }    
    19.             if (dotProduct!=0)     
    20.             {    
    21.                 return false;    
    22.             }    
    23.         }    
    24.         return true;    
    25.     }    
    26.     public static void main(String[] args) {    
    27.         int[][] matrix1={{1,2},{3,4}};    
    28.         int[][] matrix2={{0,1},{-1,0}};    
    29.             
    30.         boolean areOrthogonal = areMatricesOrthogonal(matrix1, matrix2);    
    31.         if (areOrthogonal) {    
    32.             System.out.println(“The matrices are orthogonal.”);    
    33.         } else {    
    34.             System.out.println(“The matrices are not orthogonal.”);    
    35.         }    
    36.     }    
    37. }    

    Compile and Run

    Output:

    The matrices are not orthogonal.

    Complexity Analysis:

    The time complexity of this technique is O(n), where n is the range of rows or columns in the matrices.

    The space complexity is O(1), as no additional data structures are used.

    13. Java program to find the maximum element in a two-dimensional array.

    We initialize the variable ‘ max’ with the smallest value conceivable given the data type of the array elements to determine the greatest element in a two-dimensional array. The next step is to loop separately via the array’s rows and factors. Every element is compared to the modern fee of “max,” and if the detail is more, “max” is up to date. The maximum element in the two-dimensional array will be contained in ‘max’ once all items have been iterated through. By comparing each element to the current maximum value, the method enables us to determine the maximum element quickly.

    Example

    1. public class Main  
    2. {    
    3.     public static int findMaximumElement(int[][] array) {    
    4.         int max=Integer.MIN_VALUE; // Initialize max with the minimum value    
    5.         for (int i=0;i<array.length;i++)     
    6.         {    
    7.             // Iterate through each element of the row    
    8.             for (int j=0;j<array[i].length;j++)     
    9.             {    
    10.                 // Compare the current element with the current max value    
    11.                 if (array[i][j] > max) {    
    12.                     max=array[i][j];     
    13.                 }    
    14.             }    
    15.         }    
    16.         return max; // Return the maximum element    
    17.     }    
    18.     public static void main(String[] args) {    
    19.         int[][] array={    
    20.             {1, 2, 3},    
    21.             {4, 5, 6},    
    22.             {7, 8, 9}    
    23.         };    
    24.         int maximum=findMaximumElement(array);    
    25.         System.out.println(“The maximum element in the array is: “+maximum);    
    26.     }    
    27. }    

    Compile and Run

    Output:

    The maximum element in the array is: 9

    Complexity Analysis

    The time complexity of this approach is O(n * m), where n is the number of rows and m is the number of columns in the two-dimensional array.

    The space complexity is O(1) when you consider that we are not the usage of any extra area that grows with the entered size.

    14. Java program to find the sum of each diagonal in a matrix.

    To find the sum of each diagonal in a matrix, we iterate through the elements and calculate the diagonal index of every component by summing its row and column indices. We then add the element’s value to the corresponding diagonal sum in an array. After processing all elements, the array will contain the sum of each diagonal.

    Example

    1. public class Main {    
    2.     public static int[] getDiagonalSums(int[][] matrix) {    
    3.         int rows=matrix.length;    
    4.         int cols=matrix[0].length;    
    5.         int numDiagonals=rows+cols-1;    
    6.         int[] sums=new int[numDiagonals];    
    7.         for (int i=0;i<rows;i++)   {    
    8.             for (int j=0;j<cols;j++)    {    
    9.                 int diagonalIndex=i+j;    
    10.                 sums[diagonalIndex]+=matrix[i][j];    
    11.             }    
    12.         }    
    13.         return sums;    
    14.     }    
    15.     public static void main(String[] args) {    
    16.         int[][] matrix={    
    17.             {1, 2, 3},    
    18.             {4, 5, 6},    
    19.             {7, 8, 9}    
    20.         };    
    21.         int[] diagonalSums=getDiagonalSums(matrix);    
    22.         System.out.println(“Sum of each diagonal:”);    
    23.         for (int sum:diagonalSums)  {    
    24.             System.out.println(sum);    
    25.         }    
    26.     }    
    27. }    

    Compile and Run

    Output:

    Sum of each diagonal:
    1
    6
    15
    14
    9
    

    Complexity Analysis

    The approach has a time complexity of O(m*n), where m is the number of rows and n is the number of columns in the matrix.

    The space complexity is O(m + n), as we must store the diagonal sums in an array.

    15. Java program to find the element with the maximum frequency in an array.

    We use a HashMap to record the frequency of each element in the array to locate the element with the highest frequency. The element with the highest frequency can be recognized via looping through the array and updating the frequency within the hash map. Then, by comparing the frequency counts in the HashMap, we identify the element with the maximum frequency. The approach allows us to efficiently find the element with the highest frequency in the array.

    Example

    1. import java.util.*;  
    2. public class Main {  
    3.     public static int findMaxFrequencyElement(int[] nums) {  
    4.         Map<Integer, Integer> frequencyMap = new HashMap<>();  
    5.         for (int num : nums) {  
    6.             frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);  
    7.         }  
    8.         return Collections.max(frequencyMap.entrySet(), Map.Entry.comparingByValue()).getKey();  
    9.     }  
    10.     public static void main(String[] args) {  
    11.         int[] nums = {1, 2, 3, 2, 1, 2, 3, 3, 3};  
    12.         System.out.println(“Element with maximum frequency is: ” + findMaxFrequencyElement(nums));  
    13.     }  
    14. }  

    Compile and Run

    Output:

    Element with maximum frequency is: 3

    Complexity Analysis

    The time complexity of this technique is O(n), where n is the size of the array.

    The area complexity is O(n) because a HashMap can save up to n unique elements in the worst case.

    16. Java program to rotate a two-dimensional array clockwise.

    To rotate a two-dimensional array clockwise, we can follow a two-step approach: transposing the array and reversing each row. First, we iterate via the array and switch each detail at function (i, j) with the detail at the role (j, i), then successfully transpose the array. After, we iterate through each row of the transposed array and reverse it by swapping the elements from the start and end of the row until they meet in the middle. The process rotates the array clockwise.

    Example

    1. public class Main  {    
    2.     public static void rotateClockwise(int[][] matrix)  {    
    3.         int rows=matrix.length;    
    4.         int cols=matrix[0].length;    
    5.         // Transpose the array    
    6.         for (int i=0;i<rows;i++)    {    
    7.             for (int j=i;j<cols;j++)   {    
    8.                 int temp=matrix[i][j];    
    9.                 matrix[i][j]=matrix[j][i];    
    10.                 matrix[j][i]=temp;    
    11.             }    
    12.         }    
    13.         // Reverse each row    
    14.         for (int i=0;i<rows;i++)   {    
    15.             int left=0;    
    16.             int right=cols-1;    
    17.             while (left<right)    {    
    18.                 int temp=matrix[i][left];    
    19.                 matrix[i][left]=matrix[i][right];    
    20.                 matrix[i][right]=temp;    
    21.                 left++;    
    22.                 right–;    
    23.             }    
    24.         }    
    25.     }    
    26.     public static void main(String[] args) {    
    27.         int[][] matrix = {    
    28.             {1, 2, 3},    
    29.             {4, 5, 6},    
    30.             {7, 8, 9}    
    31.         };    
    32.         System.out.println(“Original Matrix:”);    
    33.         printMatrix(matrix);    
    34.         rotateClockwise(matrix);    
    35.         System.out.println(“Rotated Matrix:”);    
    36.         printMatrix(matrix);    
    37.     }    
    38.     public static void printMatrix(int[][] matrix) {    
    39.         int rows=matrix.length;    
    40.         int cols=matrix[0].length;    
    41.         for (int i=0;i<rows;i++)   {    
    42.             for (int j=0;j<cols;j++)       {    
    43.                 System.out.print(matrix[i][j]+” “);    
    44.             }    
    45.             System.out.println();    
    46.         }    
    47.         System.out.println();    
    48.     }    
    49. }   

    Compile and Run

    Output:

    Original Matrix:
    1 2 3
    4 5 6
    7 8 9
    
    Rotated Matrix:
    7 4 1
    8 5 2
    9 6 3
    

    Complexity Analysis

    The time complexity of this approach is O(n2), where n is the size of the array.

    The space complexity is O(1) as we carry out the rotation in-place without using any additional storage systems.

    17. Java program to sort a two-dimensional array across columns.

    We construct a custom comparator that compares rows based on the required column to sort a two-dimensional array across columns. The Arrays.sort() method is called with the custom comparator as an argument. The sorting algorithm employs a comparator to compare rows according to the selected column and arrange them correctly. We can quickly sort the two-dimensional array across columns using this method.

    Example

    1. import java.util.Arrays;    
    2. import java.util.Comparator;    
    3. public class Main {    
    4.     public static void sortByColumn(int[][] matrix, int column) {    
    5.         // Use Arrays.sort() with a custom comparator to sort the matrix by the specified column    
    6.         Arrays.sort(matrix,Comparator.comparingInt(row -> row[column]));    
    7.     }    
    8.     public static void main(String[] args) {    
    9.         int[][] matrix = {    
    10.             {13, 12, 11},    
    11.             {6, 5, 4},    
    12.             {19, 18, 17}    
    13.         };    
    14.         int columnToSortBy=1;    
    15.         System.out.println(“Original Matrix:”);    
    16.         printMatrix(matrix);    
    17.         sortByColumn(matrix,columnToSortBy);    
    18.         System.out.println(“Sorted Matrix by Column ” + columnToSortBy + “:”);    
    19.         printMatrix(matrix);    
    20.     }    
    21.     public static void printMatrix(int[][] matrix) {    
    22.         int rows=matrix.length;    
    23.         int cols=matrix[0].length;    
    24.         for (int i=0;i<rows;i++)   {    
    25.             for (int j=0;j<cols;j++)   {    
    26.                 System.out.print(matrix[i][j]+” “);    
    27.             }    
    28.             System.out.println();    
    29.         }    
    30.         System.out.println();    
    31.     }    
    32. }    

    Compile and Run

    Output:

    Original Matrix:
    13 12 11
    6 5 4
    19 18 17
    
    Sorted Matrix by Column 1:
    6 5 4
    13 12 11
    19 18 17
    

    Complexity Analysis

    The time complexity of this approach is O(n log n), where n is the number of rows in the matrix.

    The space complexity is O(1) since the sorting is done in place.

    18. Java program to perform matrix exponentiation to compute Fibonacci numbers efficiently.

    We might also describe the Fibonacci sequence as a matrix and calculate matrix multiplication to compute the Fibonacci numbers using matrix exponentiation speedily. The manner includes creating a transformation matrix that represents the Fibonacci series, utilizing matrix multiplication and exponentiation strategies, and then elevating the matrix to the necessary power using the powerMatrix approach. By deleting the Fibonacci number from the following matrix, we can also quickly calculate Fibonacci numbers.

    Example

    1. public class Main {    
    2.     public static long computeFibonacci(int n)   {    
    3.         if (n<=0)   {    
    4.             return 0;    
    5.         }    
    6.         // Fibonacci transformation matrix    
    7.         long[][] fibMatrix = {{1, 1}, {1, 0}};    
    8.         // Raise fibMatrix to the power of (n-1)    
    9.         fibMatrix = powerMatrix(fibMatrix, n – 1);    
    10.         // Extract the Fibonacci number from the matrix    
    11.         return fibMatrix[0][0];    
    12.     }    
    13.     private static long[][] powerMatrix(long[][] matrix, int power) {    
    14.         if (power == 0) {    
    15.             // Identity matrix    
    16.             return new long[][]{{1, 0}, {0, 1}};    
    17.         }    
    18.         if (power == 1) {    
    19.             return matrix;    
    20.         }    
    21.         long[][] result = powerMatrix(matrix, power / 2);    
    22.         result = multiplyMatrices(result, result);    
    23.         if (power % 2 != 0) {    
    24.             result = multiplyMatrices(result, matrix);    
    25.         }    
    26.         return result;    
    27.     }    
    28.     private static long[][] multiplyMatrices(long[][] matrix1,long[][] matrix2)    {    
    29.         long[][] result=new long[2][2];    
    30.         result[0][0]=matrix1[0][0]*matrix2[0][0]+matrix1[0][1]*matrix2[1][0];    
    31.         result[0][1]=matrix1[0][0]*matrix2[0][1]+matrix1[0][1]*matrix2[1][1];    
    32.         result[1][0]=matrix1[1][0]*matrix2[0][0]+matrix1[1][1]*matrix2[1][0];    
    33.         result[1][1]=matrix1[1][0]*matrix2[0][1]+matrix1[1][1]*matrix2[1][1];    
    34.         return result;    
    35.     }    
    36.     public static void main(String[] args)    {    
    37.         int n=10;    
    38.         long fibonacci=computeFibonacci(n);    
    39.         System.out.println(“Fibonacci number at position “+n+” is: “+fibonacci);    
    40.     }    
    41. }    

    Compile and Run

    Output:

    Fibonacci number at position 10 is: 55

    Complexity Analysis

    The time complexity of this approach is O(log n) since we perform matrix multiplication using the exponentiation by squaring technique.

    The space complexity is O(1) since we only need a fixed-size matrix and a few additional variables.

    19. Given an array of integers, rearrange the array such that all even numbers appear before all odd numbers.

    Note: Maintaining the relative order is not relevant for this problem.

    We can use a two-pointer technique to reorder an array so that all even numbers appear before all odd numbers. While the right pointer begins at the end and advances backwards, the left pointer moves ahead from the beginning. The elements pointed by the left and right pointers are examined at each step, and swaps are made as needed. All even numbers will be arranged before odd numbers by the time the loop is complete.

    Example

    1. public class Main     
    2. {    
    3.     public static void rearrangeArray(int[] arr)     
    4.     {    
    5.         int left=0;    
    6.         int right=arr.length-1;    
    7.         while (left<=right)   {    
    8.             if (arr[left]%2==0)    {    
    9.                 left++; // Move the left pointer forward if the element is even    
    10.             } else if (arr[right]%2==1)   {    
    11.                 right–; // Move the right pointer backwards if the element is odd    
    12.             } else {    
    13.     swap(arr,left,right); // Swap the elements if the left element is odd and the right element is even    
    14.                 left++; // Move the left pointer forward    
    15.                 right–; // Move the right pointer backwards    
    16.             }    
    17.         }    
    18.     }    
    19.     public static void swap(int[] arr,int i,int j)   {    
    20.         int temp=arr[i];    
    21.         arr[i]=arr[j];    
    22.         arr[j]=temp;    
    23.     }    
    24.     public static void main(String[] args)    {    
    25.         int[] arr = {1,2,3,4,5,6,7,8,9};    
    26.         System.out.println(“Original Array: “);    
    27.         printArray(arr);    
    28.         rearrangeArray(arr);    
    29.         System.out.println(“Rearranged Array: “);    
    30.         printArray(arr);    
    31.     }    
    32.     public static void printArray(int[] arr)   {    
    33.         for (int num:arr)   {    
    34.             System.out.print(num+” “);    
    35.         }    
    36.         System.out.println();    
    37.     }    
    38. }    

    Compile and Run

    Output:

    Original Array:
    1 2 3 4 5 6 7 8 9
    Rearranged Array:
    8 2 6 4 5 3 7 1 9
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the number of elements in the array.

    The space complexity is O(1) as we perform the rearrangement in place without using any additional data structures.

    20. Java program to find the smallest missing positive number in an unsorted array.

    We can rearrange the array by assigning each positive integer to its appropriate index to discover the smallest missing positive number in an unsorted array. You can accomplish this by looping through the array and switching each element with a positive integer with the one at the desired index. The array is iterated once more to locate the first index where an element no longer corresponds to the required value after the rearrangement. The index corresponds to the smallest missing positive number. If all elements match their desired values, the smallest missing positive number is the next positive integer after the array size.

    Example

    1. public class Main    
    2. {    
    3.     public static int findSmallestMissingPositive(int[] nums)    
    4.     {    
    5.         int n=nums.length;    
    6.         // Rearrange the array    
    7.         for (int i=0;i<n;i++)     
    8.         {    
    9.             while (nums[i]>0&&nums[i]<=n&&nums[nums[i]-1]!=nums[i])     
    10.             {    
    11.                 swap(nums,i,nums[i]-1);    
    12.             }    
    13.         }    
    14.         //Find the smallest missing positive number    
    15.         for (int i=0;i<n;i++)     
    16.         {    
    17.             if (nums[i]!=i+1)     
    18.             {    
    19.                 return i+1;    
    20.             }    
    21.         }    
    22.         // If all elements match their desired values, return the next positive integer    
    23.         return n+1;    
    24.     }    
    25.     public static void swap(int[] nums,int i,int j)     
    26.     {    
    27.         int temp=nums[i];    
    28.         nums[i]=nums[j];    
    29.         nums[j]=temp;    
    30.     }    
    31.     public static void main(String[] args)     
    32.     {    
    33.         int[] nums={3,4,-1,1};    
    34.         int smallestMissingPositive = findSmallestMissingPositive(nums);    
    35.         System.out.println(“Smallest Missing Positive Number: “+smallestMissingPositive);    
    36.     }    
    37. }   

    Compile and Run

    Output:

    Smallest Missing Positive Number: 2

    Complexity Analysis

    The approach ensures a time complexity of O(n) and a space complexity of O(1) as we perform the rearrangement and search in place without additional data structures.

    21. Java program to find the intersection of two arrays.

    The best approach to finding the intersection of two arrays is to use a HashSet data structure. We create a HashSet and add all elements from one array to it. Then, we iterate through the second array and check if each element exists in the HashSet. If it does, we add it to the result ArrayList and remove it from the HashSet to avoid duplicates.

    Example

    1. import java.util.ArrayList;    
    2. import java.util.HashSet;    
    3. import java.util.List;    
    4. public class Main{    
    5.     public static List<Integer> intersection(int[] nums1, int[] nums2) {    
    6.         HashSet<Integer> set=new HashSet<>();    
    7.         List<Integer> result=new ArrayList<>();    
    8.         // Add elements of nums1 to the set    
    9.         for (int num:nums1)  {    
    10.             set.add(num);    
    11.         }    
    12.         // Check for intersection in nums2    
    13.         for (int num:nums2)   {    
    14.             if (set.contains(num))   {    
    15.                 result.add(num);    
    16.                 set.remove(num);    
    17.             }    
    18.         }    
    19.         return result;    
    20.     }    
    21.     public static void main(String[] args) {    
    22.         int[] nums1 = {1, 2, 2, 1};    
    23.         int[] nums2 = {2, 2};    
    24.         List<Integer> intersection=intersection(nums1, nums2);    
    25.         System.out.println(“Intersection: “+intersection);    
    26.     }    
    27. }    

    Compile and Run

    Output:

    Intersection: [2]

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the size of the larger array.

    The space complexity is O(m), where m is the size of the HashSet.

    22. Java program to find the longest subarray with an equal number of 0s and 1s.

    Utilizing the prefix sum method, we can determine the longest subarray that contains an equal number of 0s and 1s. We can calculate the running sum while traversing the array by assigning a value of 1 for every 1 and -1 for every 0. When the running sum reaches zero, the number of 0s and 1s we have seen thus far is equal. To find the longest subarray, we store the running sum in a HashMap and its corresponding index. If the same running sum appears again, we update the maximum length by subtracting the stored index from the current index. By keeping track of the maximum length throughout the iteration, we can find the longest subarray with equal 0s and 1s.

    Example

    1. import java.util.HashMap;    
    2. public class Main {    
    3.     public static int findMaxLength(int[] nums)   {    
    4.         int maxLength=0;    
    5.         int runningSum=0;    
    6.         HashMap<Integer,Integer> sumMap=new HashMap<>();    
    7.         sumMap.put(0,-1); // Handle the case when the subarray starts from the beginning    
    8.         for (int i=0;i<nums.length;i++)   {    
    9.             runningSum+=nums[i]==0?-1:1;    
    10.             if (sumMap.containsKey(runningSum))    {    
    11.                 int startIndex=sumMap.get(runningSum);    
    12.                 maxLength=Math.max(maxLength,i-startIndex);    
    13.             } else {    
    14.                 sumMap.put(runningSum,i);    
    15.             }    
    16.         }    
    17.         return maxLength;    
    18.     }    
    19.     public static void main(String[] args)    {    
    20.         int[] nums = {0, 1, 0, 0, 1, 1, 0};    
    21.         int maxLength=findMaxLength(nums);    
    22.   System.out.println(“Length of the longest subarray with equal 0s and 1s is: “+maxLength);    
    23.     }    
    24. }    

    Compile and Run

    Output:

    Length of the longest subarray with equal 0s and 1s: 6

    Complexity Analysis

    The time complexity of this approach is O(n) since we iterate through the array once.

    The space complexity is O(n) as we store the running sum and its corresponding index in the HashMap.

    23. Java program to find the maximum product of two integers in an array.

    To find the maximum product of two integers in an array, we iterate through the array and keep track of the maximum and second maximum elements. We initialize max1 and max2 to the smallest possible integer values. Then, for each element, we compare it with max1 and update max2 and max1 accordingly. After iterating through the array, the maximum product is the product of max1 and max2, as max1 will hold the largest element and max2 will hold the second largest element.

    Example

    1. public class Main {    
    2.     public static int findMaximumProduct(int[] arr)  {    
    3.       int max1=Integer.MIN_VALUE; // Initialize the maximum element to the smallest possible value    
    4.         int max2=Integer.MIN_VALUE; // Initialize the second maximum element to the smallest possible value    
    5.         for (int num:arr)    {    
    6.             if (num>max1)    {    
    7.                 max2=max1; // Update the second maximum element    
    8.                 max1=num; // Update the maximum element    
    9.             }     
    10.             else if (num>max2)    {    
    11.                 max2=num; // Update the second maximum element    
    12.             }    
    13.         }    
    14.         return max1*max2; // Return the maximum product    
    15.     }    
    16.     public static void main(String[] args)    {    
    17.         int[] arr={1,2,3,4,5};    
    18.         int maximumProduct=findMaximumProduct(arr);    
    19.         System.out.println(“Maximum Product: “+maximumProduct);    
    20.     }    
    21. }    

    Compile and Run

    Output:

    Maximum Product: 20

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the size of the array.

    The space complexity is O(1) since we only use constant extra space to store the maximum and second maximum elements.

    24. Java program to find the smallest subarray length with a sum greater than a given value.

    To find the smallest subarray length with a sum greater than a given value, we can utilize the sliding window technique. The approach involves maintaining a window that expands and contracts while calculating the current sum. We start with an empty window and gradually expand it by adding elements from the right end. If the current sum exceeds the given value, we update the minimum length of the subarray. Then, until the current total is less than or equal to the specified value, we contract the window from the left end by eliminating items. Until we reach the end of the array, we keep doing this.

    Example

    1. public class Main{    
    2.     public static int findSmallestSubarray(int[] arr,int target)   {    
    3.         int minLength=Integer.MAX_VALUE; // Variable to store the minimum length of the subarray    
    4.         int currentSum=0; // Variable to track the current sum of the subarray    
    5.         int left=0; // Left pointer to mark the start of the subarray    
    6.         int right=0; // Right pointer to mark the end of the subarray    
    7.         while (right<arr.length) {    
    8.         currentSum+=arr[right]; // Add the element at the right pointer to the current sum            while (currentSum>target)   {    
    9.   minLength=Math.min(minLength,rightleft+1); // Update the minimum length if necessary    
    10.     currentSum=arr[left]; // Subtract the element at the left pointer from the current sum  
    11.                 left++; // Move the left pointer to the right to contract the window    
    12.             }    
    13.             right++; // Move the right pointer to the right to expand the window    
    14.         }    
    15.         return (minLength==Integer.MAX_VALUE)?-1:minLength;     
    16.     }    
    17.     public static void main(String[] args)   {    
    18.         int[] arr={1, 4, 45, 6, 0, 19};    
    19.         int target=51;    
    20.         int smallestSubarrayLength=findSmallestSubarray(arr,target);    
    21.         System.out.println(“Smallest Subarray Length: “+smallestSubarrayLength);    
    22.     }    
    23. }    

    Compile and Run

    Output:

    Smallest Subarray Length: 3

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the size of the array.

    The space complexity is O(1) since we only use constant extra space to store variables.

    25. Java program to find the triplet with the smallest sum in an array.

    We can take the help of three variables (an integer array of size three will also do the work), and using a loop, we can find the minimum elements present in the given array. We will be looking for the minimum elements as we have to find the smallest sum.

    Example

    1. public class Main   {    
    2. public static void findSmallestTripletSum(int[] arr)  {    
    3. int n = arr.length; // finding the size    
    4. // for storing the first three minimum values present in the given array.    
    5. int fMin = Integer.MAX_VALUE;    
    6. int sMin = Integer.MAX_VALUE;    
    7. int tMin = Integer.MAX_VALUE;     
    8. for (int i = 0; i < n; i++)   {     
    9. // getting the first, second and third minimum elements     
    10. if (arr[i] < fMin)   {     
    11.     tMin = sMin;     
    12.     sMin = fMin;     
    13.     fMin = arr[i];     
    14. }     
    15. // updating the second and third minimum elements     
    16. else if (arr[i] < sMin)   {     
    17.     tMin = sMin;     
    18.     sMin = arr[i];     
    19. }     
    20. else if (arr[i] < tMin)   {     
    21.     tMin = arr[i];     
    22. }     
    23. }    
    24. // print statement    
    25. System.out.println(“The Triplet with the smallest sum is: {“+ fMin + “, ” + sMin + “, ” + tMin + “}”);    
    26. }    
    27. // main method    
    28. public static void main(String[] args)   {    
    29. int[] arr = {5, 1, -3, -4, -2, 6};    
    30. findSmallestTripletSum(arr);    
    31. }    
    32. }    

    Compile and Run

    Output:

    The Triplet with the smallest sum is: {-4, -3, -2}

    Complexity Analysis

    The time complexity of this approach is O(n) since we are only using one loop in the program.

    The space complexity is O(1), as we are not using any extra space that grows with the input size.

    26. Java program to increment all elements of an array by one.

    The input array is defined as {1, 2, 3, 4, 5}. The method incrementArrayElements(int[] array) accepts an array as an argument. It then uses a for loop to iterate over each element in the array. Increment Operation: Inside the loop, the code array[i]++ increments each element by one. The final output is printed in the main() method, where the incremented array elements are displayed.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         int[] array = {1, 2, 3, 4, 5};    
    4.         incrementArrayElements(array);    
    5.         // Print the incremented array    
    6.         for (int i = 0; i < array.length; i++) {    
    7.             System.out.print(array[i] + ” “);    
    8.         }    
    9.     }    
    10.     public static void incrementArrayElements(int[] array) {    
    11.         for (int i = 0; i < array.length; i++) {    
    12.             array[i]++;    
    13.         }    
    14.     }    
    15. }   

    Compile and Run

    Output:

    2 3 4 5 6

    27. Java program to move all zeroes to the end of the array.

    For this approach, we traverse the array twice. In the first traversal, we do the following:

    • Iterate through the array while counting non-zero elements. Initialize the count at 0, which also indicates the position for the next non-zero element in the array.
    • For each non-zero element, position it at arr[count] and then increase the count by 1.
    • Once all elements have been processed, all non-zero entries will be moved to the front, keeping their original sequence.

    In the second traversal, we do the following:

    • Following the initial traversal, all non-zero elements will occupy the beginning of the array, while the variable ‘count’ will indicate the position for the first zero.
    • Proceed from ‘count’ to the end of the array, filling all subsequent indices with 0.

    Example

    1. public class Main {  
    2.     public static void main(String[] args) {  
    3.         int[] arr = {1, 0, 2, 0, 3, 0, 4, 0};  
    4.         int n = arr.length;  //finding array length  
    5.         int count = 0;  
    6.         for (int i = 0; i < n; i++) { //loop iterate over the array  
    7.             if (arr[i] != 0) {  //compare if the array element is equals to zero or not  
    8.                 arr[count++] = arr[i];  //  
    9.             }  
    10.         }  
    11.         while (count < n) {  
    12.             arr[count++] = 0;  
    13.         }  
    14.         System.out.println(“Array after moving zeroes: ” + java.util.Arrays.toString(arr));  
    15.     }  
    16. }  

    Compile and Run

    Output:

    Array after moving zeroes: [1, 2, 3, 4, 0, 0, 0, 0]

    28. Reverse an array without changing the position of zeroes.

    To solve the problem, the method involves moving through the array from both ends and swapping non-zero elements until reaching the centre. Throughout this procedure, the positions of zeroes are left intact. The code employs a while loop to bypass zeroes while decrementing the index from the end. When a non-zero element is detected, it gets swapped with the corresponding non-zero element from the opposite end. This swapping continues until the centre of the array is reached.

    Example

    1. import java.util.Arrays;  
    2. public class Main {  
    3. // Print function  
    4. public static void printReverse(int[] arr) {  
    5.     // Print the original array  
    6.     System.out.print(“Original array: “);  
    7.     System.out.println(Arrays.toString(arr));  
    8.     // Reverse the array without changing the position of zeroes  
    9.     // Initialize the index to the last element  
    10.     int j = arr.length – 1;  
    11.     for (int i = 0; i < j; i++) {  
    12.     // If the current element is zero, skip to the next element  
    13.     if (arr[i] == 0) {  
    14.         continue;  
    15.     }  
    16.     // If the current element is zero from the end  
    17.     while (j > i && arr[j] == 0) {  
    18.         // Decrement the index to the previous element  
    19.         j–;  
    20.     }  
    21.     // Swap the elements  
    22.     int temp = arr[i];  
    23.     arr[i] = arr[j];  
    24.     arr[j] = temp;  
    25.     // Decrement the index to the previous element  
    26.     j–;  
    27.     }  
    28.     // Prints the reversed array  
    29.     System.out.print(“Reversed array: “);  
    30.     System.out.println(Arrays.toString(arr));  
    31. }  
    32. public static void main(String[] args) {  
    33.     int[] arr = { 6, 0, 8, 0, 2, 0, 1 };  
    34.     printReverse(arr);  
    35. }  
    36. }  

    Compile and Run

    Output:

    Original array: [6, 0, 8, 0, 2, 0, 1]
    Reversed array: [1, 0, 2, 0, 8, 0, 6]
    

    29. Java program to find the leader element in an array.

    Given an array arr[] of size n, the task is to find all the Leaders in the array. An element is a Leader if it is greater than or equal to all the elements to its right side.

    Note: The rightmost element is always a leader.

    Example

    1. public class Main {  
    2.     public static void main(String[] args) {  
    3.         int[] arr = {12, 11, 4, 7, 9, 6, 8, 15};  
    4.         int n = arr.length;  
    5.         int maxFromRight = arr[n – 1];  
    6.         System.out.print(“Leader is: ” + maxFromRight + ” “);  
    7.         for (int i = n – 2; i >= 0; i–) {  
    8.             if (arr[i] > maxFromRight) {  
    9.                 maxFromRight = arr[i];  
    10.                 System.out.print(maxFromRight + ” “);  
    11.             }  
    12.         }  
    13.     }  
    14. }  

    Compile and Run

    Output:

    Leader is: 15

    30. Java program to find all the non-empty subarrays.

    To create a subarray, we first need a starting index from the original array. We can choose this starting index by looping through the range [0 to n-1] and treating each index i as a potential starting point. For each selected starting index i, we then determine an ending index from the range [i to n-1]. A nested loop, running from [i to n-1], will assist in selecting the ending index. Once both the starting and ending indices are established, an innermost loop will be required to print the elements of the subarray.

    Example

    1. import java.util.ArrayList;  
    2. public class Main {  
    3.     //Prints all subarrays in arr[0..n-1]  
    4.     static void findSubArray(ArrayList<Integer> arr) {  
    5.         int n = arr.size();  
    6.         // Pick starting point  
    7.         for (int i = 0; i < n; i++) {           
    8.             // Pick ending point  
    9.             for (int j = i; j < n; j++) {               
    10.                 // Print subarray between current starting and ending points  
    11.                 for (int k = i; k <= j; k++) {  
    12.                     System.out.print(arr.get(k) + ” “);  
    13.                 }  
    14.                 System.out.println();  
    15.             }  
    16.         }  
    17.     }  
    18.     public static void main(String[] args) {  
    19.         ArrayList<Integer> arr = new ArrayList<>();  
    20.         arr.add(1);  
    21.         arr.add(2);  
    22.         arr.add(3);  
    23.         System.out.println(“Subarrays are:”);  
    24.         findSubArray(arr);  
    25.     }  
    26. }  

    Compile and Run

    Output:

    Subarrays are:
    1
    1 2
    1 2 3
    2
    2 3
    3
    
  • Jagged Array in Java

    A jagged array in Java is a collection of arrays where each array may contain a varied number of elements. A two-dimensional array, in contrast, requires all rows and columns to have the same length.

    Jagged arrays are also known as “ragged arrays” or “irregular arrays”. They can be created by specifying the size of each array in the declaration. For example, a jagged array with three rows can have the first row with three elements, the second with two elements, and the third with four elements.

    Example of Jagged Array

    A jagged array with three rows can have the first row with three elements, the second with two elements, and the third with four elements.

    1. int[][] jaggedArray = {  
    2.     {1, 2, 3},  
    3.     {4, 5},  
    4.     {6, 7, 8, 9}  
    5. };  

    Declaration and Initialization of Jagged Array

    In Java, a jagged array can be declared and initialized using the following syntax:

    Syntax:

    1. datatype[][] arrayName = new datatype[numRows][];  
    2. arrayName[0] = new datatype[numColumns1];  
    3. arrayName[1] = new datatype[numColumns2];  
    4. …  
    5. arrayName[numRows-1] = new datatype[numColumnsN];  

    Here, the datatype is the data type of the elements in the array, numRows is the number of rows in the jagged array, and numColumns1, numColumns2, …, numColumnsN are the number of columns in each row. Users should be aware that the number of columns in each row is flexible.

    The first line creates an array of arrays with numRows rows. Each row is initialized to null by default.

    The subsequent lines initialize each row of the jagged array. You create a new one-dimensional array of numColumns elements for each row and assign it to the corresponding row in the jagged array.

    Ways to Initialize a Jagged Array

    In addition to the standard approach of declaring and initializing a jagged array, as shown in the previous answer, several alternative ways exist to initialize a jagged array in Java.

    1. Using Array Literals

    We can use array literals to initialize the jagged array elements like this directly:

    1. int[][] jaggedArray = { {1, 2}, {3, 4, 5}, {6, 7, 8, 9} };  

    Here, we create a jagged array with three rows, where the first row has two elements, the second row has three elements, and the third row has four elements.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         // create a jagged array with three rows    
    4.         int[][] jaggedArray = {    
    5.             {1, 2, 3},   // first row has three columns    
    6.             {4, 5},      // second row has two columns    
    7.             {6, 7, 8, 9}   };  // third row has four columns    
    8.         // loop through each row of the jagged array    
    9.         for (int i = 0; i < jaggedArray.length; i++) {    
    10.             // loop through each column of the current row    
    11.             for (int j = 0; j < jaggedArray[i].length; j++) {    
    12.                 // print the value at the current position in the array    
    13.                 System.out.print(jaggedArray[i][j] + ” “);    
    14.             }    
    15.             // move to the next line for the next row    
    16.             System.out.println();    
    17.         }    
    18.     }    
    19. }    

    Compile and Run

    Output:

    1 2 3
    4 5
    6 7 8 9
    

    2. Using Nested Loops

    We can also use nested loops to initialize the jagged array elements when the elements are to be programmatically generated. Utilizing such an approach can be beneficial.

    1. int[][] jaggedArray = new int[3][];  
    2. for (int i = 0; i < jaggedArray.length; i++) {  
    3.     jaggedArray[i] = new int[i + 1];  
    4.     for (int j = 0; j < jaggedArray[i].length; j++) {  
    5.         jaggedArray[i][j] = i + j;  
    6.     }  
    7. }  

    Here, we design a jagged array with three rows, the first of which contains one element, the second two, and the third three. Using a simple formula, the nested loops generate the elements in the jagged array.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         // Create a 2-D jagged array with 4 rows    
    4.         int[][] jaggedArray = new int[4][];    
    5.         // Set the number of columns for each row    
    6.         jaggedArray[0] = new int[1];    
    7.         jaggedArray[1] = new int[2];    
    8.         jaggedArray[2] = new int[3];    
    9.         jaggedArray[3] = new int[4];    
    10.         // Fill the array with values starting from 1    
    11.         int value = 1;    
    12.         for (int i = 0; i < jaggedArray.length; i++) {    
    13.             for (int j = 0; j < jaggedArray[i].length; j++) {    
    14.                 jaggedArray[i][j] = value;    
    15.                 value++;    
    16.             }    
    17.         }    
    18.         // Print the values in the array    
    19.         for (int i = 0; i < jaggedArray.length; i++) {    
    20.             for (int j = 0; j < jaggedArray[i].length; j++) {    
    21.                 System.out.print(jaggedArray[i][j] + ” “);    
    22.             }    
    23.             System.out.println();    
    24.         }    
    25.     }    
    26. }    

    Compile and Run

    Output:

    1
    2 3
    4 5 6
    7 8 9 10
    

    3. Using Java 8 Streams

    With Java 8 streams, you can create and initialize a jagged array in a single line using the Arrays.stream and toArray methods like this:

    1. int[][] jaggedArray = Stream.of(  
    2.         new int[]{1, 2},  
    3.         new int[]{3, 4, 5},  
    4.         new int[]{6, 7, 8, 9})  
    5.         .toArray(int[][]::new);  

    Here, we make a three-row jagged array with two elements in the first row, three in the second row, and four in the third row. The Arrays.stream method converts each one-dimensional array into a stream of integers, and then the toArray method collects the stream into a jagged array.

    Example

    1. import java.util.*;    
    2. public class Main {    
    3.     public static void main(String[] args) {           
    4.         // create a jagged array with three rows    
    5.         int[][] jaggedArray = {    
    6.             {1, 2, 3},   // first row has three columns    
    7.             {4, 5},      // second row has two columns    
    8.             {6, 7, 8, 9} // third row has four columns    
    9.         };    
    10.         // loop through each row of the jagged array using streams    
    11.         Arrays.stream(jaggedArray)    
    12.             .forEach(row -> {    
    13.                 // loop through each element of the current row using streams    
    14.                 Arrays.stream(row)    
    15.                     .forEach(element -> System.out.print(element + ” “));    
    16.                 // move to the next line for the next row    
    17.                 System.out.println();    
    18.             });    
    19.     }    
    20. }    

    Compile and Run

    Output:

    1 2 3
    4 5
    6 7 8 9
    

    4. Dynamic Jagged Array

    In Java, we can create a dynamic jagged array by creating an array of arrays, where each sub-array represents a row in the two-dimensional array. Then, we can allocate memory to each sub-array to specify its number of columns.

    Example

    1. import java.util.Scanner;    
    2. public class Main {    
    3. public static void main(String[] args) {    
    4. // Create a Scanner object to get user input    
    5. Scanner scanner = new Scanner(System.in);    
    6.     // Prompt the user to enter the number of sub-arrays    
    7.     System.out.print(“Enter the number of sub-arrays: “);    
    8.     int numberOfArrays = scanner.nextInt();    
    9.     // Declare the jagged array with the number of sub-arrays    
    10.     int[][] jaggedArray = new int[numberOfArrays][];    
    11.     //Loop through each sub-array to allocate memory and get user input for each element    
    12.     for (int i = 0; i < numberOfArrays; i++) {    
    13.         // Prompt the user to enter the size of the current sub-array    
    14.         System.out.print(“Enter the size of sub-array ” + (i + 1) + “: “);    
    15.         int sizeOfSubArray = scanner.nextInt();    
    16.         // Allocate memory to the current sub-array    
    17.         jaggedArray[i] = new int[sizeOfSubArray];    
    18.         //Loop through each element of the current sub-array to get user input    
    19.         for (int j = 0; j < sizeOfSubArray; j++) {    
    20.             System.out.print(“Enter the element at index ” + j + ” of sub-array ” + (i + 1) + “: “);    
    21.             jaggedArray[i][j] = scanner.nextInt();    
    22.         }    
    23.     }    
    24.     // Print the jagged array    
    25.     System.out.println(“The jagged array is:”);    
    26.     for (int i = 0; i < numberOfArrays; i++) {    
    27.         for (int j = 0; j < jaggedArray[i].length; j++) {    
    28.             System.out.print(jaggedArray[i][j] + ” “);    
    29.         }    
    30.         System.out.println();    
    31.     }    
    32.     // Close the scanner object    
    33.     scanner.close();    
    34. }    
    35. }    

    Compile and Run

    Output:

    Enter the number of sub-arrays: 3
    Enter the size of sub-array 1: 2
    Enter the element at index 0 of sub-array 1: 1
    Enter the element at index 1 of sub-array 1: 2
    Enter the size of sub-array 2: 3
    Enter the element at index 0 of sub-array 2: 3
    Enter the element at index 1 of sub-array 2: 4
    Enter the element at index 2 of sub-array 2: 5
    Enter the size of sub-array 3: 1
    Enter the element at index 0 of sub-array 3: 6
    The jagged array is:
    1 2
    3 4 5
    6
    

    Advantages of Jagged Array

    Jagged arrays have several advantages over multidimensional arrays with a fixed size:

    1. Memory Efficiency: Jagged arrays are more memory-efficient than multidimensional arrays because they only allocate memory for the elements they need. In a multidimensional array with a fixed size, all the memory is allocated, even if some elements are unused.
    2. Flexibility: Jagged arrays are more flexible than multidimensional arrays because they can have different sizes for each row. Jagged arrays enable the representation of non-rectangular or irregular data structures.
    3. Easy to Initialize: Jagged arrays are easy to initialize because you can specify the size of each row individually. The suitability of jagged arrays lies in their ability to store data that varies in size or is generated dynamically.
    4. Enhanced Performance: Jagged arrays can provide enhanced performance in certain scenarios, such as when you need to perform operations on each row independently or when you need to add or remove rows dynamically.
    5. More natural representation of data: In some cases, jagged arrays may be a more natural representation of data than rectangular arrays. For example, when working with irregularly shaped data such as geographic maps, a jagged array can be a more intuitive way to represent the data.
    6. Easier to manipulate: Jagged arrays can be easier to manipulate than rectangular arrays because they allow for more direct access to individual elements. With rectangular arrays, you may need to use more complex indexing or slicing operations to access subsets of the data.

    How do jagged arrays differ from multi-dimensional arrays?

    A jagged array is not the same as a multi-dimensional array. There are some differences between Jagged array and multi-dimensional array that are described in the following table.

    AspectJagged ArrayMulti-dimensional Array
    StructureEach row (or sub-array) can have a different length.All rows must have the same number of columns.
    Memory AllocationMemory is allocated separately for each sub-array, making it more memory-efficient when varying row sizes are needed.It allocates a continuous block of memory for all elements, potentially wasting memory when row lengths vary.
    Declarationint[][] jaggedArray = {
        {1, 2, 3},
        {4, 5},
        {6, 7, 8, 9}
    };
    int[][] multiArray = new int[3][3]; // Fixed size: 3 rows, 3 columns
    Accessing ElementsJagged Array: jaggedArray[row][column]Multi-dimensional Array: multiArray[row][column]
    Uses CasesIt is useful when dealing with irregular data structures like variable-length rows in tables.It is ideal for grids, matrices, or fixed-size tables.
  • Java Array length Property

    In Java, the array length is the number of elements that an array can hold. There is no predefined method to obtain the length of an array. We can find the array length in Java by using the array attribute length. We use this attribute with the array name.

    Array length Attribute

    Java provides an attribute length that determines the length of an array. Every array has an in-built length property whose value is the size of the array. Size implies the total number of elements that an array can contain. The length property can be invoked by using the dot (.) operator followed by the array name. We can find the length of int[], double[], String[], etc. For example:

    1. int[] arr=new int[5];  
    2. int arrayLength=arr.length  

    In the above code snippet, arr is an array of type int that can hold 5 elements. The arrayLength is a variable that stores the length of an array. To find the length of the array, we have used the array name (arr) followed by the dot operator and length attribute, respectively. It determines the size of the array.

    How to Find Array Length in Java

    Note that length determines the maximum number of elements that the array can contain or the capacity of the array. It does not count the elements that are inserted into the array. That is, length returns the total size of the array. For arrays whose elements are initialized at the time of its creation, length and size are the same.

    If we talk about the logical size, the index of the array, then simply int arrayLength=arr.length-1, because the array index starts from 0. So, the logical or array index will always be less than the actual size by 1.

    How to Find Array Length in Java

    Let’s find the length of the array through an example.

    Example

    1. public class Main  {     
    2. public static void main(String[] args)   {     
    3. //defining an array of type int named num    
    4. //The square bracket contains the length of an array    
    5. int[] num = new int[10];     
    6. //length is an Array attribute that determines the array length     
    7. int arrayLength=num.length;    
    8. //prints array length    
    9. System.out.println(“The length of the array is: “+ arrayLength);     
    10. }     
    11. }    

    Compile and Run

    Output:

    The length of the array is: 10

    Explanation

    This Java code, which is part of the ArrayLengthExample1 class, shows how to find an array’s length. The syntax int[] num = new int[10]; is used in the main method to declare and initialise an array of type int with a length of 10. When an array is declared, its length is specified by the square brackets. The code then determines the length of the num array by using the length attribute, which is built into all Java arrays, and assigning the result to the variable arrayLength. Finally, the program prints out the length of the array using System.out.println, providing information about the number of elements the array can hold.

    Example

    1. public class Main   {     
    2. public static void main(String[] args)   {     
    3. //Initialising an array of type String named country     
    4. String[] country = { “India”, “Australia”, “Japan”, “USA”, “UAE”, “Canada”, “Brazil”};    
    5. //length is an Array attribute that determines the array length     
    6. int arrayLength=country.length;     
    7. //prints array length    
    8. System.out.println(“The size of the array is: ” + arrayLength);     
    9. }     
    10. }    

    Compile and Run

    Output:

    The size of the array is: 7

    Explanation

    With a main method, the class ArrayLengthExample2 is defined in the Java code that is provided. Several country names are initialised into an array of type String called country inside the main procedure. Next, the code calculates the length of the nation array, or the total number of entries it may contain, using Java’s length attribute for arrays. The variable arrayLength is given the length. The array’s size and the number of elements it contains are finally printed by the programme using System.out.println. This code basically shows how to use Java’s length attribute to find the length of an array and how to output the length for reference.

    Example

    1. public class Main   {    
    2. private static void LengthOfArray(String[] array)   {    
    3. //checks array is empty or not        
    4. if (array == null)   {    
    5. //if the array is empty, prints the following statement    
    6. System.out.println(“The array is empty, can’t be determined the length.”);    
    7. }     
    8. else   {    
    9. //The length attribute of the Array class determines the length of an array    
    10. int arrayLength = array.length;    
    11. //prints the array length    
    12. System.out.println(“The length of the array is: “+arrayLength);    
    13. }    
    14. }    
    15. public static void main(String[] args)   {    
    16. String[] fruits = { “Guava”, “Banana”, “Apple”, “Papaya”, “Melon”, “Strawberry”};    
    17. String[] alphabets = { “m”, “p”, “k”, “l”, “t” };    
    18. String[] numbers = { “12”, “25”, “63”, “84”, “90”, “11”, “54”};    
    19. //passing a null value to the function    
    20. LengthOfArray(null);    
    21. //passing the fruits array to the function    
    22. LengthOfArray(fruits);    
    23. //passing the alphabet array to the function    
    24. LengthOfArray(alphabets);    
    25. //passing the numbers array to the function    
    26. LengthOfArray(numbers);    
    27. }    
    28. }    

    Compile and Run

    Output:

    The array is empty, can't be determined the length.
    The length of the array is: 6
    The length of the array is: 5
    The length of the array is: 7
    

    Explanation

    The Java code that is provided defines a class called Main, and in that class, there is a method called LengthOfArray that is used to find and report the length of a specified array of strings. The procedure initially determines if the supplied array is null or empty by looking at its value. It prints a message saying that the length cannot be computed if the array is empty. If not, it uses the Array class’s length attribute to determine the array’s length and displays it. LengthOfArray’s usefulness is demonstrated in the main method by passing several arrays, such as a null value, an array of fruits, alphabets, and numerals. The length of each array is output by the programme when it runs.

    Iterating through the Array

    Another method involves iterating through the array and counting the number of elements encountered. This approach provides more flexibility and control over the counting process.

    Example

    1. public class Main {    
    2.     public static void main(String[] args) {    
    3.         int[] arr = new int[5];    
    4.         int count = 0;    
    5.         for (int element : arr) {    
    6.             count++;    
    7.         }    
    8.         int arrayLength = count;    
    9.         System.out.println(“The length of the array is: ” + arrayLength);    
    10.     }    
    11. }    

    Compile and Run

    Output:

    The length of the array is: 5
  • Multi-Dimensional Arrays in Java

    Multi-dimensional arrays in Java are basically arrays of arrays. It allows us to store data in a tabular or grid-like structure, making them useful for scenarios like matrices, game boards, or any data that requires multiple dimensions. It is useful when we want to store data in tabular form (rows and columns).

    It can be a two-dimensional (2D) or three-dimensional (3D) array.

    Two-Dimensional (2D) Array

    It is the simplest multi-dimensional array having rows and columns.

    Declaration

    1. DataType[][] arrayName;    

    or

    1. DataType arrayName[][];   

    or

    1. arrayName = new DataType[rows][columns];   

    We can declare and initialize a two-dimensional array in a single statement as follows.

    1. datatype[][] arrayName = new datatype[rows][columns];   

    Assigning Values

    1. arrayName[rows][columns] = {values};   

    Examples

    1. // 2D Array with two rows and two columns Intialised and Assigned  
    2. int[][] arr = { { 1, 2 }, { 3, 4 } };  
    3. //array with three rows and three columns  
    4.  int[][] arr = new int[3][3];  

    Representation of 2D Array

    Multi-Dimensional Arrays in Java

    Note that Java uses zero-based indexing. It means the indexing of arrays in Java starts with 0.

    Also, note that in a multi-dimensional array, each row can be of different sizes. It means that each row may not have the same number of elements.

    Two-Dimensional (2D) Array Java Program

    Example

    1. public class Main {      
    2.     public static void main(String args[]) {      
    3.         int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3×3 matrix      
    4.         // Printing the 2D array      
    5.         for (int i = 0; i < 3; i++)   //loop for rows  
    6. {      
    7.             for (int j = 0; j < 3; j++)  //loop for columns  
    8.    {      
    9.                 System.out.print(arr[i][j] + ” “);    //prints element with space  
    10.             }      
    11.             System.out.println();    //throws cursor to the next line  
    12.         }      
    13.     }      
    14. }      

    Compile and Run

    Output:

    1 2 3
    4 5 6
    7 8 9
    

    Explanation

    In the above program, we have declared and initialized a 3×3 matrix. The first for loop iterates over the rows, and the second for loop iterates over the columns. The first print statement prints the elements of the array with space, and the second print statement throws the cursor to the next line.

    Two-Dimensional (2D) Array with User Input

    Example

    1. import java.util.Scanner;  
    2. public class Main {  
    3.     public static void main(String[] args) {  
    4.         Scanner scanner = new Scanner(System.in);  
    5.         // Define the dimensions of the array  
    6.         System.out.print(“Enter the number of rows:”);  
    7.         int rows = scanner.nextInt();  //reading number of rows from the user  
    8.         System.out.print(“Enter the number of columns:”);  
    9.         int columns = scanner.nextInt();  //reading number of columns from the user  
    10.         // Initialize the 2D array  
    11.         int[][] array = new int[rows][columns];  
    12.         //reading array elements from the user  
    13.         System.out.println(“Enter the elements of the array:”);  
    14.         for (int i = 0; i < rows; i++)    //loop for rows  
    15.         {  
    16.             for (int j = 0; j < columns; j++)   //loop for columns  
    17.             {  
    18.                 System.out.print(“Enter element for position (” + i + “, ” + j + “): “);  
    19.                 //reading array elements one by one  
    20.                 array[i][j] = scanner.nextInt();  
    21.             }  
    22.         }  
    23.         // Printing the 2D array  
    24.         System.out.println(“The entered 2D array is:”);  
    25.         for (int i = 0; i < rows; i++) {  
    26.             for (int j = 0; j < columns; j++) {  
    27.                 System.out.print(array[i][j] + ” “);  
    28.             }  
    29.             System.out.println();  
    30.         }  
    31.         scanner.close();  
    32.     }  
    33. }  

    Output:

    Enter the number of rows:3
    Enter the number of columns:3
    Enter the elements of the array:
    Enter element for position (0, 0): 1
    Enter element for position (0, 1): 2
    Enter element for position (0, 2): 3
    Enter element for position (1, 0): 4
    Enter element for position (1, 1): 5
    Enter element for position (1, 2): 6
    Enter element for position (2, 0): 7
    Enter element for position (2, 1): 8
    Enter element for position (2, 2): 9
    The entered 2D array is:
    1 2 3
    4 5 6
    7 8 9
    

    Three-Dimensional (3D) Array

    It is a complex form of a 2D array. In other words, it is an array of a two-dimensional array.

    Declaration

    1. DataType[][][] arrayName;        

    or

    1. DataType arrayName[][][];   

    or

    1. arrayName = new DataType[][][];   

    We can declare and initialize a three-dimensional array in a single statement as follows.

    1. datatype[][][] arrayName = new datatype[][][];   

    Assigning Values

    1. arrayName[][][] = {values};  

    Examples

    public class Main {  
    
        public static void main(String[] args)   
    
        {  
    
            //declaring and initializing three-dimensional array  
    
            int[][][] threeDArray = {  
    
                {  
    
                    {1, 2, 3},  
    
                    {4, 5, 6}  
    
                },  
    
                {  
    
                    {7, 8, 9},  
    
                    {10, 11, 12}  
    
                }  
    
            };  
    
            //Print the elements of the 3D array  
    
            System.out.println("Elements of the 3D Array:");  
    
            for (int i = 0; i < threeDArray.length; i++) {  
    
                for (int j = 0; j < threeDArray[i].length; j++) {  
    
                    for (int k = 0; k < threeDArray[i][j].length; k++) {  
    
                        System.out.print(threeDArray[i][j][k] + " ");  
    
                    }  
    
                    System.out.println(); // Move to the next line for better readability  
    
                }  
    
                System.out.println(); // Add a blank line between blocks  
    
            }  
    
        }  
    
    }

    1. // 3D Array with two rows ad two columns Intialised and Assigned  
    2. int[][][] values = {{{1, 2, 3}, {4, 5, 6}}, {{-2, -8, 3, 7}, {5}, {12, 11}}};  
    3. //array contains three array of three rows and three columns   
    4.  int[][][] arr = new int[3][3][3];  

    Representation of 3D Array

    Multi-Dimensional Arrays in Java

    Three-Dimensional (3D) Array Java Program

    Example

    Compile and Run

    Output:

    Elements of the 3D Array:
    1 2 3
    4 5 6
    
    7 8 9
    10 11 12
    

    Size of Multidimensional Arrays

    We can calculate the size of the array by multiplying the size of all the dimensions. It gives the number of elements that can be stored in an array. For example, int[][][] num = new int[5][5][5]; can store total 125 elements.

    Why Use Multidimensional Arrays?

    Multidimensional arrays are useful in many real-world scenarios, such as:

    1. Mathematical computations: Representing matrices for algebraic calculations.
    2. Game development: Storing board layouts, game grids, or levels.
    3. Image processing: Representing pixels in a digital image.
    4. Data analysis: Managing structured data like spreadsheets or databases.

    Conclusion

    Multidimensional arrays in Java serve as an effective solution for managing organized data structures while processing them. Multidimensional arrays surpass the functionality of single-dimensional arrays because they enable table organization, which results in applications ranging from scientific computing to game development.

    Two-dimensional arrays function as the preferred form for applications that need matrix computations together with pathfinding implementations and data presentation. The option to produce jagged arrays makes the process more adaptable for developers since they can handle irregular data formats.

  • setInterval() Method

    JavaScript setInterval() Method

    In JavaScript, the setInterval() is a window method that is used to execute a function repeatedly at a specific interval. The setTimeout() Method allows you to execute the function only once after the specified time.

    The window object contains the setInterval() method. However, you can execute the setInterval() Method without taking the window object as a reference.

    Syntax

    Following is the syntax to use the setInterval() method in JavaScript

    setInterval(callback,interval, arg1, arg2,..., argN);

    The first two parameters are required others are optional.

    Parameters

    • Callback − It is a callback function that will be executed after every interval.
    • Interval − It is the number of milliseconds after the callback function should be executed.
    • Arg1, arg2, arg3, , argN − They are multiple arguments to pass to the callback function.

    Return Value

    The setInterval() method returns the numeric id.

    Example

    In the code below, the startTimer() function uses the setInterval() method to call the timer() function after every 1000 milliseconds.

    The timer() function increases the value of the second global variable every time it is called by the setInterval() method and prints the counter.

    You can click the button to start a timer in the output.

    Open Compiler

    <html><body><button onclick ="startTimer()">Start Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){setInterval(timer,1000);// Calls timer() function after every second}functiontimer(){// Callback function
    
         seconds++;
         output.innerHTML +="Total seconds are: "+ seconds +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    JavaScript setInterval() Method

    Arrow Function with setInterval() Method

    The below example contains almost the same code as the above example. Here, we have passed the arrow function as a first argument of the setInterval() method rather than passing the function name only. You can click the button to start the timer.

    Example

    Open Compiler

    <html><body><button onclick ="startTimer()">Start Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){setInterval(()=>{
    
            seconds++;
            output.innerHTML +="Total seconds are: "+ seconds +"&lt;br&gt;";},1000);// Calls timer() function after every second}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Arrow Function with setInterval() Method

    Passing More than 2 Arguments to setInterval() Method

    In the code below, we have passed 3 arguments to the setInterval() method. The first argument is a callback function to print the date, the second argument is an interval, and the third argument will be passed to the callback function.

    Example

    Open Compiler

    <html><body><button onclick ="startTimer()">Start Date Timer</button><div id ="output"></div><script>let output = document.getElementById('output');var seconds =0;functionstartTimer(){let message ="The date and time is: ";setInterval(printDate,1000, message);}functionprintDate(message){let date =newDate();
    
         output.innerHTML += message + date +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Passing More than 2 Arguments to setInterval() Method

    The clearInterval() Method in JavaScript

    The JavaScript clearInterval() method is used to stop the code execution started using the clearItnerval() method.

    It takes the numeric id returned by the setInterval () method as an argument.

    Syntax

    Follow the syntax below to use the clearInterval() method.

    clearInterval(id);

    Here id is an id returned by the setInterval() method.

    Example

    In the code below, we have used the setInterval() method to show the number after incrementing by 10 and after each second.

    When the number becomes 50, we stop the timer using the clearInterval() method.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');let number =10;let id =setInterval(()=>{if(number ==50){clearInterval(id);
    
            output.innerHTML +="The time is stopped."}
         output.innerHTML +="The number is: "+ number +"&lt;br&gt;";
         number +=10;},1000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    The number is: 10
    The number is: 20
    The number is: 30
    The number is: 40
    The time is stopped.The number is: 50
    

    Real-time Use Case of the setInterval() Method

    In the above examples, we have printed the messages using the setInterval() method. In this section, we will see the real-time use cases of the setInterval() method.

    Here, we have listed some of the real-time use cases.

    • To refresh the date
    • For slideshow
    • For animation
    • To show the clock on the webpage
    • To update live cricket score
    • To update weather information
    • To run cron jobs

    Here are the real-time examples of the setInterval() method.

    Flipping the color of the HTML element after each interval

    In the code below, we flip the color of the <div> element after every second.

    We have defined the div element in the HTML body.

    In the <head> section, we have added the red and green classes. Also, we added the background color in the red and green classes.

    In JavaScript, we have passed the callback function as the first argument of the setInterval() method, which will be called after every 1000 milliseconds.

    We access the <div> element in the callback function using its id. After that, we check whether the classList of the <div> element contains the red class. If yes, we remove it and add the green class. Similarly, if classList contains the green class, we remove it and add the red class.

    This is how we are flipping the color of the <div> element using the setInterval() method.

    Example

    Open Compiler

    <html><head><style>.red {background-color: red;}.green {background-color: green;}
    
      #square {height:200px; width:200px;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;Using setInterval() method to flip the color of the HTML element after each interval&lt;/div&gt;&lt;div id ="square"class="red"&gt;&lt;/div&gt;&lt;script&gt;let output = document.getElementById('output');setInterval(function(){let square = document.getElementById('square');if(square.classList.contains('red')){
            square.classList.remove('red');
            square.classList.add('green');}else{
            square.classList.remove('green');
            square.classList.add('red');}},1000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Flipping color of HTML element after each interval

    Moving Animation Using the setInterval() Method

    In the code below, we create moving animation using the setInterval() method.

    We have created the two nested div elements. The outer div has the parent id, and the inner div has the child id. We have set dimensions for both div elements and position to relative.

    In JavaScript, we have initialized the left variable with 0. After that, we invoke the callback function of the setInterval() method after every 50 milliseconds.

    In each interval, we change the position of the <div> element by 5px, and when the left position becomes 450px, we stop the animation.

    Example

    Open Compiler

    <html><head><style>
    
      #parent {
         position: relative; 
         height:50px;
         width:500px;
         background-color: yellow;}
      #child {
         position: relative; 
         height:50px;
         width:50px;
         background-color: red;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="parent"&gt;&lt;div id ="child"&gt;&lt;/div&gt;&lt;/div&gt;&lt;script&gt;let child = document.getElementById('child');let left =0;// Moving animation using the setInterval() methodsetInterval(()=&gt;{if(left &lt;450){
            left +=5;
            child.style.left = left +'px';}},50);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Moving Animation Using setInterval() Method

    You can also use the setInterval() method to run the particular code asynchronously.

  • setTimeout() Method

    JavaScript setTimeout() Method

    In JavaScript, the setTimeout() is a global method that allows you to execute the function or a particular JavaScript code only once after a specified time.

    The window object contains the setTimeout() method. You may use the window object to execute the setTimeout() method.

    The setTimeout() method can also be used to manipulate the DOM elements after the specified time of the user interaction.

    Syntax

    The syntax of the setTimeout() method in JavaScript is as follows −

    window.setTimeout(callback, delay, param1, param2,..., paramN);ORsetTimeout(callback, delay, param1, param2,..., paramN);

    The setTimeout() method takes at least 2 parameters.

    Parameters

    • Callback − It is a callback function that will be called after a specific time. You can pass the arrow function, function expression, or regular expression as a value of this parameter.
    • delay − It is the number of milliseconds after that the callback function should be called. Here, 1 second is equal to 1000 milliseconds.
    • param1, param2, …, paramN − They are optional parameters to be passed as a callback function parameter.

    Return Value

    It returns the numeric id, which you can use to clear timeout.

    Example

    In the below code, we have defined the timeout() function, printing the message in the web page.

    We passed the timeout() function as the first argument of the setTimeout() method, and 1000 milliseconds as a second argument.

    The setTimeout() method will invoke the timeout() function after 1 second or 1000 milliseconds.

    Open Compiler

    <html><body><div id ="output"></div><script>
    
      document.getElementById('output').innerHTML ="Wait for a message! &lt;br&gt;";setTimeout(timeout,1000);functiontimeout(){
         document.getElementById('output').innerHTML +="This message is printed after 1 second!";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Wait for a message!
    This message is printed after 1 second!
    

    Arrow Function with setTimeout() Method

    In the below code, we have passed the arrow function as the first argument of the setTimeout() method. It works the same as passing the function name as an argument and defining the function outside.

    It prints the message after 2000 milliseconds.

    Example

    Open Compiler

    <html><body><div id ="output"></div><script>
    
      document.getElementById('output').innerHTML +="You will see the message after 2000 milliseconds! &lt;br&gt;";setTimeout(()=&gt;{
         document.getElementById('output').innerHTML +='Hi! How are you?';},2000);&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    You will see the message after 2000 milliseconds!
    Hi! How are you?
    

    Passing More than 2 Arguments to setTimeout() Method

    You can pass more than 2 arguments to the setTimeout() method. The first argument is a callback function, the second argument is a delay in the milliseconds, and other arguments to pass to the function parameter.

    In the code below, we have passed 5 arguments to the setTimeout() method. In the sum() function, we received the last 3 arguments of the seetTimeOut() method as a parameter and summed them.

    Example

    Open Compiler

    <html><body><div>Wait for a sum of3 number.!</div><div id ="output"></div><script>setTimeout(sum,1000,10,20,30);functionsum(num1, num2, num3){let result = num1 + num2 + num3;
    
         document.getElementById('output').innerHTML ="Sum = "+ result;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Wait for a sum of 3 number.!
    Sum = 60
    

    Execute Code After Every N Seconds

    We created the counter using the setTimeout() method in the code below.

    We have defined the global variable p for the counter. In the counter() function, we print the counter value and use the setTimeout() method to call the counter function again after 1000 milliseconds.

    Example

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');
    
      output.innerHTML +="The output of the counter is given below. &lt;br&gt;";var p =0;functioncounter(){
         output.innerHTML +="count is - "+ p +".&lt;br&gt;";setTimeout(counter,1000);
         p++;}counter();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    The output of the counter is given below.
    count is - 0.
    count is - 1.
    count is - 2.
    count is - 3.
    count is - 4.
    count is - 5.
    count is - 6.
    

    JavaScript clearTimeout() Method

    Sometimes, developers are required to cancel the time out before it executes the function or the JavaScript code. In such cases, you can use the clearTimeout() method.

    Syntax

    You can follow the syntax below to use the clearTimeout() method.

    clearTimeout(id);

    Parameters

    id − It is an id returned by the setTimeout() method to cancel it.

    Example

    In the below code, we have defined the startTimeOut() and stopTimeOut() functions, which will be called when users press the respective buttons.

    In the startTimeOut() function, we set the timeout of the 3 seconds and store the id returned by the setTimeout() method into the timeOut variable.

    In the stopTimeOut() function, we use the clearTimeout() method and pass the timeOut as an argument to clear the timeout.

    Open Compiler

    <html><body><p>Click the Stop timeout button within 3 seconds after pressing the Start timeout button.</p><button onclick ="startTimeOut()">Start Timeout</button><button onclick ="stopTimeOut()">Stop Timeout</button><p id ="output"></p><script>let output = document.getElementById('output');let timeout;functionstartTimeOut(){
    
         timeout =setTimeout(()=&gt;{
            output.innerHTML ="Timeout is done";},3000);}functionstopTimeOut(){clearTimeout(timeout);
         output.innerHTML ="Timeout is stopped";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    JavaScript clearTimeout() Method

    Zero Delay SetTimeout

    The zero delay timeout means you call the setTimeout() method by passing the 0 milliseconds as an argument.

    As you pass the 0 milliseconds as an argument, it may or may not call the JavaScript code written into the callback function after 0 milliseconds. It totally depends on the pending tasks in the queue. Once the queue of tasks is completed, it will execute the code of the callback function.

    Now, the question is, what is the need of the zero delay timeout?

    Sometimes, you need to execute the particular JavaScript code as soon as possible once the script gets loaded into the browser. In such cases, you can use the setTimeout() method by passing 0 milliseconds as a second argument.

    Syntax

    Follow the syntax below to use the zero-delay timeout.

    setTimeout(callback,0);

    In the above syntax, we have passed the callback function as the first parameter and 0 milliseconds as the second parameter.

    Example

    In the code below, we add a start message, zero delay timeout message, and end message to the web page.

    In the output, you can see that it prints the start message. After that, it prints the end message and the zero delay timeout message. So, it executes the zero delay timeout code when the whole script gets loaded in the browser.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById('output');
    
      output.innerHTML +="The code execution started. &lt;br&gt;";setTimeout(function(){
         output.innerHTML +="Inside the zero delay timeout. &lt;br&gt;";},0);
      output.innerHTML +="The code execution ended. &lt;br&gt;";&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    The code execution started.
    The code execution ended.
    Inside the zero delay timeout.
    

    You can also recursively use the setTimeout() method, as shown in the example of the counter. Furthermore, you can also pass the anonymous function expression as a first parameter, like the arrow function. If you want to execute the particular JavaScript code, you can use the zero delay timeout once the whole script gets executed.

  • Timing Events

    What are the Timing Events?

    JavaScript timing events are used to execute the code after a specified time only once or multiple times. In JavaScript, you can use the timing events to control when a particular task should be executed.

    The ‘window’ object contains the various methods for timing events, which you can use to schedule the tasks. You can call these methods using the window object or without using it.

    Here is the list of methods that can be used to schedule the tasks.

    MethodDescription
    setTimeout()To execute the code after N number of milliseconds only once.
    clearTimeout()To clear the timeout, which was set using the setTimeOut() method.
    setInterval()To execute the particular task after each N milliseconds.
    clearInterval()To clear the interval, which was set using the setInterval() method.

    Let’s understand the timing events via the example below.

    The setTimeout() Method

    <html>
    <body>
       <div id = "output">The message will be printed after 2000 milliseconds! <br></div>
       <script>
    
      setTimeout(() =&gt; {
         document.getElementById('output').innerHTML += 'Hello World &lt;br&gt;';
      }, 2000);
    </script> </body> </html>

    Output

    The message will be printed after 2000 milliseconds!
    Hello World
    

    The clearTimeout() Method

    In the below example, we used the setTimeout() method to print the ‘hello world’ after 3000 milliseconds. We used clearTimeout() method to prevent setTimeout() method to execute.

    Example

    <html>
    <body>
       <p>Message will print after 3 seconds.</p>
       <p>Click the button to prevent timeout to execute.</p>
       <p id="demo"></p>
       <button onclick="stop()">Clear Timeout</button>
       <script>
    
      const myTimeout = setTimeout(greet, 3000);
      function greet() {
         document.getElementById("demo").innerHTML = "Hello World!"
      }
      function stop() {
         clearTimeout(myTimeout);
      }
    </script> </body> </html>

    Output

    The clearTimeout() Method

    The setInterval() and clearInterval() Methods

    In the code below, we have used the setInterval() method to show the number after incrementing by 10 and after each second.

    When the number becomes 50, we stop the timer using the clearInterval() method.

    Example

    <html>
    <body>
       <div id = "output"> </div>
       <script>
    
      let output = document.getElementById('output');
      let number = 10;
      let id = setInterval(() =&gt; {
         if (number == 50) {
            clearInterval(id);
            output.innerHTML += "The time is stopped."
         }
         output.innerHTML += "The number is: " + number + "&lt;br&gt;";
         number += 10;
      }, 1000);
    </script> </body> </html>

    Output

    The number is: 10
    The number is: 20
    The number is: 30
    The number is: 40
    The time is stopped.The number is: 50
    

    Real-time Use Cases of Timing Events

    Here, you will learn the real-time use cases of the timing events.

    • For animation and transition
    • For slideshow and carousel
    • For countdown timers
    • For user authentication timeouts
    • To autosave drafts like Google docs
    • To schedule notifications, email, message, etc.
    • To terminate the session as like banking websites
    • For progress bar

    However, there are other use cases also. You can use the setTimeOut() or setInterval() methods to achieve the above functionalities.

    Whats Next?

    In the following chapters, you will learn setTimeOut() and setInterval() methods in detail.

  • Promises Chaining

    The promise chaining in JavaScript can handle multiple related asynchronous operations even with a single promise. While a single promise handles a single asynchronous operation, the promise chaining allows you to create a sequence of promises. Here success or rejection of one promise triggers the execution of the next promise. This enables you to handle multiple asynchronous operations.

    In JavaScript, we can produce the promise code using the Promise() constructor and consume using the then() method. It handles the single asynchronous operation. To handle the multiple asynchronous operations, we require to use the multiple promises, as shown in the example below.

    Example

    In the code below, we have defined promise1, which gets resolved in 1 second. Also, we have defined the global data variable.

    After that, we used the then() method to consume the promise1, and inside the callback function, we stored the return value from the promise in the data.

    Next, we have defined the promise2, which gets resolved after 2 seconds. Next, we used the then() method with promise2 and used the data variable inside the callback function.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");var data;// First promiselet promise1 =newPromise((resolve, reject)=>{setTimeout(()=>{resolve(10);},1000);});
    
      promise1.then((value)=&gt;{
         data = value;// Stroing value into the data
         output.innerHTML +="The promise1 is resolved and data is: "+ data +"&lt;br&gt;";});// Second promiselet promise2 =newPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve(20);},2000);});
      promise2.then((value)=&gt;{
         data = data * value;// Using the data from the first promise
         output.innerHTML +="The promise2 is resolved and data is: "+ value +"&lt;br&gt;";
         output.innerHTML +="The final value of the data is: "+ data +"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    The promise1 is resolved and data is: 10
    The promise2 is resolved and data is: 20
    The final value of the data is: 200
    

    In the above example, we have created two different promises to perform multiple operations on the data returned from the promise1.

    It increases the code complexity and decreases the readability.

    Here, promise chaining comes into the picture.

    JavaScript Promise Chaining

    The concept of promise chaining in JavaScript allows you to do multiple related asynchronous operations with a single promise.

    You can use the multiple then() methods while consuming the promise to perform the multiple asynchronous operations.

    Syntax

    The syntax of the promise chaining in JavaScript is as follows −

    Promise
       .then(callback);.then(callback);....then(callback);

    In the above syntax, we have used multiple then() methods to handle the multiple asynchronous operations. Each then() method executes the single callback function.

    Example

    In the code below, we have defined the promise1. After that, we used the promise chain to perform the multiple asynchronous operations.

    From the first then() method, we return the value after multiplying with 2. In the next then() method, we print the updated value and return the new value after multiplying the old value with 2. Similarly, the operation we are doing is in the third then() method.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{resolve(2);});// Promise chaining
    
      promise1
      .then((value)=&gt;{
         output.innerHTML ="The square of 2 is "+ value *2+"&lt;br&gt;";return value *2;// Returning a promise for next then() method}).then((value)=&gt;{
         output.innerHTML +="The square of 4 is "+ value *2+"&lt;br&gt;";return value *2;}).then((value)=&gt;{
         output.innerHTML +="The square of 8 is "+ value *2+"&lt;br&gt;";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    The square of 2 is 4
    The square of 4 is 8
    The square of 8 is 16
    

    Multiple Promise Handlers

    You can also use the multiple promise handlers to consume the single promise. However, if you use multiple promise handlers, it is not called promise chaining.

    Example

    In the code below, we have created the promise1.

    After that, we used the multiple promise handlers to consume the promise. Each promise handler solves the promise separately.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{resolve(2);});
    
    
      promise1
      .then((value)=&gt;{
         output.innerHTML +="Inside the first promise handler. &lt;br&gt;";return value *2;})
      promise1
      .then((value)=&gt;{
         output.innerHTML +="Inside the second promise handler. &lt;br&gt;";return value *2;})
      promise1
      .then((value)=&gt;{
         output.innerHTML +="Inside the third promise handler. &lt;br&gt;";return value *2;})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Inside the first promise handler.
    Inside the second promise handler.
    Inside the third promise handler.
    

    Error Handling with Promise Chaining

    You can use the catch() method with promise chaining to handle the error.

    If you use the catch() method at last after all then() methods, it catches the error in any then() method and handles it. If you use the catch() method in between then() methods, it catches the error in the then() methods used before it.

    Lets understand it via the example below.

    Example

    In the code below, we have defined the promise and rejected it.

    After that, we used the promise chaining to consume the promise. We used two then() methods and 1 catch() after all then() methods.

    In the output, you can see that as we rejected the promise, control goes into the catch() method.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{reject("There is an error.");});
    
    
      promise1
      .then((value)=&gt;{
         output.innerHTML +="The returned value is: "+ value +"&lt;br /&gt;";return value +" Everything is fine!";}).then((value)=&gt;{
         output.innerHTML += value;}).catch((error)=&gt;{
         output.innerHTML += error;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    There is an error.
    

    Returning the Promise

    When you return the value from the then() method, it returns the promise by default and resolves it with a returned value, as it is an asynchronous method.

    However, you can manually return the promise to reject the promise or perform any other operation.

    Example

    In the code below, we have defined the primise1 and used the setTimeOut() method inside the callback function.

    After that, we consume the promise using multiple then() methods. From each then() method, we return a new promise.

    When you return only the value from the then() method, it returns the promise, which gets resolved immediately. But when you want to add some delay, you can return the promise from then() method.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");const promise1 =newPromise((resolve, reject)=>{setTimeout(()=>{resolve("Stage 1");},500);});
    
    
      promise1
      .then((value)=&gt;{
         output.innerHTML += value +"&lt;br /&gt;";returnnewPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve("Stage 2");},1000);});}).then((value)=&gt;{
         output.innerHTML += value +"&lt;br /&gt;";returnnewPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve("Stage 3");},200);});}).then((value)=&gt;{
         output.innerHTML += value +"&lt;br /&gt;";
         output.innerHTML +="Finished";})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Stage 1
    Stage 2
    Stage 3
    Finished
    

    Converting Nested Callback Functions into the Promise Chaining

    You learned about the nested callback functions in the JavaScript-callbacks' chapter. It is also called the callback hell due to its complex syntax.

    Here, we will learn to convert the callback hell into the promise chaining to make it more readable.

    Lets look at the example of the nested callback functions.

    Nested Callback functions

    Example

    In the code below, the updateData() function takes the data as a first parameter and the callback function as a second parameter.

    The updateData() function calls the callback function by passing the data as an argument after 1000 milliseconds.

    Next, we have invoked the updateData() function and passed the 10 as a first argument and the anonymous function as a callback function.

    The callback function stores the resultant value into p after adding 1 to the num1 value.

    Next, we call the updateData() function inside the callback function. Also, we have passed the data and callback function as an argument. This way, we have defined the nested callback functions.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");
    
      output.innerHTML +="Wait for updating the data...&lt;br&gt;";//    Callback hellfunctionupdateData(data, callback){setTimeout(()=&gt;{callback(data);},1000);}updateData(10,function(num1){let p =1+ num1;updateData(30,function(num2){let q =1+ num2;updateData("The numeric value is: "+(p + q),function(answer){
               output.innerText += answer;});});});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Wait for updating the data...
    The numeric value is: 42
    

    Now, lets learn to convert the above example into promise chaining.

    Converting nested callback functions to promise chaining

    Example

    In the code below, the updateData() function returns a single promise.

    After that, we used the promise chaining, an alternative to the callback hell defined in the above example.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");
    
      output.innerHTML +="Wait for updating the data...&lt;br&gt;";functionupdateData(data){returnnewPromise((resolve, reject)=&gt;{setTimeout(()=&gt;{resolve(data);},1000);});}updateData(10).then((num1)=&gt;{let p =1+ num1;returnupdateData(p);}).then((num2)=&gt;{let q =31;returnupdateData("The final value is: "+(num2 + q));}).then((res)=&gt;{
         output.innerText += res;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    Wait for updating the data...
    The final value is: 42
    

    Real-time Examples of Promise Chaining

    In real-time development, you can use the promise chaining to fetch the data and perform the operations on the data.

    Example

    In the code below, when users click the fetch data button, it invokes the fetchData() function.

    In the fetchData() function, we have used the fetch() API to fetch data from the API.

    After that, we used the then() method to convert the data into JSON.

    Next, we used the then() method again to print the JSON data.

    Open Compiler

    <html><body><button onclick ="fetchData()"> Fetch Data </button><div id ="output"></div><script>let output = document.getElementById("output");functionfetchData(){fetch('https://jsonplaceholder.typicode.com/todos/1').then(response=> response.json())// Promise chaining.then((data)=>{
    
            output.innerHTML +="The data is - "+JSON.stringify(data);})}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>
  • Promisification

    Promisification in JavaScript

    Promisification in JavaScript is a concept to convert the callback functions into a regular function, returning the promise.

    The reason to convert the callback functions into promises is that when you need to write the nested callback functions, it increases the complexity of the code. So, you can write a function returning the promise.

    In JavaScript, you can pass the function as an argument of another function called the callback function. The callback functions are used to handle the asynchronous task.

    Let’s first write an example of the callback function.

    Callback Function

    Example

    In the below code, we have passed the callback function as a last argument of the getSum() function. The getSum() function calls the callback function after passing the error and resultant sum value as an argument.

    Open Compiler

    <html><body><div id ="output">The sum of5 and 10 is:</div><script>functiongetSum(p, q, callback){let sum = p + q;setTimeout(()=>callback(null, sum),100);}getSum(5,10,(err, sum)=>{// callback function
    
         document.getElementById("output").innerHTML += sum;});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    The sum of 5 and 10 is: 15
    

    Lets perform the promisification of the callback functions discussed in the above example.

    Promisification of Callback Fucntion

    Example

    Lets understand the below code step by step.

    Step 1 − First, we have created the findSum() function. It takes the p1, p2, and callback function as a parameter.

    Step 2 − Next, the findSum() function checks whether the p1 and p2 are valid. If not, it calls the callback function by passing the error as an argument.

    Step 3 − In other cases, it calls the callback function by passing the sum and message as arguments.

    Step 4 − Next, we have defined the promisifyFunc() function, which takes the function as an argument that is needed to promisify.

    Step 5 − The promisifyFunc() function returns the function, and that function returns the promise.

    Step 6 − In the promise, we have defined the callbackFunc() function, which resolves or rejects the promise based on the argument it receives.

    Step 7 − Next, we insert the callbackFunc() function into the args array and use the call() method to call the func function, which we received as a parameter of the promisifyFunc() function.

    Step 8 − After that, we call the promisifyFunc() function and store the returned function in the getSUmPromise() function.

    Step 9 − When you execute the getSumPromise() function, it returns the promise, which you can consume the then() and catch() method.

    Open Compiler

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");constfindSum=(p1, p2, callback)=>{if(!p1 ||!p2){returncallback(newError("Missing dependencies"),null);}const sum = p1 + p2;const msg ='The sum of numbers is '+ sum;returncallback(null, sum, msg);// We call the callback function}functionpromisifyFunc(func){return(...args)=>{// Returning a functionreturnnewPromise((resolve, reject)=>{// Returning a promise// Defining a custom callback for the functionfunctioncallbackFunc(err, ...data){if(err){returnreject(err)}returnresolve(data)}
    
               args.push(callbackFunc);// Adding callback function into argumentfunc.call(this,...args);// Calling the findSum() function})}}const getSumPromise =promisifyFunc(findSum)getSumPromise(5,10).then((message)=&gt;{
         output.innerHTML = message;}).catch((err)=&gt;{
         output.innerHTML = err;})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</code></pre>

    Output

    15,The sum of numbers is 15
    

    The above code looks complex, but if you use it to handle the nested callback functions, it becomes easy to manage them. Here, you can pass custom callback functions to the particular function inside the promise.