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
  • 127,459
  • 24
  • 238
  • 287
Eamon Moloney
  • 1,853
  • 4
  • 19
  • 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
  • 97,814
  • 39
  • 186
  • 310
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
  • 158,873
  • 26
  • 254
  • 302
PermGenError
  • 45,977
  • 8
  • 87
  • 106
3

You may simply cast it:

int c = (int)b;
kosa
  • 65,990
  • 13
  • 130
  • 167
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,483
  • 4
  • 23
  • 41
FK82
  • 4,907
  • 4
  • 29
  • 42
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,557
  • 14
  • 55
  • 86
0

This simple line will do the job.

integer_var_name = (int) double_var_name;
Jagger
  • 10,350
  • 9
  • 51
  • 93
scanE
  • 332
  • 4
  • 19