Java Array Sum sum(final byte[] array)

Here you can find the source of sum(final byte[] array)

Description

Sums an array of bytes.

License

Apache License

Parameter

Parameter Description
array Byte array.

Return

The sum of the values of the array. Returns 0 if the array is 0 or empty.

Declaration

public static long sum(final byte[] array) 

Method Source Code

//package com.java2s;
/*/*from w w  w . j  a va 2 s  .co m*/
 *  Copyright 2011 Eric F. Savage, code@efsavage.com
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

public class Main {
    /**
     * Sums an array of bytes.
     * 
     * @param array
     *            Byte array.
     * @return The sum of the values of the array. Returns 0 if the array is 0
     *         or empty.
     */
    public static long sum(final byte[] array) {
        if (array == null || array.length == 0) {
            return 0;
        }
        int retVal = array[0];
        for (int i = 1; i < array.length; i++) {
            retVal += array[i];
        }
        return retVal;
    }

    /**
     * Sums an array of integers.
     * 
     * @param array
     *            Integer array.
     * @return The sum of the values of the array. Returns 0 if the array is 0
     *         or empty.
     */
    public static long sum(final int[] array) {
        if (array == null || array.length == 0) {
            return 0;
        }
        int retVal = array[0];
        for (int i = 1; i < array.length; i++) {
            retVal += array[i];
        }
        return retVal;
    }
}

Related

  1. sum(double[] vector)
  2. sum(double[] x)
  3. sum(double[] x, int length)
  4. sum(double[] x, int start, int end)
  5. sum(double[] xs)
  6. sum(final double... values)
  7. sum(final double[] a)
  8. sum(final double[] arr)
  9. sum(final double[] array)