Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assignment doubt

 
Divya Gehlot
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In below program we have assigned float f=10;
that should give us compiler error . but this program compiles fine and gives output 10.
what am I missing . please let me know.
 
Henry Wong
author
Marshal
Pie
Posts: 21357
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In below program we have assigned float f=10;
that should give us compiler error . but this program compiles fine and gives output 10.
what am I missing . please let me know.


You forgot about the implicit casts. An int will implicitedly cast to a float. Hence, it is possible to (look like) assign an int literal to a float (but it is really a cast).

Henry
 
Divya Gehlot
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it now
Thanks a lot
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But, if you try to assign a *floating point value* to the float variable without using "f", it will give you the compilation error as you expected.



The output is :



Does that help?

Thanks for the post Divya!
 
Yogvinder Singh Ghotra
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
10 is a int literal
10.0 is a double literal

Can I answer the last post by this??
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Yogvinder Singh Ghotra:
....Can I answer the last post by this??


Yes, very much!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic