• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;

------------------
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
BTW,
++,-- have implicit casts too,
Alex
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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


 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don' think ++,-- have implicit cast.
Thanx
Rajani

Originally posted by Alex Sbityakov:
BTW,
++,-- have implicit casts too,
Alex


reply
    Bookmark Topic Watch Topic
  • New Topic