Click on the blue words in the upper left corner and follow “Big Guy outside the pot”
Focus on sharing the latest foreign technology content
1. An overview of the
In this quick tutorial, we’ll discuss the concept of lossy transformations in Java and the reasons behind them.
In the meantime, we’ll explore some convenient transformation techniques to avoid this error.
2. Lossy conversion
Lossy transformation is the loss of information while processing data.
In Java, this corresponds to the possibility of losing variable values or precision when converting from one type to another.
When we try to convert a variable of a high-level type to a low-level type, Java will generate an incorrect, incompatible type when compiling the code: a potentially lossy conversion.
For example, let’s try assigning a long value to an int value:
long longNum = 10;
int intNum = longNum;
When compiling this code, Java produces an error:
incompatible types: possible lossy conversion from long to int
Here, Java will find that long and int are incompatible and cause lossy conversion errors. Because you can have long values outside of the int range of -2,147,483,648 to 2,147,483,647.
Similarly, we try to assign a long to a float:
float floatNum = 10.12f;
long longNum = floatNum;
incompatible types: possible lossy conversion from float to long
Because floats can represent small values that don’t have a corresponding long type. Therefore, we will receive the same error.
Similarly, converting a double to an int results in the same error:
double doubleNum = 1.2;
int intNum = doubleNum;
incompatible types: possible lossy conversion from double to int
The double value may be too large or too small for an int value, and the small value will be lost in the conversion. Therefore, this is a potentially lossy transformation.
In addition, we may encounter this error when performing a simple calculation:
int fahrenheit = 100;
int celcius = (fahrenheit - 32) * 5.0/9.0;
When a double is multiplied by an int, the result is a double. Therefore, it is also a potentially lossy transformation.
Therefore, incompatible types in lossy conversions can have different sizes or types (integer or decimal).
3. Basic data types
In Java, there are many basic data types and their corresponding wrapper classes.
Next, let’s make a list of all possible lossy transformations in Java:
short to byte or charchar to byte or shortint to byte, short or charlong to byte, short, char or intfloat to byte, short, char, int or longdouble to byte, short, char, int, long or float
Note that although short and CHAR have the same range. However, the conversion from short to char is lossy because char is an unsigned data type.
4. Transform technology
4.1. Conversion between two basic data types
The simple way to avoid lossy conversions for primitive types is by casting down; In other words, cast a high-level type to a low-level type. For this reason, it is also called a narrowing primitive conversion.
For example, let’s convert long to short using a downward cast:
long longNum = 24;
short shortNum = (short) longNum;
assertEquals(24, shortNum);
Similarly, convert a double to an int:
double doubleNum = 15.6;
int integerNum = (int) doubleNum;
assertEquals(15, integerNum);
However, we should note that casting down a high-level type with a value too large or too small to a low-level type can result in unexpected values.
We convert a long value to a value outside the range of the short type:
long largeLongNum = 32768;
short minShortNum = (short) largeLongNum;
assertEquals(-32768, minShortNum);
long smallLongNum = -32769;
short maxShortNum = (short) smallLongNum;
assertEquals(32767, maxShortNum);
If we look closely at the transformations, we see that these are not the expected values.
In other words, when Java is converting from a high-level type to a low-level type, when the maximum value of the low-level type is reached, the next value is the minimum value of the low-level type, and vice versa.
Let’s look at an example to understand this. When largeLongNum with a value of 32768 is converted to short, the value of shortNum1 is -32768. Since the maximum value of short is 32767, Java will select the next minimum value of short.
Similarly, when smallLongNum is converted to short. ShortNum2 has a value of 32767, which Java USES as the next maximum for Short.
Also, let’s look at what happens when we convert the maximum and minimum values of long to ints:
long maxLong = Long.MAX_VALUE;
int minInt = (int) maxLong;
assertEquals(-1, minInt);
long minLong = Long.MIN_VALUE;
int maxInt = (int) minLong;
assertEquals(0, maxInt);
4.2. Convert between wrapper objects and primitive types
To convert the wrapper object directly to the base type, we can use various methods in the wrapper class, such as intValue()
, shortValue()
, and longValue()
. This is called unpacking.
For example, let’s convert a Float object to a long:
Float floatNum = 17.564f;
long longNum = floatNum.longValue();
assertEquals(17, longNum);
In addition, if we look at the implementation of longValue or similar methods, we will find the use of narrowing the original transformation:
public long longValue() {
return (long) value;
}
However, sometimes you should avoid narrowing the original transformation to preserve valuable information:
Double doubleNum = 15.9999;
long longNum = doubleNum.longValue();
assertEquals(15, longNum);
After conversion, the value of longNum is 15. However, doubleNum is 15.9999, very close to 16.
Instead, we can use math. round()
to convert to the nearest integer:
Double doubleNum = 15.9999;
long longNum = Math.round(doubleNum);
assertEquals(16, longNum);
4.3. Convert between wrapper objects
To do this, let’s use the transformation techniques we’ve already discussed.
First, we will convert the wrapper object to a base value, cast it down and convert it to another wrapper object. In other words, we will perform unboxing, downcast, and boxing techniques.
For example, let’s convert a Double object to an Integer object:
Double doubleNum = 10.3;
double dbl = doubleNum.doubleValue(); // unboxing
int intgr = (int) dbl; // downcasting
Integer intNum = Integer.valueOf(intgr);
assertEquals(Integer.valueOf(10), intNum);
Finally, we use intet.valueof ()
to convert the basic type int to an Integer object. This type of conversion is called boxing.
5. To summarize
In this article, we explored the concept of lossy transformations in Java through examples. In addition, we have written a handy list of all possible lossy transformations in Java.
Along the way, we’ve determined that narrowing the original transform is an easy way to transform the base type and avoid lossy conversion errors.
At the same time, we explored other convenient techniques for numeric conversion in Java.
The code implementation for this article can be found on the GitHub project.
From spring for All community Translation group
Recently, I have translated the articles into PDF.
Reply in the background of official account: 002 can get oh ~
The content of PDF will be updated continuously in the future, please look forward to it!
● Top 10 mistakes you make using the Spring Framework
● Why Spring as the Java framework?
●Solr full-text search
Top right button to share with more people ~
Here we are. Click and watch before you go
Read More:
- Local date time conversion in java8
- The conversion between [Python] bytes and hex strings.
- Conversion from hexadecimal to decimal
- No matching editors or conversion strategy found
- Conversion of audio file format with ffmpeg command
- ‘Conversion failed when converting date and/or time from character string.DB-Lib error message 241,
- Mutual conversion between date and localdatetime
- Solution: Spring no matching editors or conversion strategy found
- Error report of covertotraditional conversion from simplified to traditional
- Conversion between list and string array
- Python conversion hex to string, high and low data processing
- Conversion to dalvik format failed with error 1 solution
- matlab Conversion to cell from char is not possible.
- Error lnk1123: failure during conversion to coff: problem solving
- Link: fatal error lnk1123: failure during conversion to coff: file in
- Mybatis uses step-by-step lazy loading to cause abnormal JSON conversion. The interface 500 reports an error
- Error: failed to find conversion function from unknown to text
- LinkIssue: Error ‘LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or cor
- “Pandoc document conversion failed with error 1033” error message appears in rstudio knit
- rmd to pdf error: pandoc document conversion failed with error 43