Thursday, December 07, 2006

Downcasting vs Upcasting in Java

CharSequence l_sq0 = new String( "HelloWorld 0" );
System.out.println( "CharSequence: " + l_sq0.toString() );
// Downcasting CharSequence to String
String l_tstr2 = (String)l_sq0;
byte[] l_bytes = l_tstr2.getBytes();
System.out.println( "String: " + l_tstr2.toString() +
                " Length: " + l_bytes.length );
        
String l_tstr = new String( "Hello World 1" );
// Upcasting String to CharSequence
CharSequence l_sq = (CharSequence)l_tstr;
System.out.println( "String: " + l_tstr.toString() );
System.out.println( "CharSequence: " + l_sq.toString() );
 
In the above example, String which implemented CharSquence in java.lang has been upcasted and downcasted at two different places. So, that is allowed.


Need a quick answer? Get one in minutes from people who know. Ask your question on Yahoo! Answers.

4 Comments:

Blogger prethesh said...

This comment has been removed by the author.

6:01 AM  
Blogger prethesh said...

so do you mean java support downcasting by default and we have to do explict upcasting. is it correct?

6:03 AM  
Anonymous Anonymous said...

This comment has been removed by the author.

12:52 AM  
Anonymous Anonymous said...

Great explanation! I also thought this explanation of downcasting was helpful as well:

http://www.programmerinterview.com/index.php/java-questions/downcasting-in-java/

12:52 AM  

Post a Comment

<< Home