Saturday 7 December 2013

Typecasting in Java

Typecasting is a technique in which we change one type of data to another type to suit our needs. Let's say we have a double and we wish to convert it to integer. Or maybe we have a long that needs to be converted to byte.

Before we start converting one datatype to another, lets read up about available datatypes in java: http://mycodedock.blogspot.in/2013/11/data-types-in-java.html

In-fact, lets establish a few thumb-rules-

  • whenever converting smaller-bit datatypes to larger-bit datatypes we use Implicit Casting.
  • whenever converting larger-bit datatypes to smaller-bit datatypes we use Explicit Casting.
  • boolean datatype cannot be converted to any other datatype
  • conversion from string type to any other datatype needs the string to be parsed

  • conversion of any datatype (except boolean) to string needs to be done by passing value

Now you know all datatype conversion techniques that are used in java. Though, you might want to brush your skills up by some practice.


| Advertisement |

Saturday 30 November 2013

Data-types in Java

Lets have a look at primitive datatypes in Java with their sizes and ranges.

S. No.Data-typeSizeRange
1byte8-bit-128 to 127
2short16-bit-32,768 to 32,767
3integer32-bit-2147483648 to 2147483647
4long64-bit-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
5float32-bit- Floating point integer -
6double64-bit- Floating point integer -
Apart from these primitive data types, java.lang.String provides a data-type String.

Now lets look at the examples to learn how to use these in our programs. We'll be initializing these data-types and printing them to see how they look like...




Each data-type has its benefits and limitations. A good programmer exploits the benefits and avoids the limitation. Let us take the following case...

Assume we have a huge array of 10000000000 indices. And the value that we wish to store against each index is between 0 to 5. (Like in case of movie ratings!). So here, instead of using integer we can use byte to save space because we are certain that the value will never be greater than 5.

But at times we might tend to go over-board with this and encounter errors in our programs! Like if we wish to store radius of curvature of a rocket in flight, we would want to use a data-type that can hold huge and precise values rather than something like byte or short!

So its all about striking a good balance :)
| Advertisement |