hi
how are u all

this is my program

import javax.swing.*;
public class Qustion2 {  
              
   public static void main (String args[]){  

    double x =2/3;
    double y = (3*x*x)-(8*x)+4;
     
      JOptionPane.showMessageDialog(null,"At x= " + x +" the value is " + y);

        }
    }

Mathematically when i substitute x =2/3

i get result equal zero but here i didn't get it

any body tell me why ?

Recommended Answers

All 8 Replies

Because 2 and 3 are Integers, so pure Integer math is performed.

Use a literal double (i.e. 2.0 instead of 2) or cast at least one of them to a double

double a = (double) 2 / 3;
// or
double b = 2 / (double) 3;
// or
double c = (double) 2 / (double) 3;
// or
double d = 2.0 / 3;
// or
double e = 2 / 3.0;
// or
double f = 2.0 / 3.0;
// or any combination of casting and literal doubles
commented: Helpful! +6

thank you very much
i appreciate your help,but if the value of an expression in an assignment statements are not of the same data type, the an assignment conversion occurs.

but when we talking about double, it has a higher precision.
so 2/3 is valid

i wanna know, in java why we don't get zero in this situation.
while mathematically when dividing 2/3 it give us 0.666666.... ??

Because what is automatically "converted" is the result of the operation, not the individual pieces of the operation. Therefore, the operation consists of two Integers 2/3, therefore Integer math is performed resulting in Integer 0. And the Integer 0, automatically converted to double is 0.0.

Edit: And what do you mean by

in java why we don't get zero in this situation

You do get zero in this situation, and for the reasons explained above.

Edit Again: Why do people simply refuse to believe either 1) there own eyes or 2) explanations from people who know, simply because their initial impression of their own code is "it should be right", even though it's not?

ok don't be angry :)
i just want to know why thats all!!!
i'm student in the first year coz that i'm asking so many questions :(
and Unfortunately i didn't get it

when i run this program with double=2/3
i get the result=4.0 instead of 0

i wanna know why ?
:)

And I just told you. It is because x is 0 so that equation for y becomes 0-0+4, which is 4, of course.

now i got it
thank you very much
i really appreciate your help
:D:D:D

Do you also have a firm grasp of the integer math that was happening in the first place (i.e. why the integer 2 divided by the integer 3 yields the integer 0)?

Just in case you don't, it's because 2 will not divide evenly by 3, so there is no whole number N where 3*N = 2. The result of 2/3 would be zero with a remainder of 2. That remainder can be found using the modulo operator (%).

For instance:
2/3 = 0
2%3 = 2

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.