Data types in java (JNNC Technologies)


Data types in java  refer to type of data that can be stored in variable. As Java is strongly typed language, you need to define datatype of variable to use it and you can not assign incompatible datatype otherwise the compiler will give you an error.
The compiler will give you an error with this message – “Type mismatch: cannot convert from String to int”.
There are two types of data types in java.
  • Primitive data types
  • Referenced data types.

Primitive data types:

Primitive data types are those datatypes which are defined by java language itself.
There are 8 primitive data types in java.
Data TypeDefault ValueDefault size
booleanfalse1 bit
char‘\u0000’2 byte
byte01 byte
short02 byte
int04 byte
long0L8 byte
float0.0f4 byte
double0.0d8 byte
Let’s see some example about data types:

Adding two integers:

When you run above program, you will get below output:
30

Assigning int to double(Widening):

Here we will assign int to double. As double takes more memory than int. This is widening operation.
When you run above program, you will get below output:
30
30.0

Assigning double to int(Narrowing or typecasting):

Here we will assign double to int. As double takes more memory than int. This is Narrowing operation.
When you run above program, you will get below output:
30.0
30

Assinging int to byte(Overflow condition):

When you assing int to byte and value of int is larger than size of byte then it is a case of overflow.
When you run above program, you will get below output:
200
-56

Reference data types:

Reference data types are those data types which are provided as class by Java API or by class that you create.
String is example of Reference data types provided by java.
That’s all about data types in java.

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();