• Post Reply Bookmark Topic Watch Topic
  • New Topic

Study Guide confusion  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I am reading the Programmer I Study Guide and a bit confused with some of the text.

In Chapter 2 there is a section about data types and operators, questioning the data type of the result. The example is as follows:

What is the data type of x + y?
double x = 39.21;
float y = 2.1;

This states that this will not compile as the float value requires a postfix f.

A later example asks this:

What is the data type of x * y / z?
short x = 14;
float y = 13;
double z = 30;

There is no mention of this failing to compile.  Is this because the value of y isn't actually a decimal number?  Shouldn't the compiler have an issue with it anyway?
 
Greenhorn
Posts: 12
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

No. It does not throw compilation error. As per my understanding 13 is an integer literal and integer literals can be assigned to a float variable without any casting. Also they can be assigned to long and double as well without any casting. These three assignments (an int literal to float, long and double) fall under widening data conversion.
Where as floating point literals are treated as double data type hence can NOT be assigned to float data type as it comes under narrowing data conversion. It requires explicit (casting) f, at the end of the floating point literal, to be assigned to a float data type variable.
 
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everything is correct except for the part where you say that putting f at the end of the literal is casting. It's not. The letter at the end of a decimal number literal is called a floating point type suffix and it can be any of f, F, d, or D. An F or f suffix will tell Java to treat the literal value as a float, while the D or d suffix will tell Java to treat the literal as a double. When a decimal literal has no suffix, it will be treated as a double by default.
 
Sarah Holland
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help Makes absolute sense now!
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!