This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting" Watch "casting" New topic
Author

casting

Lori Zink
Greenhorn

Joined: Aug 01, 2001
Posts: 1
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

Joined: Jul 18, 2001
Posts: 30
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

Joined: Jun 25, 2001
Posts: 50
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

Joined: Jul 23, 2001
Posts: 49
BTW,
++,-- have implicit casts too,
Alex
Guoqiao Sun
Ranch Hand

Joined: Jul 18, 2001
Posts: 317
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


Guoqiao Sun<br />SCJP2 SCWCD2<br />Creator of <a href="http://www.jiris.com/" target="_blank" rel="nofollow">www.jiris.com</a>, Java resource, mock exam, forum
Mini Pilla
Ranch Hand

Joined: Jul 15, 2001
Posts: 112
I don' think ++,-- have implicit cast.
Thanx
Rajani
Originally posted by Alex Sbityakov:
BTW,
++,-- have implicit casts too,
Alex

 
wood burning stoves
 
subject: casting
 
Similar Threads
Need Help With This java Problem(Review for a test)
Strings
Assignments
A question about creating an anonymous inner class
Jxam Question