This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about ~ operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about ~ operator" Watch "Question about ~ operator" New topic
Author

Question about ~ operator

Sudhakar Krishnamurthy
Ranch Hand

Joined: Jun 02, 2003
Posts: 76
Can anyone shed some light on this behavior??

short i =0;
i>>=i; //compiles fine, an int is implicitly converted to a short here
i~=i; //throws a compiler error, explict casting is required here

Why?
TIA
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
As far as I know, there is no such operator as ~=. ~ is the Unary NOT operator, which means that it only functions on one operand. The compound assignment operators are designed to be shorthand notations of Binary Operators, such as +, -, >>, etc.


SCJP Tipline, etc.
Sudhakar Krishnamurthy
Ranch Hand

Joined: Jun 02, 2003
Posts: 76
i get it, thanks
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Originally posted by Sudhakar Krishnamurthy:
Can anyone shed some light on this behavior??

short i =0;
i>>=i; //compiles fine, an int is implicitly converted to a short here
i~=i; //throws a compiler error, explict casting is required here

Why?
TIA


I changed the code slightly as below:

The compiler indicates that it will not compile because of a possible loss of precision. This makes sense because you are trying to put an integer value (32 bits) into a short value (16 bits). Remember that the value of the short variable,i, will be promoted to an integer before applying the unary operator. Thus, an explicit cast is required. This can result in some strange results when attempting this operation.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Question about ~ operator
 
Similar Threads
short ckt ques from mock exam
operators
bitwise >>> strange behaviour
Please explain....!!!!
which version is used