Do you confident about primitive types and arithmetic operators in Java?
Do you confident about primitive types and arithmetic operators in Java? (+, -, *, /, %, ++, --)
Let's go through some examples!
Example 1: What do you think about the following code? (True or false)
short s1 = 10;
short s2 = 11;
short s3 = s1 + s2;
The answer is false. There will be a compilation error on line 3. Types as "byte", "short", and "char" are automatically promoted to "int" when used in expressions. So, the result of the "s1 + s2" expression is of type "int".
To resolve this, you have two options:
Change the type of s3 from "short" to "int":
int s3 = s1 + s2;
Cast the result to "short" before assigning to s3:
short s3 = (short) (s1 + s2);
Example 2: What do you think about this statement? (True or false)
float a = 123.456;
The answer is false. This will result in a compilation error because in Java, a floating-point number like "123.456" is considered a "double" type by default.
To fix this, either add the 'f' suffix or change the variable type:
// Using the 'f' suffix
float a = 123.456f;
// Alternatively, change the type to double
double a = 123.456;
Example 3: How about this statement? (True or false)
double d1 = 12.5;
float f1 = 12.5f;
float result = (float) (d1 + f1);
This will result in a compilation error on line 3. When performing arithmetic operations, Java automatically promotes types to the larger one. You have three solutions:
Cast d1 to "float" before addition:
float result = (float) d1 + f1;
Cast the result to "float" after addition:
float result = (float) (d1 + f1);
Change the result type to "double":
double result = d1 + f1; // Recommended
Note: For "long" type, use 'l' or 'L' suffix to specify the value.
Example 4: What is the result of this statement?
short s = (short) 1921222;
System.out.println(s);
The result printed is 20678 = 1921222 % (2^16/2).
Example 5: What is the result of this statement?
System.out.println((2147483647 + 1));
// Note: 2^32/2-1 = 2147483647
The printed result is "-2147483648". When values exceed the range of "int", they wrap around.
Example 6 (last): What are the results of the following code?
// 1.
long x = 10;
int y = 5;
y = (int) (x * y);
// 2.
long x = 10;
int y = 5;
y *= x;
The first statement results in a compilation error on line 3. To fix it, cast the result explicitly.
The second statement works fine because of implicit type casting
All Rights Reserved