6

I'm looking at http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html

I am trying

    double b = Math.sqrt(absoluteNumber);
    int c = b.intValue();

but I am getting this error:

Factorise.java:13: error: double cannot be dereferenced
int c = b.intValue();

Help please?

arshajii
  • 123,543
  • 24
  • 232
  • 276
Eamon Moloney
  • 1,753
  • 4
  • 18
  • 22

6 Answers6

15

double is not an object, it is a primitive type.

Simply writing (int)b will do the job.

If you really need a Double object, you need to construct one.

bmargulies
  • 94,623
  • 39
  • 172
  • 299
6

double is a "primitive type", it doesn't have an intValue() method (in fact it doesn't have any methods, as it is a primitive). Try the Double wrapper class, which has an intValue() method.

Double b = Math.sqrt(absoluteNumber);
int c = b.intValue();

Or simply use casting:

double b = Math.sqrt(absoluteNumber);
int c = (int) b;
Dave Newton
  • 156,572
  • 25
  • 250
  • 300
PermGenError
  • 45,111
  • 8
  • 85
  • 106
2

You may simply cast it:

int c = (int)b;
kosa
  • 64,776
  • 13
  • 121
  • 163
1

The specific compile time error in your class is the result of trying to call a method on a value which was declared as a primitive type. Primitive types are not Objects and thus do not have properties. Hence they do not have any methods.

You could either cast the primitive double value to a primitive intvalue,

double b = Math.sqrt(absoluteNumber) ;
int a = (int) b ; 

or cast the double to a Double---using a Java feature called auto-boxing---in order to use the intValue method of the Number interface implemented by the Double class:

double b = Math.sqrt(absoluteNumber) ;
int a = ( (Double) b ).intValue( ) ;

Another way is to use the valueOf and intValue methods of the Double class:

double b = Math.sqrt(absoluteNumber) ;
int a = ( Double.valueOf(b) ).intValue( ) ;
bw_üezi
  • 4,371
  • 4
  • 21
  • 41
FK82
  • 4,747
  • 4
  • 26
  • 40
0

Try

public static void main(String[] args) {
        Double  b = Math.sqrt(43253);
        int c = b.intValue();

        System.out.println("#### S = " + c);

    }

Output

#### S = 207
Bhavik Ambani
  • 6,464
  • 14
  • 53
  • 86
0

This simple line will do the job.

integer_var_name = (int) double_var_name;
Jagger
  • 10,048
  • 7
  • 47
  • 88
scanE
  • 332
  • 4
  • 19