Data type conversion in java

Above screenshot gives you size of each data type in java, which will give us an idea of compatibility of data type conversion and the result if you forcefully convert one to another type.

String to int

int to double

Output : 10.0

double to int

Output : 13

long to int

Output : 2147483647

here the value of long variable is with in the range of int, that’s why no loss in data while conversion, but if we keep long value more than int range, there will be data loss, let’s take a look at it –

Output : -877

same is with byte and short data type while converting long to byte or short type.

Other datatype to String

valueOf(<datatype> <variable>) method allows us to convert any datatype like int, char, long, Object etc to String

[as shown in the above screenshot]

output : 980

Another method is to use toString(<primitive dataType> <variable>), example as follows

output : 100

toString() method basically uses respective Object types (Integer, Byte, Long etc) to convert primitive types(int, byte, long etc) to string.

Content posted is based on learning or working experience, please leave comments if anything needs to be added or updated, discuss your queries on our facebook:qavalidation.com, Thanks!

Leave a Reply

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

%d bloggers like this: