HomeSearch

Java Cast and Convert Types

Cast variables, including objects and numbers. Arrays too are cast.
Casts. Data is typed. Often its type is considered part of the data: it is metadata, information about itself. Casting, in converting types, thus changes data.
Casting and converting in Java is a practical operation. We use implicit (hidden) and explicit (specified) casts. Complex conversions too are needed.
Object and String. This program casts a String variable to its ancestor class Object (all classes derive from Object). It then casts the object back to a String.

Implicit: An implicit cast uses no special expression syntax. Rather it converts one type to another—the compiler decides on its own.

Explicit: This is specified directly in the syntax. The Object is explicitly cast to a String in the third statement.

Java program that uses String, Object cast public class Program { public static void main(String[] args) { String value = "cat"; Object temp = value; // Implicitly cast to Object. String value2 = (String) temp; // Cast to String. System.out.println(value2); } } Output cat
Numeric. Numbers can be cast with the same syntax as classes. For casting to a larger byte size number (a "widening" cast) no cast is required.

But: For "narrowing" casts, where a larger byte size number is reduced to fit in a smaller type, a cast is required.

Data loss: This may occur in a narrowing conversion. Be sure the value can be represented in the new data size.

Java program that uses numeric casts public class Program { public static void main(String[] args) { int size = 5; double size2 = size; // No cast needed. byte size3 = (byte) size; // A larger type must be cast down. System.out.println(size); System.out.println(size2); System.out.println(size3); } } Output 5 5.0 5
Invalid cast, ClassCastException. Some casts will fail. And often the compiler will detect an invalid cast at compile-time, saving us the trouble of running an invalid program.

Here: The Object cannot be cast to String, because it is of type StringBuilder. A ClassCastException occurs.

Java program that uses invalid cast public class Program { public static void main(String[] args) { StringBuilder builder = new StringBuilder(); builder.append("cat"); Object temp = builder; // This is fine. String value = (String) temp; // This causes an error. System.out.println(value); } } Output Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuilder cannot be cast to java.lang.String at program.Program.main(Program.java:10)
Array covariance. This concept means an array of a derived class can be cast to an ancestor class array. So an array of Strings can be cast to an array of Objects.Object Arrays

Tip: Array covariance is most often useful when we want to pass an array of any type as an Object array to a commonly-used method.

And: In most programs, array covariance is not important. Using exact types is clearer and faster.

Java program that uses Object array public class Program { public static void main(String[] args) { String[] values = { "cat", "dog", "rabbit" }; // A String array is also an Object array. Object[] array = values; // Loop over objects and print String lengths. for (Object v : array) { System.out.println(((String) v).length()); } } } Output 3 3 6
Casts versus conversions. Typically casts describe special syntax instructions to convert types. Conversions meanwhile include more complex operations, like converting a String to an array.
Number to String. A number cannot be cast to a String—instead we must convert it with a method like Integer.toString. This method returns a String version of the int argument.
Java program that converts number to String public class Program { public static void main(String[] args) { int number = 100; String result = Integer.toString(number); // Number to String. System.out.println(result); } } Output 100
String to number. We convert a String to an integer by parsing it. The Integer.parseInt method can do this. It receives a String argument and returns an int.Strings
Java program that converts String to number public class Program { public static void main(String[] args) { String value = "100"; int result = Integer.parseInt(value); // String to number. System.out.println(result); } } Output 100
Long to int. Suppose we have a long value and wish to have an int. We can cast the long to an int directly with a cast expression. This works if the int can store the long's value.

However: If the long is out of range and cannot be represented by an int, we will have an incorrect value in the int.

Java program that casts long to int public class Program { public static void main(String[] args) { // Cast long to int directly. long test = 200; int result = (int) test; System.out.println("INT: " + result); } } Output INT: 200
Long to int, exact. With Math.toIntExact, we can safely convert a long to an int. This may cause an exception if the value cannot be stored in the int, so we must have a try and catch.Math
Java program that converts long to int import java.lang.Math; public class Program { public static void main(String[] args) { try { // Use Math.toIntExact to convert long to int. long test = 200; int result = Math.toIntExact(test); System.out.println("INT: " + result); } catch (ArithmeticException ex) { System.out.println("ERROR: " + ex); } } } Output INT: 200
Boolean to int. Sometimes we want to convert a boolean into an int. Typically we want true to equal 1, and false to be 0. This is done with a simple method and a ternary expression.Convert boolean to int
Float. We can cast doubles to floats, but we must specify this with a cast expression. Some conversions to float, like from int, can be done without any special syntax.Float
Casting is complex. It is often language-specific. Conversions require more steps. They are often reused in many projects and stored in utility classes.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls