• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help with data types and casting

 
Momen Travolta
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can`t deduce the rules! the results are mostly unexpected to me! please help me.



About casting:-
Do I have to use casting only when assigning a higher data type to a lower one?
 
Henry Wong
author
Marshal
Pie
Posts: 20831
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Momen Travolta wrote:
About casting:-
Do I have to use casting only when assigning a higher data type to a lower one?


Casting must be explicit if the source range is not within the target range. This means that an double must be explicited casted to a long, but not vica versa. And in the case of a short and char, it means that casting must be done in both directions.

Henry
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Momen Travolta wrote:

Long.MAX_VALUE is 2^63-1, or 9223372036854775807. Both a and b are larger than this number. c is shorter but the number is an int, and is larger than Integer.MAX_VALUE (2^31-1 or 2147483647). Adding the L tells the compiler that this literal is not an int but a long.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 1: You are dividing a float with an int. The result will be a float. Floats are limited to about 6 or 7 digits of precision.
Line 2: You are dividing a long by an int. The result will be a long. Because it is an integer division, the result is 0.
Line 3: Similar to line 2, integer division, result is 0.
Line 4: Dividing a double by an int, the result is a double, which has more digits than a float (line 1).

Line 7: Floating-point literals are double by default, you can't assign them to a float without casting or appending an "f".
Lines 8-9: Assigning values to float, what are you unclear about here?
Line 10: Assigning an int literal to a float is allowed, you might loose some digits.

Line 14: The int literal is too big to fit into a 32-bit int, so you get an error.
Line 15: The long literal is too bit to fit into a 64-bit long, so you get an error.
Line 16: The int literal is too big to fit into a 32-bit int, so you get an error.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47232
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's a higher data type? What's lower data type? I don't think those are standard Java terms.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic