Created
September 18, 2012 15:25
-
-
Save jainmickey/3743744 to your computer and use it in GitHub Desktop.
A simple program on how to do type cast in Java.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Example of using type cast in java */ | |
class TypeCast{ | |
public static void main(String args[]){ | |
int myInt = 123; | |
double myDouble = 123.0; | |
String myStr = "123"; | |
String txtStr = "Hello, World!"; | |
/* It doesn't give actual value because result will be integer and it doesn't include decimal numbers */ | |
System.out.println("myInt/5 gives :- " + (myInt / 5)); | |
// Its modulus gives remainder as result | |
System.out.println("myInt%5 gives :- " + (myInt % 5)); | |
/* It gives actual answer because double is decimal type and result is double */ | |
System.out.println("myDouble/5 gives :- " + (myDouble / 5)); | |
// Another type-cast by forcing double math | |
System.out.println("myInt/5.0 gives :- " + (myInt / 5.0)); | |
// Attemp to convert string to int but it gives error | |
//System.out.println("myStr to int :- " + (int)myStr); | |
/* java has a Integer class which has a method parseInt it to convert string to integer */ | |
System.out.println("Converting string to int :- " + Integer.parseInt(myStr)); | |
// converting a text string to int gives runtime error | |
//System.out.println("Converting text string to int :- " + Integer.parseInt(txtStr)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment