This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt regarding explicit cast and implicit cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt regarding explicit cast and implicit cast" Watch "Doubt regarding explicit cast and implicit cast" New topic
Author

Doubt regarding explicit cast and implicit cast

jyothi dandamudi
Greenhorn

Joined: May 11, 2011
Posts: 4
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 763
The "20" is an integer. So, it needs to be casted to String.
Mala Gupta
Author
Ranch Hand

Joined: Sep 27, 2002
Posts: 251
    
    9
Jyothi,

The following isn't an example of casting (explicit or implicit):



The variable out is of type PrintStream in class System. Class PrintStream defines overloaded println methods to accept and write different types of data. In the above mentioned line of code, you are not using implicit or explicit casting. You are calling overloaded println method.

The following code uses a method to convert an int value to String:



With respect,
Mala


Author of Manning's OCA Java SE 7 Programmer I Certification Guide and OCP Java SE 7 Programmer II Certification Guide
jyothi dandamudi
Greenhorn

Joined: May 11, 2011
Posts: 4


Mala when i cast it to (byte) it will work fine. So according to your explanation the PrinStream class does'nt have any overlaoded method which take byte . So we have to cast it to byte or String.

Am i understading it correctly. Please correct me if i am wrong.

Thanks,
Jyothi
Zhenyi Luo
Ranch Hand

Joined: Sep 03, 2012
Posts: 33
jyothi dandamudi wrote:

Mala when i cast it to (byte) it will work fine. So according to your explanation the PrinStream class does'nt have any overlaoded method which take byte . So we have to cast it to byte or String.

Am i understading it correctly. Please correct me if i am wrong.

Thanks,
Jyothi


From my perspective,
System.out.println(b); // does implicit casting by compiler (converting byte to int is always safe).
String byteToString = Byte.toString((byte)20); // need explicit casting by converting int to byte(not safe, because int might exceed the range of byte. It's your responsibility to make sure it's safe).
 
GeeCON Prague 2014
 
subject: Doubt regarding explicit cast and implicit cast