Skip to main content

Casting and Conversation In JAVA

 

Lest's Start JAVA Programming

Part 7

Casting

Casting the way of converting data from one data type to another data type. for an Example:- assign int variable to double variable.

Casting can happen in different ways. Here we are take a look at the 2 main ways casting can happen.
  • Implicit casting
  • Explicit casting
Read about other types of casting documentation

Implicit Casting

Implicit casting happens automatically when converting data from small data type to large data type. like int convert to double .Implicit casting to work target data type must be the large size data type. for example, converting 8 bit data type will to 16 bit data type. 


Let's take a look at some code examples.
Example 01

Example 02

Example 03

Explicit Casting

This happen when convert large data types to small data types and also this is not happening automatically, this need to do manually in our code using "()" operator.

If we didn't do it, compiler will return compile-time error.

Also most important thing is. When we convert large data type to small data type we may lost some data, we may not get the same value from both variables.

Reason is, if we convert 16 bit data type value to 8 bit data type value. 8 bit data type can only contain 8 bit but there are 16 bit in the value we trying to convert so the extra bits will be removed in order to convert 16 bit to 8 bit data type.


Let's take a look at some code examples.
Example 01

Example 02

Example 03

Wrapper Classes

To convert primitive data type to object we need wrapper classes. With wrapper classes we can convert string value like "1234" to int value and vice versa.

Ways to use wrapper classes for converting data types.

Using ".parse" method.

All the numeric data types (Short, Long, Integer, Double) have ".parse" method in their wrapper class. We can use this to convert string to numeric data type.

Using wrapper class constructor.


Using "valueOf()" method.

All most every wrapper class types have "valueOf()" method in them. We can use that to convert data types.

There are other methods that wrapper classes offer to use in data conversion. Each wrapper class have methods that identical for them and methods that every wrapper class have.  
  • toString()
  • format()
  • etc...

Comments

Popular Posts

What is a Computer Program ?

Let's Start JAVA Programming - [Part 01]

Lest's Start JAVA Programming - [Part 04]