Sunday, 26 May 2013

Casting


class Casting{public static void main( String args[] )
{int anInt = 5;float aFloat = 5.8f;aFloat = anInt; // Implicit casts up are okanInt = aFloat ; // Compile error,
// must explicitly cast downanInt = (int) aFloat ;float error = 5.8; // Compile error, 5.8 is doublefloat works = ( float) 5.8;char c = (char) aFloat;double aDouble = 12D;double bDouble = anInt + aDouble; // anInt is cast upto double,int noWay = 5 / 0; // Compile error, compiler detects
// zero divideint zero = 0;int trouble = 5 / zero; //Some compilers may give error hereint notZeroYet;notZeroYet = 0;
 trouble = 5 / notZeroYet ; // No compile error!}}
Ints and Booleans are Different
class UseBoolean {public static void main( String args[] )
{if ( ( 5 > 4 ) == true )System.out.println( "Java's explicit compare " );if ( 5 > 4 )System.out.println( "Java's implicit compare " );if ( ( 5 > 4 ) != 0 ) // Compile errorSystem.out.println( "C way does not work" );boolean cantCastFromIntToBoolean = (boolean) 0;
// compile errorint  x  =  10;int  y  =  5;if ( x = y ) // Compile error

System.out.println( "This does not work in Java " );}} 

No comments:

Post a Comment