-5

I was doing simple java programming.But I couldn't find why my code doesn't show exect output.It should print the sqrt of given number but the output is 0.

import java.lang.*;
class Calculator{
    double i;
    double x=Math.sqrt(i);
    
}
public class MultipleObject {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Calculator a=new Calculator();
        a.i = 16;
        System.out.println(a.x);

    }

}

2 Answers2

2

your are not setting x (Math.sqrt(i)) in the right place

import java.lang.*;
class Calculator{
    double i;
//  double x=Math.sqrt(i); // won't work here
    double x;
    
}
public class MultipleObject {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Calculator a=new Calculator();
        a.i = 16;
      // you could do it here
        a.x = Math.sqrt(a.i);
        System.out.println(a.x);

    }

}

or what you could do is rather than making it a variable, make it a method

  public double getX() {
    return Math.sqrt(this.i);
  }
Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Why `double x=Math.sqrt(i);` won't work at instance field level? it will. – Giorgi Tsiklauri Jul 06 '20 at 17:31
  • @GiorgiTsiklauri it will not, as i as not been initialized yet. – ControlAltDel Jul 06 '20 at 17:32
  • 1
    instance fields are always initialized :) – Nowhere Man Jul 06 '20 at 17:33
  • @ControlAltDel that's another point, but it will crash at run-time. What I meant, is that there's nothing semantically wrong. `i` can be initialized via constructor, though, as it's not statically bound and constructor will execute before the `Math.sqrt` call. – Giorgi Tsiklauri Jul 06 '20 at 17:36
  • @AlexRudenko If you mean initialized to null or 0, then yes. But this isn't helping the conversation with the given code – ControlAltDel Jul 06 '20 at 17:36
  • @ControlAltDel haha, I was wrong, it doesn't even crash. :)) – Giorgi Tsiklauri Jul 06 '20 at 17:42
  • @GiorgiTsiklauri _constructor will execute before_ is not quite true -- if there was constructor initializing _only i_ (e.g. with 16), it would not help to set `x = Math.sqrt(i);` to 4. – Nowhere Man Jul 06 '20 at 17:54
  • Yeah, agree. Actually was just recalling initialization order.. and it's not clearly given in JLS. But yea.. constructor will execute after static block, static fields, and instance block and instance fields initialized bound statically. – Giorgi Tsiklauri Jul 06 '20 at 18:45
0

x is evaluated when you create an instance of Calculator, and at this moment it is 0.0.

You should pass i via constructor, and evaluate x in either constructor or method.

class Calculator {
   public final double x; 
   Calculator(double i) {
      this.x = Math.sqrt(i);
   }
}
> new Calculator(100).x
$1 ==> 10.0
andreoss
  • 1,570
  • 1
  • 10
  • 25