Java is a statically typed language. That means all variables should be declared of their type before they can be used. For example
String s = "qwerty"; int age = 18; char c = 'a';
The advantage of doing this is we can identify type mismatch issues during the compile time itself.
There are 8 primitive data types in Java.
|Primitive Data Types||size||default value||min value||max value|
|float||32 bit(IEEE 754 |
|double||64 bit(IEEE 754 floating point)||0.0d|
|boolean||1 bit (not precisely defined)||false||false||true|
|char||16 bit||‘u\0000’||‘\u0000’ (or 0)||‘\uffff’ (or 65,535)|
In addition to the above 8 primitive data types java has non-primitive data types like String, Class, Array , Interface etc.
Can we use underscore characters in numeric literals ?
Yes. To increase readability we can use underscore to group numbers in numeric literals. This is available from Java 7 and above. However, note that we cannot use underscore at the end or beginning of numbers and before or after decimal points. Those are invalid.
//All are valid. long years = 1_100_000_000L; long ssn = 123_12_1234l; float pi = 3.14_159f; //All below are invalid long years = _1_100_000_000L; long ssn = 123_12_1234_l; float pi = 3._14_159f;
Can we use float or double for Currency / money calculations ?
Don’t use float or double primitive types for currency or monetary calculations. As they are based on IEEE 754 floating point we will get unexpected results. For example consider the code below. We expect that the result should be 3.09. But it is 3.090002
float num1 = 6.09f; float num2 = 3.0f; System.out.println(num1-num2); //Returns 3.0900002
To get precise values use java.math.BigDecimal for currency or monetary calculations.
BigDecimal amount = BigDecimal.valueOf(6.09); BigDecimal amount2 = BigDecimal.valueOf(3.0); System.out.println(amount.subtract(amount2)); //Returns 3.09 as expected.