Can you create a matrix of primitive types that default to all zeros?

Yes, you can, and here’s how

Q: Is there anything in the Java specification that says a matrix of any primitive type will default to all zeros? For example, I am looking to optimize calculation results so that once I have a value from a calculation, I cache it, making all subsequent calls basically for free. Can I assume if I use the following statement:

double results[][]= new double[ 100 ][ 8 ]; 

that all indices are the same value (that is, 0, NaN, and so on)?

A: The way that it is

Java initialization is fairly straightforward and, more importantly, consistent. The consistency is important because it ensures common, portable behavior on all platforms. As such, with Java you never have to worry about primitive sizes or initialization behavior.

Practically, initialization issues break down into the following categories: local variables, final members, and everything else.

Local variables

You must explicitly initialize local variables. Local variables are those found inside of methods.

Final members

You must explicitly initialize final instance member variables either in their declaration or within the constructor.

Everything else

All class member variables, instance member variables, and array variables are initialized in the following ways:

Type Default value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char ‘u0000’
boolean false
references null

Your question

Let’s look a bit closer at your question. Take the following class definition as an example:

 
public class TestClass 
{ 
   public TestClass(int val) 
{ 
   memberFinalInt = val; 
} 
public void TestMethod() 
{ 
double results[][]= new double[ 100 ][ 8 ]; 
} 
public final int memberFinalInt; 
public [] int memberArrayInt; 
public int memberInt; 
} 

Let’s look at the members first. When instantiated, TestClass‘s memberInt is initialized to 0. memberArrayInt is initialized to null, and MemberFinalInt is initialized within the constructor to val.

Inside of TestMethod, I’ve created a double array with dimensions [100][8]. That creates an array with 100 double buckets, each bucket containing 8 doubles. Each double is initialized to 0, as per the Java specifications.

That’s about all there is to it.

Source: www.infoworld.com