title: How can I initialize a generic variable in Java?
body: <p>I am trying to write a method in which I need to create a temp variable, sum, of generic type T. However, I'm getting the error "The local variable sum may not have been initialized". How can I initialize a generic variable? I can't set it to 0 or 0.0, and I can't find information anywhere on how to deal with this. Here is the portion of code that I'm working with:</p>
  
  <pre><code>public Matrix&lt;T,A&gt; multiply(Matrix&lt;T,A&gt; right) throws MatrixException
  {
      Matrix&lt;T,A&gt; temp = new Matrix&lt;T,A&gt;(arithmetics, rowSize, columnSize);
  
      T sum, product;
  
      if (rowSize != right.columnSize)
          throw new MatrixException("Row size of first matrix must match column size " 
                  + "of second matrix to multiply");
  
      setup(temp,rowSize,columnSize);
  
      for (int i = 0; i &lt; rowSize; i++){
          for (int j = 0; j &lt; right.columnSize; j++) {
              product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i]));
              sum = arithmetics.add(product, sum);
              temp.matrix[i][j] = sum;
          }
      }
      return temp;
  }
  </code></pre>
  
  <p>I'm not sure if this will help clarify, but here is my interface Arithmetics:</p>
  
  <pre><code>public interface Arithmetics&lt;T&gt; {
  
  public T zero();
  public T add( T a, T b );
  public T subtract( T a, T b);
  public T multiply (T a, T b);
  public T parseString( String str );
  public String toString( T a );
  
  }
  </code></pre>
  
  <p>And here is one of my classes, DoubleArithmetics, just to show how I'm implementing the interface:</p>
  
  <pre><code>public class DoubleArithmetics implements Arithmetics&lt;Double&gt; {
  
  protected Double value;
  
  public Double zero() 
  {
  
      return new Double(0);
  }
  
  public Double add( Double a, Double b ) 
  {
  
      return new Double(a.doubleValue()+b.doubleValue());
  }
  
  public Double subtract (Double a, Double b)
  {
      return new Double(a.doubleValue()-b.doubleValue());
  }
  
  public Double multiply (Double a, Double b)
  {
      return new Double(a.doubleValue()*b.doubleValue());
  }
  
  public Double parseString( String str )
  {
      return Double.parseDouble(str);
  }
  
  public String toString( Double a )
  {
      return a.toString();
  }
  }
  </code></pre>