HudaTutorials.com

Java double Array - double Array in Java

Last updated on

double Array in Java

double Array Java

Java double Array

Java double array is used to store double data type values only. The default value of the elements in a double array Java is 0.

With the following java double array examples you can learn

  • how to declare java double array
  • how to assign values to java double array
  • how to get values from java double array
  • How to sort double array in java

What is double in Java ?

The double is a keyword in Java and also a primitive data type. The double data type is a double precision 64-bit IEEE 754 floating point in Java. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, double data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Exploring Double Arrays in Java : A Comprehensive Guide

Java Double Array Introduction :

In Java, arrays serve as fundamental data structures for storing and manipulating collections of elements of the same type. Among these, double arrays hold a special place, allowing for the storage of floating-point numbers with double precision. This article aims to provide a comprehensive guide to working with double arrays in Java, covering their declaration, initialization, manipulation, and common operations.

Understanding Double Arrays:

A double array in Java is a one dimensional array or single dimensional array that stores elements of the double data type. Double precision floating-point numbers in Java conform to the IEEE 754 standard, providing a significant range and precision for representing fractional values.

Declaration, Initialization, Accessing and Modifying Elements:

Double arrays can be declared and initialized in various ways, depending on the requirements:

  1. Declaration:
    double[] doubleArray;
  2. Initialization with a Specific Size:
    doubleArray = new double[5];
  3. Initialization with Values:
    double[] initializedArray = {1.5, 2.7, 3.2, 4.8, 5.1};
  4. Accessing and Modifying Elements:
    double value = initializedArray[index]; // Accessing an element
    initializedArray[index] = newValue; // Modifying an element
  5. How to sort double array in java

    In Java, you can sort a double array using the Arrays class from the java.util package. Here's how you can do it using the sort method:

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            double[] arr = {3.5, 1.2, 4.7, 2.1, 5.0};
            
            // Sorting the array in ascending order
            Arrays.sort(arr);
            
            // Printing the sorted array
            System.out.println("Sorted array in ascending order:");
            for (double num : arr) {
                System.out.print(num + " ");
            }
            System.out.println();
            
            // Sorting the array in descending order
            // Since there's no built-in method for sorting in descending order, 
            // you can first sort in ascending order and then reverse the array
            Arrays.sort(arr);
            reverse(arr);
            
            // Printing the sorted array in descending order
            System.out.println("Sorted array in descending order:");
            for (double num : arr) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
        
        // Method to reverse an array
        private static void reverse(double[] arr) {
            int start = 0;
            int end = arr.length - 1;
            while (start < end) {
                double temp = arr[start];
                arr[start] = arr[end];
                arr[end] = temp;
                start++;
                end--;
            }
        }
    }

    Note that for descending order, we first sort the array in ascending order using Arrays.sort() and then reverse the array. The above code will output:

    Sorted array in ascending order:
    1.2 2.1 3.5 4.7 5.0 
    Sorted array in descending order:
    5.0 4.7 3.5 2.1 1.2

Common Operations:

Double arrays support a variety of common operations, including:

  • Iterating through the array using loops (e.g., for loop, enhanced for loop, while loop).
  • Finding the length of the array using the 'length' attribute.
  • Performing mathematical operations on array elements (e.g., sum, average, min, max).
  • Sorting the array using built-in sorting methods or custom algorithms.

Example: Calculating Average of Double Array:

Here's an example demonstrating how to calculate the average of elements in a double array:

double[] values = {10.5, 20.7, 15.3, 18.9, 22.1};
double sum = 0;

for (double value : values) {
    sum += value;
}

double average = sum / values.length;
System.out.println("Average: " + average);

Single, Double and Multi Dimensional Arrays with Java Double Arrays

Arrays are fundamental data structures in Java used for storing collections of elements of the same type. They offer a convenient way to organize and manipulate data efficiently. In this article, we'll explore different types of arrays in Java, with a particular focus on double arrays. We'll cover single dimensional, double dimensional or 2D Arrays, and 3D Arrays or multi dimensional arrays, highlighting their declaration, initialization, access, and common operations.

Single Dimensional Arrays:

Single dimensional arrays, also known as one dimensional arrays, store elements in a linear sequence. They are declared and initialized with a specific size or with predefined values. Here's an example of a single dimensional double array:

