File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Arithmetic Operations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arithmetic Operations" Watch "Arithmetic Operations" New topic
Author

Arithmetic Operations

Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
Why I'm getting the comlipe time error for the program?



---------- Compile ----------
Num_Pro.java:6: possible loss of precision
found : int
required: short
a =a+2;
^
1 error
Normal Termination
Output completed (2 sec consumed).

If 40 can be represented as short then why not 42?

[edit]Add code tags. CR[/edit]
[ August 18, 2008: Message edited by: Campbell Ritchie ]

Thanks,
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57
Hi Philipe,
Always remember that irrespective of the data type of a, the result of a + 2 will be an int. And since you can not assign an int value (even if it is in range of short or byte) to shorter data type without explicitly casting it, you can not assign the result of a+2 (which is an int) to a(which is short). You need to cast the result as following:
a = (short)(a+2);
This will run fine.
Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
But in the below program why no explicit casting required.




[edit]Add code tags. CR[/edit]
[ August 18, 2008: Message edited by: Campbell Ritchie ]
Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
Program with corrections.Why no explicit casting required below

[edit]add code tags. CR[/edit]
[ August 18, 2008: Message edited by: Campbell Ritchie ]
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57
Hi Phillip,
Why do you think that an explicit cast is required here? You are declaring a variable of type short and incrementing it. When you increment a variable of type short then the number 1 which is added is of type short. But when you increment it using binary operator + by writing (a+1) then here 1 is an integer and consequently the result becomes an integer.
Remember:
a++ //compiler takes care of adding a value one of the same datatype as of a
a+1 //You are telling the compiler to add the value 1 of type integer
[ August 18, 2008: Message edited by: Shahnawaz Shakil ]
eshu khare
Ranch Hand

Joined: Aug 01, 2008
Posts: 44
hi,

the above suggestions are absolutely good at their place,thogh I am new to the java programing but still have one solution which is as below.


Thanks & Regards
Eshu Khare
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arithmetic Operations