2
public class JAVA_Guevarra {

public static void main(String[] args) {
    //These are the variables
    double empBasicPay[] = {4000,5000,12000,6000,7500};
    double empHousingAllow[] = new double[5];
    int i;

    //This program computes for the payment of the employees
    for(i=0; i<5; i++){
        empHousingAllow[i] = 0.2 * empBasicPay[i];
        //This loop statement gets 20% of the employee basic payment
    }
    System.out.println("Employee Basic and House Rental Allowance");

    for(i = 0; i<5; i++){
        System.out.println(empBasicPay[i] + " " + empHousingAllow[i]);
        //This prints out the final output of the first loop statement
    }
}


}

What does the new double[5] do in this statement?

Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
Lee
  • 41
  • 2
  • 8

3 Answers3

2

it's not just new double, it is new double[5] which create an array for maximum 5 doubles

as oracle doc explain it well (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)

// declares an array of integers
int[] anArray;

// allocates memory for 10 integers
anArray = new int[10];

// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;

so double empHousingAllow[] = new double[5]; allocate memory for an array of five doubles

XioRcaL
  • 653
  • 2
  • 11
  • 23
0

The new keyword in Java is used to create objects. In this case, the object which is being created is an array containing five doubles.

You might want to have a look at this question, which describes declaration of arrays in greater detail.

Community
  • 1
  • 1
Zhewriix
  • 148
  • 10
0

Actually the concept required size when you define an array, later you can not change the size.

You can not assign value directly to the memory block like

double d[5];
d[0] = 10.05;

you need to create memory block with specific type. That's why you need to define an array in that manner.

double d[] = new double[5]

Or

double d[5];
d[0] = new double like that.

then you can add the value to that block.