double[] singleArray = {1.5, 2.7, 3.2, 4.8, 5.1};
Single Dimensional Array Example using Java double Array
public class Main {
    public static void main(String[] args) {
        // Creating a single-dimensional array of doubles
        double[] prices = {12.5, 10.2, 15.75, 20.0, 8.99};
        
        // Accessing elements of the single-dimensional array
        System.out.println("Prices:");
        for (int i = 0; i < prices.length; i++) {
            System.out.println("Item " + (i + 1) + ": $" + prices[i]);
        }
    }
}

In this example, prices is a single-dimensional array of doubles, representing the prices of items. The loop iterates over the array and prints each element along with its index.

Double Dimensional Arrays:

Double dimensional arrays, also known as two dimensional arrays or 2D Arrays, are arrays of arrays. Each element of the outer array holds another array as its value. Here's an example of a double dimensional array of double type:

double[][] double2DArray = {
    {1.1, 2.2, 3.3},
    {4.4, 5.5, 6.6},
    {7.7, 8.8, 9.9}
                    };
Example of a double-dimensional array (or a 2D array) of doubles in Java
public class Main {
    public static void main(String[] args) {
        // Creating a 2D array of doubles
        double[][] matrix = {
            {1.5, 2.5, 3.5},
            {4.5, 5.5, 6.5},
            {7.5, 8.5, 9.5}
        };
        
        // Accessing elements of the 2D array
        System.out.println("Matrix:");
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.println("Element at row " + i + ", column " + j + ": " + matrix[i][j]);
            }
        }
    }
}

In this example, matrix is a double-dimensional array of doubles. It represents a 3x3 matrix. The nested loops iterate over the rows and columns of the matrix, printing each element along with its row and column indices.

Multi Dimensional Arrays:

Multi dimensional arrays extend the concept of double dimensional arrays to more than two dimensions. Which arrays holds more than two dimensions are called as multi dimensional array. They are declared and initialized similarly to double dimensional arrays but with additional dimensions. Here's an example of a three dimensional array of double type:

double[][][] double3DArray = {
    {{1.1, 1.2}, {1.3, 1.4}},
    {{2.1, 2.2}, {2.3, 2.4}}
                    };

Following is the example of a multi-dimensional array (specifically a 3D array) of doubles in Java.

public class Main {
    public static void main(String[] args) {
        // Creating a 3D array of doubles
        double[][][] multiArray = {
            {
                {1.1, 1.2},
                {1.3, 1.4}
            },
            {
                {2.1, 2.2},
                {2.3, 2.4}
            }
        };
        
        // Accessing elements of the 3D array
        System.out.println("Multi-dimensional array:");
        for (int i = 0; i < multiArray.length; i++) {
            for (int j = 0; j < multiArray[i].length; j++) {
                for (int k = 0; k < multiArray[i][j].length; k++) {
                    System.out.println("Element at layer " + i + ", row " + j + ", column " + k + ": " + multiArray[i][j][k]);
                }
            }
        }
    }
}

Following example demonstrating single, double, and multi-dimensional arrays using Java double arrays:

public class Main {
    public static void main(String[] args) {
        // Single-dimensional array
        double[] singleArray = {1.1, 2.2, 3.3, 4.4, 5.5};
        
        // Accessing elements of the single-dimensional array
        System.out.println("Single-dimensional array:");
        for (int i = 0; i < singleArray.length; i++) {
            System.out.println("Element at index " + i + ": " + singleArray[i]);
        }
        
        // Double-dimensional array
        double[][] doubleArray = {
            {1.1, 1.2, 1.3},
            {2.1, 2.2, 2.3},
            {3.1, 3.2, 3.3}
        };
        
        // Accessing elements of the double-dimensional array
        System.out.println("\nDouble-dimensional array:");
        for (int i = 0; i < doubleArray.length; i++) {
            for (int j = 0; j < doubleArray[i].length; j++) {
                System.out.println("Element at row " + i + ", column " + j + ": " + doubleArray[i][j]);
            }
        }
        
        // Multi-dimensional array
        double[][][] multiArray = {
            {
                {1.1, 1.2},
                {1.3, 1.4}
            },
            {
                {2.1, 2.2},
                {2.3, 2.4}
            }
        };
        
        // Accessing elements of the multi-dimensional array
        System.out.println("\nMulti-dimensional array:");
        for (int i = 0; i < multiArray.length; i++) {
            for (int j = 0; j < multiArray[i].length; j++) {
                for (int k = 0; k < multiArray[i][j].length; k++) {
                    System.out.println("Element at layer " + i + ", row " + j + ", column " + k + ": " + multiArray[i][j][k]);
                }
            }
        }
    }
}

