• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arithmetic Operations

 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Shahnawaz Shakil
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 165
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic