Meaningless Drivel is fun!
The moose likes Mock Exam Errata and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "casting" Watch "casting" New topic


gaurav nayyar

Joined: Jul 13, 2001
Posts: 9
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

Joined: Aug 30, 2000
Posts: 3141
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

Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Asma Zafar
Ranch Hand

Joined: May 11, 2001
Posts: 49
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

Asma Zafar,<BR>Sun Certified Programmer for Java2 Platform
I agree. Here's the link:
subject: casting
jQuery in Action, 3rd edition