TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Java Cast and Convert Types

These Java examples 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.

Based on:

Java 8

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.

Int

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

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

Casting is complex. It is often language-specific, so we must memorize its syntax. Conversions require more steps. They are often reused in many projects and stored in utility classes.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf