dcsimg
why can't I add two short type variables in java? what is the concept behind it?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   prasanna_d
Posted On:   Friday, March 13, 2009 06:41 AM

can anyone tell me why does not this code work?

public class xxx{

public static void main(String[] args){
short s1;
short s2;
s1 = 8;
System.out.println("++++++++++ s1 = "+s1);
s2 = s1+ 5;
System.out.println("++++++++++ s2 = "+s2);
}

}

Re: why can't I add two short type variables in java? what is the concept behind it?

Posted By:   Anonymous  
Posted On:   Monday, April 13, 2009 02:20 AM

In Java, the default numeric type is integer. Hence when you add up two short type or 1 short type with a numeric constants then the result get converted to premitive integer type.



Another concept to remember is that size of the numeric types grows in following order.



byte-> short -> int ->double



Hence when you want to assign the result (which will be in default int type) to a short there will be a precision loss, hence java wont allow that without programmer's knowledge. If you want to do that explicitly then you have to type cast it like in the below example.



short a = 2;

short b = 3;

short c = (short) (a + b);
About | Sitemap | Contact