How to do Type Casting in Java

Type Casting in Java

In this tutorial, You will learn about some basic functions of type casting in Java. To understand type casting you must know about the wrapper classes in Java.

Wrapper Classes in Java:

In Java, some classes Objectify the primitive data types, i.e. for each data type there is a corresponding data type like for int there is Integer class.
This class is based on a design pattern named as Wrapper Pattern. These classes are used to convert incompatible data types. As well as many other useful functions can be performed.

wrapper classes of java
wrapper classes of java

In Java, there are many built-in functions which are used to converts values from one type to another.
Using Wrapper classes we can be covert int to string or string to int like:

Integer to String:

Integer in Wrapper Classes
Integer in Wrapper Classes

 

Convert Char to Int:

But it requires only decimal no is character value.

String to Char Array:

String wrapper class for type casting
String wrapper class for type casting

Convert Double to Int:

Convert long to int:

If the value is too big in Java, we use the big integer to save them.

Convert String to BigInteger:

It’s simple because big integer object take a string in its constructor and if we have value in int then convert it into a string and pass it to a big-integer constructor.

Convert Int to Int Array:

By default, there is no such a function or method which convert int value to int array I mean if we have an integer like

and we want to convert it into int array like

Then we have to write our code. First convert int to a string then put that string in an array.

Hope you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!

Leave a Reply

Your email address will not be published. Required fields are marked *