Saturday, December 16, 2017

Data Types in Java

Data Types: In java every variable and every expression has some types.Each and every data type is clearly defined.
Every assignment should be checked by compiler for typed compatibility. Because of above reasons we can conclude java language is strongly typed programming language.

Java is not considered as pure object oriented language because several features are not satisfied by java (like operator overloading and multiple inheritance etc.).
Moreover we are depending on premitive data types which are non objects.



Except boolean and char, remaining data types are considered as signed data types because we can represent both positive and negative numbers.

byte:

size: 1 byte (8 byte)

MAX_VALUE= +127
MIN_VALUE= -128
Range = -128 to +127



short:This is the most rarely used datatype in java.
size: 2 bytes (16 bits)
Range: -32768 to 32767

short datatype is best suitable for 16 bit processor like 8085.but these processor are completely outdated and hence corresponding datatype also outdated datatype.


int: The most commonly use in java is int.

size: 4 byte (32 byte)
Range: -2147483648 to 2147483647


long: Sometimes int may not enough to hold big values then we should go for long type.
example 1: The amount of distance travel by light in thousand days so to hold this value int may not enough, we should go for long data type.

  long l= 1,26000*60*60*24*1000 miles.

example 2:The number of character present in a big file may exceed int range hence the return type of length method is long but not int.

long l= f.length();

size= 8 bytes (64 bits)
Range: -2^63 to 2^63-1



Note: All the above datatypes (byte,short,int,long) representing integral value. If we want to represent  floating point values then we should go for floating point data types.


Floating point datatypes:

float: If we want 5 to 6 decimal places of accuracy then we should go for float.

1. Accuracy is 5 to 6 decimal point number.
2. Single precision
3. size: 4 bytes.
4. Range: -3.4e38 to 3.4e38


double:If we want 14 to 15 decimal places of accuracy then we should go for double.
1. Accuracy is 14 to 15 decimal point number.
2. double precision
3. size: 8 bytes.
4. Range: -1.7e308 to 1.7e308



boolean:
size: not applicable
Range: not applicable(but allowed values are true/false)

char: Old languages (like C/C++ ) are ASCII code based and the number of different ASCII code character are <=256. To represent these 256 characters 8 bits are enough. Hence the size of in old language is 1 byte.

But Java is unicode based and the number of different unicode characters are >256 and <=65536. To represent these many characters 8 bit may not enough so we should go for
16 bit. Hence the size of char in java is 2 bytes.

size: 2 bytes
Range: 0 to 65535



No comments:

Post a Comment