should bei = f1; //will not compile
? (What's f1? Although that could be the basis of why it won't compile, but I don't think that was the intent here?)i = 1f; //will not compile
Moderator: admin
should bei = f1; //will not compile
? (What's f1? Although that could be the basis of why it won't compile, but I don't think that was the intent here?)i = 1f; //will not compile
Code: Select all
int i1 = Integer.MAX_VALUE;
System.out.println(Integer.toHexString(i1));
int i2 = Integer.MAX_VALUE-1;
System.out.println(Integer.toHexString(i2));
float f1 = i1;
System.out.println(Float.toHexString(f1));
float f2 = i2;
System.out.println(Float.toHexString(f2));
Code: Select all
7fffffff
7ffffffe
0x1.0p31
0x1.0p31
JLS contains the following statement in section 5.1.2 regarding this:"The reverse, however, is a different story. Although float and double also do lose information when you assign an int or a long to them respectively, Java allows such assignments without a cast nonetheless. In other words, Java allows implicit widening of int and long to float and double
respectively.
So, the actual reason why Java allows this assignment without a cast even though there is a loss of information is not really very clear. It is just how Java designers decided it to work.A widening primitive conversion from int to float , or from long to float , or from long to double , may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).
long g = 922337203685477580; //Long.MAX_VALUE;
So, the concepts discussed in the “Working with Inheritance - II” chapter will be applicable to explicit casting for Float to Integer wrapper classes (because they are reference types). Based on the concepts discussed here, you cannot assign an Integer object to a Float variable.In all of the cases listed above, I showed you how to assign a value of one type to a variable of the same type, i.e., an int value to an int variable or a Student object to a Student variable. But it is possible to assign a value of one type to a variable of another as well. This topic is too broad to be
covered fully in this chapter because the rules of such assignments touch upon multiple concepts. I will cover them as and when appropriate. Let me list them here first:
1. ....
2. ....
3. Assignments involving reference types - This expands the scope of casting to reference types. I will discuss this in the “Working with Inheritance - II” chapter.
Users browsing this forum: Google [Bot] and 40 guests