wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "operator" Watch "operator" New topic
Author

operator

Mukesh Prajapati
Greenhorn

Joined: Feb 02, 2011
Posts: 10
public class MainClass{
public static void main(String[] argv){
byte b = 1;
byte b1 =-b;
System.out.println(b1);
}
}

why it gives error like this "possible loss of precision"
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

The range of byte is from -128 to +127. So there exists one byte value for which its negative cannot be represented as a byte. Hence the message.

(If you were thinking that the compiler will recognize that the value of "b" at that point would be 1, that's wrong. The compiler doesn't do any such thing.)
Suhas Mandrawadkar
Ranch Hand

Joined: Jul 21, 2007
Posts: 72

-Edited-
Following post is perfect explanation


Regards, Suhas S. Mandrawadkar.
Certifications: SCJP 6, SCWCD 5, Oracle WebLogic Server Administrator, OCE Java EE 6 EJB Developer
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Mukesh Prajapati wrote:public class MainClass{
public static void main(String[] argv){
byte b = 1;
byte b1 =-b;
System.out.println(b1);
}
}

why it gives error like this "possible loss of precision"


Hi Mukesh...You are getting error because you are trying to store an integer in byte variable....How? See when you are writing then you are assigning a Java expression(an expression is a combination of Java terms that yields a value) to byte variable b1....When the compiler evaluates an expression it will automatically promote data type (when compiler sees that an expression has a byte or short data type they will be converted to int) i.e when you are assigning -b to b1 then b will be converted to int data type and you cannot store an int value to byte variable..Why value was changed because when you are writing -b this is an expression since you are doing some manipulation....So when you write this way then no errors Since here you are assigning a value not an expression in b1 so no change of data type....So to avoid your error you have to do an explicit cast like this way
Mukesh Prajapati
Greenhorn

Joined: Feb 02, 2011
Posts: 10
thanks

Rameshwar Soni
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39086
    
  23
Suhas Mandrawadkar wrote:-Edited-
Following post is perfect explanation
Don't change your posts after they have been replied to.
Suhas Mandrawadkar
Ranch Hand

Joined: Jul 21, 2007
Posts: 72

Campbell Ritchie wrote:
Suhas Mandrawadkar wrote:-Edited-
Following post is perfect explanation
Don't change your posts after they have been replied to.


I understand. But it was out of context and harmless
 
GeeCON Prague 2014
 
subject: operator