File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operator n assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "operator n assignment" Watch "operator n assignment" New topic
Author

operator n assignment

pravin kumar
Ranch Hand

Joined: Nov 03, 2005
Posts: 30
What is the result that will be printed out here ?
int i = - 128;
System.out.println((byte)i << 1);

answer is -256 ..please explain how to calculate the same...
Jay Pawar
Ranch Hand

Joined: Aug 27, 2004
Posts: 411
Originally posted by pravin kumar:
What is the result that will be printed out here ?
int i = - 128;
System.out.println((byte)i << 1);

answer is -256 ..please explain how to calculate the same...


-128 is represented as 1111 1111 1111 1111 1111 1111 1000 0000

when you perform (byte)i << 1 last 8 bits of i are considered which are 1000 0000
and then left shift operation is carried out. Now point to be noted here is whenever a bit operation is performed the number is represented as int (32 bit) so -128 is represented as
1111 1111 1111 1111 1111 1111 1000 0000 and then when you left shift by 1
you get
1111 1111 1111 1111 1111 1111 0000 0000 which is -256


There would be big difference in the answer if you try to print this
System.out.println((byte)(i<<1));

Hope that helps
[ December 10, 2005: Message edited by: Jay Pawar ]

Cheers,<br />Jay<br /> <br />(SCJP 1.4)<br />Heights of great men were not achieved in one day, they were toiling day and night while their companions slept.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: operator n assignment
 
Similar Threads
HTML Tags in XML file
How to write the xsl for this...
Help Please!!!
XSLT string processing
Data base creation