Java Tutorial
//Compatible types Example byte a = 50; int b; //automatic conversion happens here if data of byte type is assinged to int variable. // int variable is always large enought to hold data of byte type. b = a;
int a = 100; byte b; // .... //here data of int type is assigned to variable of byte type. byte type variable is not large enough to hold value of int type data. //Need casting here, to convert int data to be assigned in byte variable. b = (byte) a;Type Casting in java:
// Type conversion in java class TypeConversionTest { public static void main(String args[]) { byte a; int b = 310; double c = 500.14; // Conversion of int to byte. a = (byte) b; System.out.println("a and b: " + a + " " + b); // Conversion of double to int. b = (int) c; System.out.println("b and c: " + b + " " + c); //Conversion of double to byte. a = (byte) c; System.out.println("a and c: " + a + " " + c); } }Output:
a and b: 54 310 b and c: 500 500.14 a and c: -12 500.14
int num = Integer.parseInt("302");Integer.parseInt method is used to convert string into integer value.
]$ java ArithmeticTest Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:592) at java.lang.Integer.parseInt(Integer.java:615) at ArithmeticTest.main(ArithmeticTest.java:5)
string str = Integer.toString(302);Integer.toString method is used to convert integer into string.
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page