Win a copy of Event Streams in Action this week in the Java in General forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Devaka Cooray
• Liutauras Vilda
• Jeanne Boyarsky
• Bear Bibeault
Sheriffs:
• Paul Clapham
• Knute Snortum
• Rob Spoor
Saloon Keepers:
• Tim Moores
• Ron McLeod
• Piet Souris
• Stephan van Hulst
• Carey Brown
Bartenders:
• Tim Holloway
• Frits Walraven
• Ganesh Patekar

# short or int?

Ranch Hand
Posts: 114
what's wrong with the following ?
short s=9;
short p=s+9;
why s+9 is integer (since storage is 16bits for short)

Ranch Hand
Posts: 18944
Java is doing that to you on purpose. Java converts the types of the operands in arithmatic expressions. For example, if you add a long and an int, the result is a long because Java makes sure that both operands are promoted to long before doing the math. Operands of type short or byte are both automatically converted to int before performing the operation. That is why your result is an int. You could solve this problem by casting your result before setting the variable. For example:

<PRE>
short a = 1;
short b = (short)(a + 1);
</PRE>
Hope this helps.
Nick

nachiket deshpande
Ranch Hand
Posts: 114
thanks Nick!
i am little confused with the fundas of shifting bits.specially for negative integers.'
for example -1 is written as:111111110,is it appropriate to write it in integer form as 11111111 11111111 11111111 11111110

nachiket deshpande
Ranch Hand
Posts: 114
in continuation of my previous problem what happens to

nachiket deshpande
Ranch Hand
Posts: 114
sorry...
-1 is written as 11111111 is it correct?
now -1>>4 or -1>>5 or in general -1>>i will always give us -1.it it correct?

Greenhorn
Posts: 5
Yes its true that -1 is 11111111111111111111111111111111 in binary, so in any case-1>>i will give -1 because when it gives a right shift,again it remains samei.e 11111111111111111111111111111111

Originally posted by nachiket deshpande:
sorry...
-1 is written as 11111111 is it correct?
now -1>>4 or -1>>5 or in general -1>>i will always give us -1.it it correct?

[This message has been edited by Niti Gupta (edited October 31, 2000).]

 Consider Paul's rocket mass heater.