File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
gaurav nayyar
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following lines of code
byte b = 0;
b += 1;

1.results in b having the value 1.
2.causes a compiler error.
3.will require a cast (byte) before 1.

answer is 1
but how is it different from
b= b+1
it generates a compiler error while above code doesnt why?
 
Jane Griscti
Ranch Hand
Posts: 3141
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guarav,
In the first instance <code>b += 1</code> narrowing primitive conversion rules apply (See JLS §5.1.3 and §15.26.2)
In the second example, <code> b = b + 1</code>, '1' is an int, the value for 'b' is promoted to an 'int' and the result is an 'int'; narrowing conversion rules are not applied.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
Asma Zafar
Ranch Hand
Posts: 49
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for the syntax op1 op= op2,
the actual expression becomes
op1 = (datatype of op1) (op1 op op2);
so casting has been done implicitly. That is:
byte b=0;
b += 1;
means b = (byte)(b+1) instead of
b= b+ 1 (where explicit casting will be required.)
Hope this helps,

------------------
Asma Zafar,
Sun Certified Programmer for Java2 Platform
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic