Search code examples
javaintdouble

Cannot resolve method 'intValue()'


I am trying to create a get method for a private double variable.

When I write

public class {

  private double x = 4.12;

  public int get(){
    double temp = new Double(this.x);
    return temp.intValue();
  }

}

The IDE suggest to remove Double Unnecessary boxing 'new Double(this.x)' and it does not recognize intValue() method. The same goes when just writing:

return this.x.intValue();

Solution

  • Primitives don't have methods, and there's no point in creating a new instance of Double only to immediately unwrap it again.

    Cast instead:

    return (int) this.x;