What is a double array in Java ?

A double array is an array that holds a primitive double data type values or Java Double wrapper class in Java. A double array in Java is an array that holds elements of the 'double' data type. It is declared like any other array in Java, but it specifically stores floating-point numbers with double precision.

How do you declare a double array in Java?

Following statement shows you how to declare a double array in Java.

// double array declaration
double doublearray[5];

In the above Java double array declaration double is a primitive data type and doublearray[5] is a double array variable with 5 array elements of type double.

How to declare and initialize a double array in Java ?

// Declare a double array
double[] doubleArray;

// Initialize the array with a specific size
doubleArray = new double[5];

// Initialize the array with values
double[] initializedArray = {1.5, 2.7, 3.2, 4.8, 5.1};

// Accessing elements of the array
double firstElement = initializedArray[0]; // Accesses the first element (1.5)
double thirdElement = initializedArray[2]; // Accesses the third element (3.2)

// Modifying elements of the array
initializedArray[1] = 10.0; // Changes the second element to 10.0

How to create a double array in Java ?

Creating a double array in Java is very simple, it is in a single line. You could use a double array to store a collection of double data. You can define a double array in Java as follows :

// creating a Java double array
double double_array[] = new double[10];

Initializing a double Array in Java

Arrays are declared with [] (square brackets). If you put [] (square brackets) after any variable of any type only that variable is of type array remaining variables in that declaration are not array variables those are normal variables of that type.

If you put [] (square brackets) after any data type all the variables in that declaration are array variables. All the elements in the array are accessed with index. The array element index is starting from 0 to n-1 number i.e. if the array has 5 elements then starting index is 0 and ending index is 4.

// declares an array of doubles
double[] doubleArray;

What is the Length of an Array in Java ?

In Java all the arrays are indexed and declared by int only. That is the size of an array must be specified by an int value and not long or short. All the arrays index beginning from 0 to ends at 2147483646. You can store elements upto 2147483647. If you try to store long (big) elements in array, you will get performance problems. If you overcome performance problems you should go to java collections framework or simply use Vector.

Syntax :

< data type > < variable >[];
< data type >[] < variable >;

Related : Java boolean Array

Java double Array Example

Following example shows Java double Array . Save the following Java double Array example program with file name JavaDoubleArrayExample.java .

public class JavaDoubleArrayExample
{
	public static void main(String args[])
	{
		double a[];
		a = new double[4];
		// java double array initialization
		a[0] = 100000d;
		a[1] = 300000d;
		a[2] = 400000d;
		a[3] = 786777d;
		System.out.println("Java double Array Example");
		for(int i=0;i<a.length;i++)
		{
			System.out.println("Element at Index : "+ i + " " + a[i]);
		}
	}
}

Related : Java byte Array

How to assign values to Java double array at the time of declaration ?

Following Java double array example you can learn how to assign values to Java double array at the time of declaration.

Following example shows How to assign values to Java double array at the time of declaration . Save the following assign values to Java double array at the time of declaration example program with file name AssignDoubleArrayValuesAtDeclaration.java .

Assign values to Java double array at the time of declaration Example

public class AssignDoubleArrayValuesAtDeclaration
{
	public static void main(String args[])
	{
		double a[] = {100000d,300000d,400000d,786777d};
		System.out.println("Java double Array Example");
		for(int i=0;i<a.length;i++)
		{
			System.out.println("Element at Index : "+ i + " " + a[i]);
		}
	}
}

Related : Java char Array

How to declare Java double array with other Java double array variables ?

Following Java double array example you can learn how to declare Java double array with other Java double array variables.

Following example shows Declare Java double array with other Java double array variables . Save the following Declare Java double array with other Java double array variables example program with file name DeclareJavaDoubleArrayWithDoubleVariables.java .

Declare Java double array with other Java double array variables Example

public class DeclareJavaDoubleArrayWithDoubleVariables
{
	public static void main(String args[])
	{
		double a[], a2;
		a = new double[4];
		a[0] = 100000d;
		a[1] = 300000d;
		a[2] = 400000d;
		a[3] = 786777d;
		a2 = 333333d;
		System.out.println("Java double Array Example");
		System.out.println("a2 value is : "+a2);
		for(int i=0;i<a.length;i++)
		{
			System.out.println("Element at Index : "+ i + " " + a[i]);
		}
	}
}

