Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
Lori Zink
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given these declarations:
int i = 5;
short s = 3;
char c = 'a';
byte b = 2;
The following stuff compiles and I don't know why...
s += i;
c += i;
b += i;
The following stuff does NOT compile (needs explicit cast) and I don't understand WHY NOT if the first stuff did!
s = s + i;
c = c + i;
b = b + i;

------------------
 
Namrata Shetty
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i = 5;
short s = 3;
char c = 'a';
byte b = 2;
The following stuff compiles and I don't know why...
s += i;
c += i;
b += i;
the way the above above works is
s+=i; is actually seen by JVM as s=(short)(s+i);
casting is done by JVM whereas
s=s+i; //it needs an explicit cast
similarly for the other cases
 
Rashmi Hosalli
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats because when you use the operation and the assignment at the same time i.e += there is an implicait cast included...hence
s+=i is equivalent to s = (short)s+i;
but when you say s = s + i,there is no casting done and you get a compile time error.
Rashmi
 
Alex Sbityakov
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW,
++,-- have implicit casts too,
Alex
 
Guoqiao Sun
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, all, as far as I know, the following operator will carry out implicit cast:

Correct me if i am wrong,
guoqiao
Originally posted by Alex Sbityakov:
BTW,
++,-- have implicit casts too,
Alex

 
Mini Pilla
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don' think ++,-- have implicit cast.
Thanx
Rajani
Originally posted by Alex Sbityakov:
BTW,
++,-- have implicit casts too,
Alex

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic