Free CoreJava Programs Source codes | Examples | Video Tutorials Download

Wednesday, January 21, 2009

Program For Type Casting

/**

* Write a program for type cast following int -> double double -> float float ->

* double String -> int double -> int float -> int

*

*

*/

public class TypeCasting {

/**

* typecasting with Exception handling

*/

public static void doTypeCasting() {

try {

int intNo = 11;

double dblNo = 1.1d;

float flNo = 2.2f;

String strNo = "11";

// int -> double

dblNo = intNo;

System.out.println("int : " + intNo + " to double :" + dblNo);

// double to float

dblNo = 1.1d;

flNo = (float) dblNo;

System.out.println("double : " + dblNo + " to float : " + flNo);

// float to double

flNo = 2.2f;

dblNo = flNo;

System.out.println("float : " + flNo + " to double : " + dblNo);

// string -> int

strNo = "11";

intNo = Integer.parseInt(strNo);

System.out.println("String : " + strNo + " to int : " + intNo);

// float to int

flNo = 1.9f;

intNo = (int) flNo;

System.out.println("float : " + flNo + " to int : " + intNo);

// double to int

dblNo = 1.9;

intNo = (int) dblNo;

System.out.println("double : " + dblNo + " to int : " + intNo);

} catch (Exception e) {

System.out.println("Error Occured!!");

e.printStackTrace();

}

}

/**

* execution begin from here

*

* @param args

* commandline arguments

*/

public static void main(String[] args) {

doTypeCasting();

}

}

No comments:

Post a Comment

Followers