Related : Java short Array

How to assign Java double array to other Java double array ?

Following Java double array example you can learn how to assign Java double array to other Java double array.

Following example shows How to assign Java double array to other Java double array . Save the following assign Java double array to other Java double array example program with file name AssignJavaDoubleArrayToDoubleArray.java .

Assign Java double array to other Java double array Example

public class AssignJavaDoubleArrayToDoubleArray
{
	public static void main(String args[])
	{
		double[] a, a2;
		a = new double[4];
		a[0] = 100000d;
		a[1] = 300000d;
		a[2] = 400000d;
		a[3] = 786777d;
		a2 = a;
		System.out.println("Java double Array Example");
		System.out.println("a array values");
		for(int i=0;i<a.length;i++)
		{
			System.out.println("Element at Index : "+ i + " " + a[i]);
		}
		System.out.println("a2 array values");
		for(int i=0;i<a2.length;i++)
		{
			System.out.println("Element at Index : "+ i + " " + a2[i]);
		}
	}
}

Related : Java int Array

How to Convert double Array to String in Java ?

The java.util.Arrays.toString(double[]) method returns a string representation of the contents of the specified double array . The string representation consists of a list of the array's elements, enclosed in square brackets ("[]") . Adjacent elements are separated by the characters ", " (a comma followed by a space) .

The following example shows the usage of java.util.Arrays.toString() method .

Following example shows How to Convert Java double array to String Example . Save the following Convert Java double array to String Example program with file name ConvertDoubleArrayToString.java .

How to Convert Java double array to String Example

import java.util.Arrays;
public class ConvertDoubleArrayToString
{
	public static void main(String args[])
	{
		double double_array[] = {100, 200, 300, 400};
		// converting java double array to string
		System.out.println("converted double array to String");
		System.out.println(Arrays.toString(double_array));
	}
}

How to Convert a double array to a float array in Java ?

Convert a double array to a float array in Java is not possible by using casting the array. You need to explicitly convert each array item. Following example shows how to convert a double array to a float array in Java.

Following example shows How to Convert a double array to a float array in Java . Save the following Convert a double array to a float array in Java example program with file name ConvertDoubleArrayToFloatArray.java .

Convert a double array to a float array in Java Example

public class ConvertDoubleArrayToFloatArray
{
	public static void main(String args[])
	{
		double[] doubleArray = {3.5,5.0,7.5,11.55};
		float[] floatArray = new float[doubleArray.length];
		for (int i = 0 ; i < doubleArray.length; i++)
		{
			floatArray[i] = (float) doubleArray[i];
		}
		for(int i=0; i < floatArray.length; i++)
		{
			System.out.println("Element at Index "+ i + " is : " + floatArray[i]);
		}
	}
}

Related : Java float Array

How to Convert a float array to a double array in Java ?

Convert a float array to a double array in Java is not possible by using casting the array. You need to explicitly convert each array item. Following example shows how to convert a float array to a double array in Java. In the below example don't forget to put f after the float values. The float values must be specify with f because Java compiler treat as double value.

Following example shows How to Convert a float array to a double array in Java . Save the following Convert a float array to a double array in Java example program with file name ConvertFloatArrayToDoubleArray.java .

Convert a float array to a double array in Java Example

public class ConvertFloatArrayToDoubleArray
{
	public static void main(String args[])
	{
		float[] floatArray = {2.0f,1.5f,8.45f,116.77f};
		double[] doubleArray = new double[floatArray.length];
		for (int i = 0 ; i < floatArray.length; i++)
		{
			doubleArray[i] = (double) floatArray[i];
		}
		for(int i=0; i < doubleArray.length; i++)
		{
			System.out.println("Element at Index "+ i + " is : " + doubleArray[i]);
		}
	}
}

Related : Java long Array

How to Initialize ArrayList with doubles ?

ArrayList can not take primitive data type double. We can use the Java wrapper class Double instead of Java primitive double data type.

Initializing ArrayList with doubles Example

import java.util.*;
public class JavaDoubleArrayList
{
	public static void main(String args[])
	{
		ArrayList<Double> java_double_arraylist = new ArrayList<Double>(Arrays.asList(new Double[10]));
		Collections.fill(java_double_arraylist, 77.33d);
		System.out.println(java_double_arraylist);
	}
}