Primitive data types
These are the basic building block data types in Java
They are boolean, byte, char, short, int, long, float, double
Java Primitive Data types and their limits
If you try to put a value greater than the maximum value for a data type, it will result in an Overflow
If you try to put a value lesser than the minimum value for a data type, it will result in an Underflow
Int
package com.hello.pkg;
public class BasicDataTypes {
public static void main(String[] args) {
int intMinValue = Integer.MIN_VALUE;
int intMaxValue = Integer.MAX_VALUE;
System.out.println("Min: " + intMinValue + " , Max: " + intMaxValue);
System.out.println("Overflow: " + (intMaxValue + 1) + " , Underflow: " + (intMinValue -1));
int literalValue = 2_147_483_647;
System.out.println("Int as literal Value: " + literalValue);
byte byteMinValue = Byte.MIN_VALUE;
byte byteMaxValue = Byte.MAX_VALUE;
System.out.println("Byte Min: " + byteMinValue + " , Byte Max: " + byteMaxValue);
int shortMinValue = Short.MIN_VALUE;
int shortMaxValue = Short.MAX_VALUE;
System.out.println("Short Min: " + shortMinValue + " , Short Max: " + shortMaxValue);
}
}
Output
Min: -2147483648 , Max: 2147483647
Overflow: -2147483648 , Underflow: 2147483647
Int as literal Value: 2147483647
Byte Min: -128 , Byte Max: 127
Short Min: -32768 , Short Max: 32767
Java treats Double as the default floating point number
For precise calculations like currency calculations Java recommends using BigDecimal
A float gives you approx. 6-7 decimal digits precision while a double gives you approx. 15-16. Also the range of numbers is larger for double.
A double needs 8 bytes of storage space while a float needs just 4 bytes.
This will give error:
public class MyClass {
public static void main(String args[]) {
float a = 0.5;
}
}
/MyClass.java:3: error: incompatible types: possible lossy conversion from double to float float a = 0.5;
This will work perfectly fine
public class MyClass {
public static void main(String args[]) {
double a = 0.5;
}
}
This will also work perfectly fine
public class MyClass {
public static void main(String args[]) {
float a = (float)0.5;
}
}
Reason : Java by default stores real numbers as double to ensure higher precision.
No comments:
Post a Comment