Skip to content

Instantly share code, notes, and snippets.

@jainmickey
Created September 18, 2012 15:25
Show Gist options
  • Save jainmickey/3743744 to your computer and use it in GitHub Desktop.
Save jainmickey/3743744 to your computer and use it in GitHub Desktop.
A simple program on how to do type cast in Java.
/* 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