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

Doubt regarding explicit cast and implicit cast

 
jyothi dandamudi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Himai Minh
Ranch Hand
Posts: 1309
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "20" is an integer. So, it needs to be casted to String.
 
Mala Gupta
Author
Ranch Hand
Posts: 296
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
jyothi dandamudi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic