Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Working with byte variables

 
Sibendu Dey
Greenhorn
Posts: 20
Java Oracle Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone,

Can anyone help me with the following codes?



In the above code , can anyone tell me why 'cc' variable initialization fails to compile but compiler is ok with 'dd' variable initialization ?

Thank you
 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First:
if you try this

because it will be promoted to int (all + - * / % - promoted to int if one operand smaller or equal int)
if one is long - promoted to long
if one is float - promoted to float
if one is double - promoted to double

if you use float + float it not promoted to double:


but if you use compound assignment


and if you use constant or constant expression (int or smaller) you will get

result is narrowing ok (but rusult must fit into type of variable)

some more


and you can use widening: from byte to short to int to long to float to double
and: from char to int to long to float to double
but you can`t byte to char and short to char because byte and short may be : -10 for example, and char is unsigned

and one more narrowing can be used in return from method

but when you invoke this method narrowing can`t be used:


method choose in invocation:
1. One to one (byte to byte) if there is no:
2. Widening: byte to short to int ... if no:
3. Boxing: byte to Byte if no
3. to Number if no:
4. to Object if no:
5. var args method.

and if you pass null method that accept object is chosen (most specific)
if there is equal most specific method - compiler error because ambiguous.

and some words about Wrapers:

in this case when you invoke meth (Byte b), bb and b - refer to same object,
but when you asign b = 100; at //3 you create new object and assign it to variable b, at this point b and bb refer to different object. to understand this you may want read this

about constant expressions from jls: 15.28. Constant Expressions
about assigment jls: 5.2. Assignment Conversion
 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and one more about wrappers.
Byte b =10;
meth(b);

first:
1 to 1 chosen (void meth(Byte){}) of no
not used method with parameter other wraper.
to Number if no
to Object if no
unboxing to byte if no
widening:
to short
to int
to long
to float
to double
after unboxing never boxing
last - var args
may be some thing i forgotten when i prepare i see table about casting wrapers to primitive and primitive to wrapers, sorry don`t remember in which source.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One important rule to remember: the result of integer operations is always an int. So adding two bytes will not result in a byte, but in an int. And an int doesn't fit in a byte, so you'll get the compiler error (variable cc). If you use literals or compile time constants (using final), the value is known at compile time. And the compiler is one smart cookie: so if the value fits in the byte (or other primitive data type) all is fine, no compiler errors (variable dd). But if the value doesn't fit in the byte (or other primitive data type), you'll get a compiler error

Some examples:





Now it's time for a little pop quiz. Does the following code compiles or not?


Hope it helps!
Kind regards,
Roel
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent post, I am able to get everything explained in this post prior to these statements. Sorry for my disability for not getting the following explanation.
Sergej Smoljanov wrote:method choose in invocation:
1. One to one (byte to byte) if there is no:
2. Widening: byte to short to int ... if no:
3. Boxing: byte to Byte if no
3. to Number if no:
4. to Object if no:
5. var args method.

Can you(or anybody) please explain me what exactly these statements mean? If possible with bit of java code please.

and if you pass null method that accept object is chosen (most specific)
if there is equal most specific method - compiler error because ambiguous.


What does this mean?


Note: Text content in the code blocks is automatically word-wrapped



I take in line 2 you mean invocation of method meth(bb), instead of void meth(Byte bb) is that right?

in this case when you invoke meth (Byte b), bb and b - refer to same object,
but when you asign b = 100; at //3 you create new object and assign it to variable b, at this point b and bb refer to different object. to understand this


Sorry for not getting this explanation as well. I do understand the content in this link though.

Finally I dint get following post either.

Sergej Smoljanov wrote:and one more about wrappers.
Byte b =10;
meth(b);

first:
1 to 1 chosen (void meth(Byte){}) of no
not used method with parameter other wraper.
to Number if no
to Object if no
unboxing to byte if no
widening:
to short
to int
to long
to float
to double
after unboxing never boxing
last - var args
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
Now it's time for a little pop quiz. Does the following code compiles or not?



At fist glance, I though it will compile but it will not. As byte range is -127 to 128, value 200 is not big enough to fit into byte. Am I right till here?

With Respect,
Prathima
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:
Roel De Nijs wrote:
Now it's time for a little pop quiz. Does the following code compiles or not?



At fist glance, I though it will compile but it will not. As byte range is -127 to 128, value 200 is not big enough to fit into byte. Am I right till here?

Spot-on! Although you made a little slip-up in your explanation: As byte range is -128 to 127, value 200 is too big to fit into byte

[edit] Fixed typo in byte range to avoid confusion (thanks Sharmili)
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:
Sergej Smoljanov wrote:method choose in invocation:
1. One to one (byte to byte) if there is no:
2. Widening: byte to short to int ... if no:
3. Boxing: byte to Byte if no
3. to Number if no:
4. to Object if no:
5. var args method.

Can you(or anybody) please explain me what exactly these statements mean? If possible with bit of java code please.

Determining which overloaded method will be invoked is one of the hardest things on both the OCAJP7 as the OCPJP7 exams. In this post you have 15 little examples to decide which overloaded method is invoked. Try them all out and you'll have a better understanding of the above rules... If you doubt about a few, feel free to post a reply.

Prathima gaitonde wrote:Finally I dint get following post either.
Sergej Smoljanov wrote:and one more about wrappers.
Byte b =10;
meth(b);

first:
1 to 1 chosen (void meth(Byte){}) of no
not used method with parameter other wraper.
to Number if no
to Object if no
unboxing to byte if no
widening:
to short
to int
to long
to float
to double
after unboxing never boxing
last - var args

To better understand this list, you can use the same thread with the 15 examples. But instead of using an int as parameter in the main method, you now use an Integer. So use the following main method instead and try to predict which method is invoked. Again if you have some doubt(s), feel free to post a reply.


Hope it helps!
Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:

and if you pass null method that accept object is chosen (most specific)
if there is equal most specific method - compiler error because ambiguous.


What does this mean?

It's about what happens when you invoke a method with a null value. It will become more obvious with a few small examples as well.

Let's assume the main method is always the same in every example:


Here are a few examples. All these examples will compile successfully. It's up to you to determine which method will be invoked (before confirming your answer by compiling and running the examples).





Hope it helps!
Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:I take in line 2 you mean invocation of method meth(bb), instead of void meth(Byte bb) is that right?

in this case when you invoke meth (Byte b), bb and b - refer to same object,
but when you asign b = 100; at //3 you create new object and assign it to variable b, at this point b and bb refer to different object. to understand this

That's one of the reasons why I already mentioned to always be careful to post code and always make sure the code is valid and compiles (unless you are in doubt about a compiler error ). Otherwise other ranchers might be confused or have trouble understanding.

Here is the same code snippet which compiles successfully:


So your assumption was again spot-on The explanation is similar to the link you mentioned. At line 2, b and bb refer to the same object (created at line 1 using autoboxing). But on line 3, a new Byte object is created and therefore b and bb are not referring to the same object anymore. It seems you are invoking post-increment on a Byte object, but behind the scenes (and for your convenience) the wrapper object is unboxed/unwrapped first, then incremented with 1 and finally autoboxed in another Byte object. So the behind-the-scenes code of line 3 will probably look like (or something similar):


Hope it helps!
Kind regards,
Roel
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for the reply Roel,


Roel De Nijs wrote:
Here are a few examples. All these examples will compile successfully. It's up to you to determine which method will be invoked (before confirming your answer by compiling and running the examples).


I found this example gives compile time error :method call is ambiguous. Sorry if I am wrong.

My understanding on this post, please correct me if I am wrong.

1>As long as parameters of the method, are from the same hierarchy list there is no ambiguity(compile time error).

2>Upon Invocation, That method which takes, the parameter, of type most subclass will be called. Provided, method call is such that argument fits into all the methods.
Example:


Here, out put of the program is fnfexception:null. If we uncomment the last method then, its a compile time error.

Out put of Example A is: string: null
Out put of Example b is: double: null

3> If we change the method call to call(10), then:

Out put of Example A is: object: 10
Out put of Example b is: object: 10
Example C is: Compile time error. Overloaded call is not applicable for the argument(int) .

With great respect,
Prathima
 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 to 1 chosen


then try to comment in sequence (line 4-6, after run coment 8-10 ...)meht for each primitive: and you will see widening for each call with primitive argument
when you coment line 4-26 you will see boxing for each calling with primitive argument
then comment lines from 4 to 53 and you will see to Number for each calling with wrapper or primitive argument
then comment lines from 4 to 59 and you will see to Object for each calling with wrapper or primitive argument
and only if you comment 4-62 you will still not see var args for each calling with wrapper or primitive argument because error like this:
reference to meth is ambiguous, both method meth(byte...) in Test and method meth(Byte...) in Test match

and also calling
that now has no suitable method
lets comment also (90-114 and 171-183 and 198-210) (lines that make ambiguous, and lines that has no suitable method and lines that call with array of wrappers because we comment suitable method for it as lines that make ambiguous)
 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also:

try to comment first 30-53 - you get one step up to Number
try to comment 30-58 - one more up to Object
try to comment 30-62 what you get?
try comment 30-62 and 4-6 what is result?
and if you also comment 8-10?... and one by one all method that accept primitive?
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:
Roel De Nijs wrote:

I found this example gives compile time error :method call is ambiguous. Sorry if I am wrong.

My understanding on this post, please correct me if I am wrong.

1>As long as parameters of the method, are from the same hierarchy list there is no ambiguity(compile time error).

You are spot-on! No need to be sorry

The rule is very simple: when you pass a null value to some overloaded methods, the most specific one is chosen. So if parameter types are in the same hierarchy tree (like in ExampleD), the compiler is able to determine the most specific type and the code compiles (and runs) successfully. But if parameter types are in different hierarchy trees (like in ExampleC, it's impossible to know for the compiler which type is the most specific one and that's why you get the ambiguity compiler error.

Prathima gaitonde wrote:2>Upon Invocation, That method which takes, the parameter, of type most subclass will be called. Provided, method call is such that argument fits into all the methods.
Example:


Here, out put of the program is fnfexception:null. If we uncomment the last method then, its a compile time error.

Both statements are correct! If the last method is uncommented you have 2 different hierarchy trees: the first one of IOException and the second one of RuntimeException.

Prathima gaitonde wrote:Out put of Example A is: string: null
Out put of Example b is: double: null

No mistakes here!

Prathima gaitonde wrote:3> If we change the method call to call(10), then:

Out put of Example A is: object: 10
Out put of Example b is: object: 10
Example C is: Compile time error. Overloaded call is not applicable for the argument(int) .

Bang on! Can you explain why object: 10 is printed in ExampleB and not double: 10? Why is 10 not a Double (with upper case d) as it easily fits into a double (with lower case d)? (note: I'm just playing to be confused, I know the answer, just want to check if you know it too )

And finally another little pop-quiz. What's the result of this code (which looks almost the same as ExampleC)?


Hope it helps!
Kind regards,
Roel
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roel,

Only because of the support provided by you and few other ranchers, I am very happy today to answer your post , To answer this "surprisingly", I dint have to run the program this time, just able to spot it on my won , still did make sure, such that my post should not mislead others, answer to your fist quiz(Play),

Roel De Nijs wrote:
Out put of Example A is: object: 10
Out put of Example b is: object: 10
Example C is: Compile time error. Overloaded call is not applicable for the argument(int) .
Bang on! Can you explain why object: 10 is printed in ExampleB and not double: 10? Why is 10 not a Double (with upper case d) as it easily fits into a double (with lower case d)? (note: I'm just playing to be confused, I know the answer, just want to check if you know it too )


Here, int constant gets promoted to Integer Object, which cant be fit into either String or Double, but Object can take it as, its a superclass of Integer. Now second quiz,

And finally another little pop-quiz. What's the result of this code (which looks almost the same as ExampleC)?


Answer is string:null, as method get, returns string object with value null.
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sergej Smoljanov,

Its really nice to see your post, you have great patience to explain the concept to me. With your and Roel's help I am stating my views about overloaded methods, both of you please correct me if I am wrong or need to know something else, such that it will help, even others.

Overloaded Method Call
1. Between primitive, object, varargs, the precedence rule for execution of the overloaded methods is,
primitives
objects
varargs

2. Integer constant is int (or can be promoted to Integer) by default. Similarly decimal constant is double (or can be promoted to Double) by default.

3. Constant is converted to object if and only if no matching primitive method is found.

4. If the method call is with parameter null then, the object argument should be of different hierarchy level, otherwise compile time error.

5. If the methods argument differ in hierarchy level then, method that have a argument of type lower order gets called.

6. Even in case of methods with primitive argument, that method which has the, least enough space to take the parameter is called.

with kind Regards,
Prathima
Screenshot (6).png
[Thumbnail for Screenshot (6).png]
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:Here, int constant gets promoted to Integer Object, which cant be fit into either String or Double, but Object can take it as, its a superclass of Integer.

Almost perfect! 1 little remark/nitpick about spelling There is a huge difference between "object" (lower case o) and "Object" (upper case o). In the sentence "int constant gets promoted to Integer Object", it should be "object" (lower case o).

Prathima gaitonde wrote:Answer is string:null, as method get, returns string object with value null.

Spot-on! Although the value is null, the compiler can determine it's a String (because that's the return type of the get method). And thus no compiler error in this code example.

Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:4. If the method call is with parameter null then, the object argument should be of different hierarchy level, otherwise compile time error.

5. If the methods argument differ in hierarchy level then, method that have a argument of type lower order gets called.

Not true! But maybe it's nothing more than a wording issue and you know correctly how it works as it is very hard to explain in words.

I'll give it a try! When you call an overloaded method with a null value, the method with the most specific type is executed. When the most specific type can't be determined, you'll get a compiler error. And to determine the most specific rule you can use this rule (from the JLS, slightly adapted): The informal intuition is that methodX is more specific than methodY if any invocation handled by the methodX could be passed on to methodY without a compile-time type error.


Prathima gaitonde wrote:6. Even in case of methods with primitive argument, that method which has the, least enough space to take the parameter is called.

I don't understand what you mean with this statement. Can you rephrase it or give a code example?

Hope it helps!
Kind regards,
Roel
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
Prathima gaitonde wrote:
6. Even in case of methods with primitive argument, that method which has the, least enough space to take the parameter is called.

I don't understand what you mean with this statement. Can you rephrase it or give a code example?


I mean, this for example


The out put of the code is Short, as int is assigned to byte it may be obvious that, one thinks the output of the code will be Int. Also int and short both can take byte, so this point was constructed by me to make it easy to remember.

With great respect,
Prathima
 
Henry Wong
author
Marshal
Pie
Posts: 22113
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:
Its really nice to see your post, you have great patience to explain the concept to me. With your and Roel's help I am stating my views about overloaded methods, both of you please correct me if I am wrong or need to know something else, such that it will help, even others.


While this is interesting, and works in the examples provided, isn't method overloading much more complex than that? How about dealing with methods that has more than one parameter?

Anyway, the complete, and complicated set of rules are ... In order to find and choose which overloaded method to use ...

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.1

This actually starts off pretty complex, as it has three different phases. Phase one is the simplest and requires an understanding of implicit casting. Phase two is a bit more complex, and requires an understanding of autoboxing, and of course ...

http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.3

Phase three requires an understanding of varargs, generics, etc., and is rife for confusion. Regardless, all three phases also requires an understanding of the concept of most specific method ...

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5

Hope this helps,
Henry
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:The out put of the code is Short, as int is assigned to byte it may be obvious that, one thinks the output of the code will be Int. Also int and short both can take byte, so this point was constructed by me to make it easy to remember.

I assumed you were refering to such an example. Just checking to be 100% sure

You could rephrase point 6 to (but the most important is that you understand): A primitive type will be widened to the smallest available primitive. So applied to your example: a byte will be widened to short (as short is smaller than int).

And a reply of me would not be complete if I didn't have a few pop quiz questions So here we go:
1/ can a long be widened to a float?
2/ can a byte be widened to a char?
3/ can a char be widened to a short?
4/ can a char be widened to a float?

Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:Phase three requires an understanding of varargs, generics, etc., and is rife for confusion. Regardless, all three phases also requires an understanding of the concept of most specific method ...

A little (useful) note: generics is not on the OCAJP exams, so no need to bother now. For the OCPJP exams you need to know generics and its (little) intricacies on method overloading (and which method will be invoked).
 
Sergej Smoljanov
Ranch Hand
Posts: 467
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sergej Smoljanov wrote:....
may be some thing i forgotten when i prepare i see table about casting wrapers to primitive and primitive to wrapers, sorry don`t remember in which source.

just find source:
5.5. Casting Conversion
Table 5.1. Casting conversions to primitive types
Table 5.2. Casting conversions to reference types
this two table will take more time and likely write lot of code to understand it, main purpose to see consistent pattern.
example: table 5.1
all wrapper can be unboxing to primitive (like Byte to byte) and than widening to primitive that is bigger than (primitive when unboxing) (except Byte to char, Short to char because Byte/Short can be negative and char can`t -> so you can`t cast Byte or Short to char and you cant`t cast Integer, Long, Float, Double to char).
or example 2:
Boolean can be boxing only to Object or unboxing to boolean, except Object and Boolean no one wrapper can be unboxing to boolean
also you can see ω (signifies widening primitive conversion from table) - to see where is widening between primitive
 
Prathima gaitonde
Ranch Hand
Posts: 130
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
And a reply of me would not be complete if I didn't have a few pop quiz questions So here we go:
1/ can a long be widened to a float?
2/ can a byte be widened to a char?
3/ can a char be widened to a short?
4/ can a char be widened to a float?



Hi Roel,

Answer:

1>Long can fit only in double
2> char can fit only in int, float, long, double.
3>Can byte be widened? Is it not the data type in java with small range, than any other data types? Yes, it is true that byte cant fit into char.

Thanks to Sergej Smoljanov and Henry Wong. Reply from these two helped me in answering this quiz question of yours.

With great respect,
Prathima
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prathima gaitonde wrote:1>Long can fit only in double

A long can fit in both a float and a double (more info in this and following posts). Also be careful: there is an important difference between long and Long.

Prathima gaitonde wrote:2> char can fit only in int, float, long, double.



Prathima gaitonde wrote:3>Can byte be widened? Is it not the data type in java with small range, than any other data types? Yes, it is true that byte cant fit into char.

This seemed easy, but there is a catch byte, short and other primitive data types are signed, only char is not, char is unsigned. That's why byte can not fit into char.

So this code won't compile:

But this code will compile successfully:

And this code... again won't compile:

Once more, great fun with a very simple question!

Hope it helps!
Kind regards,
Roel

[edit] fixed mistake to avoid confusion (Thanks Sharmili)
 
Sharmili Rameshbabu
Greenhorn
Posts: 27
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
Spot-on! Although you made a little slip-up in your explanation: As byte range is -127 to 128, value 200 is too big to fit into byte


Isnt the range of byte -128 to 127??
 
Sharmili Rameshbabu
Greenhorn
Posts: 27
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:

And a reply of me would not be complete if I didn't have a few pop quiz questions So here we go:
1/ can a long be widened to a float?
2/ can a byte be widened to a char?
3/ can a char be widened to a short?
4/ can a char be widened to a float?


What i have answered when i saw these questions are
1/true
2/false
3/false
4/true

Prathima gaitonde wrote:
1>Long can fit only in double


I tried the following code and call with long argument actually calls the method with float parameter.


output is float. So it means long is widened to float. Is it not?
 
Sharmili Rameshbabu
Greenhorn
Posts: 27
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This link from oracle docs also mentions long can be widened to float or double
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sharmili Rameshbabu wrote:
Roel De Nijs wrote:
Spot-on! Although you made a little slip-up in your explanation: As byte range is -127 to 128, value 200 is too big to fit into byte


Isnt the range of byte -128 to 127??

Of course! A typo of mine, I updated the original statement, so others won't get confused. Well spotted!
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sharmili Rameshbabu wrote:output is float. So it means long is widened to float. Is it not?

Yes, it definitely is! And it's confirmed in the link you provided. Have a cow for spotting 2 bugs in this thread. It's well deserved!

Still for me it's a little bit weird that long fits float, because long is a 64-bit data type and float is just 32-bit. This little code snippet shows what happens when you assign the maximum value of long to a float:


Output: 9223372036854776000,000000 9223372036854775807

So you clearly have precision loss. But you do not need a cast to assign a long to a float, so clearly long can be widened to float.

Kind regards,
Roel
 
Sharmili Rameshbabu
Greenhorn
Posts: 27
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Roel! Even i thought about the bit length of both the data types, its weird! and explanation from the same link goes as below.

A widening conversion of an int or a long value to float, or of a long value 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).
 
Henry Wong
author
Marshal
Pie
Posts: 22113
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
Still for me it's a little bit weird that long fits float, because long is a 64-bit data type and float is just 32-bit. This little code snippet shows what happens when you assign the maximum value of long to a float:


Output: 9223372036854776000,000000 9223372036854775807

So you clearly have precision loss. But you do not need a cast to assign a long to a float, so clearly long can be widened to float.


You can also lose precision going from a long to a double too. A double only allows 52 bits for the mantissa, so it is possible to choose a long value that can't be converted to a double without loss of precision.

Henry
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:You can also lose precision going from a long to a double too. A double only allows 52 bits for the mantissa, so it is possible to choose a long value that can't be converted to a double without loss of precision.

True! Can be easily illustrated if you make a small change to the previous code snippet.Output: 9223372036854776000,000000 9223372036854775807

And for completeness: no precision loss with an int widened to a double, but widened to a float you don't get exactly the same maximum value of int. This code snippetprints: 2147483647 2147483648,000000 2147483647,000000

Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic