different behaviour of operators

K

Kavya

Here's the code

public class Main
{

public static void main (String[] args)
{
int b=10;
double r=0.0;
b =b + r*10.0;//This gives error
b+=r*10.0;// This works fine
System.out.println (b);
}
}

Error comes as
found: double
required:int

Why += version working?
 
P

Patricia Shanahan

Kavya said:
Here's the code

public class Main
{

public static void main (String[] args)
{
int b=10;
double r=0.0;
b =b + r*10.0;//This gives error
b+=r*10.0;// This works fine
System.out.println (b);
}
}

Error comes as
found: double
required:int

Why += version working?

"A compound assignment expression of the form E1 op= E2 is equivalent to
E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is
evaluated only once."

[http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304]

Your += is equivalent to:

b = (int)((b) + (r*10.0));

except for only evaluating b once, which makes no difference because
evaluating b has no side effects.

The line that gives the error does not have the (int) cast that is
implied by the +=.

Patricia
 
K

Kavya

Patricia said:
Kavya said:
Here's the code

public class Main
{

public static void main (String[] args)
{
int b=10;
double r=0.0;
b =b + r*10.0;//This gives error
b+=r*10.0;// This works fine
System.out.println (b);
}
}

Error comes as
found: double
required:int

Why += version working?

"A compound assignment expression of the form E1 op= E2 is equivalent to
E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is
evaluated only once."

[http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5304]

Your += is equivalent to:

b = (int)((b) + (r*10.0));

except for only evaluating b once, which makes no difference because
evaluating b has no side effects.

The line that gives the error does not have the (int) cast that is
implied by the +=.

Thank You.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top