Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

does += (in general - all shorthand operators) imply an implicit cast?

 
Aakash Goel
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is wrong with...

char c = 'a';
c=c+4;


considering that

char c='a';
c+=4;

works fine!!

Thanks in advance!
 
Tom Kowalski
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It`s because, those expressions are similar but not exactly this same. When you use ‘+=’ java will cast the expression automatically so when you write:

The compiler will see something like this:

P.S I suggest you K&B book, you will find there many answers which will appear for sure, while you are learning for SCJP ^^

 
Paolo Dina
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to reply to the question in the subject, YES. Quote from JLS.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
 
Aakash Goel
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just wanted to confirm that implicit cast is implied. thanks everyone
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic