Sunday, June 1, 2014

IDEONE Java Basics 103 – Float Variables

---
IDEONE Java Basics 103 – Float Variables

PREREQUISITE

This tutorial uses the online compiler IDEone (www.ideone.com ).
IDEone gives you few benefits:
1) Zero setup. You just need Internet Connection and a modern Web Browser.
2) Online storage. You can refer back to the codes at later time.
3) Public codes available. You can also see how others write codes and learn from them as well.
4) Online Learning. You can ask a companion at remote location to help edit the codes or review your codes for improvements or troubleshooting algorithms.

STEPS

1) Start with the basic template

Clone the code above. (Click the Fork button).

2) Edit the codes.

2-1) Change the variable data type in declaration statement.

                float first_number, second_number, answer;
2-2) Change the operator in operation statement.

                answer = first_number + second_number;
2-3) Run.
Problem: Since we have declared the variables as float data type, the compiler expects to receive a float value instead of a double value.
Solution: We have to explicitly tell the compiler to assign float values by adding the letter f after the number.
2-4) Add f to the value in assignment statement.

                first_number = 10.5f;
                second_number = 20.8f;
2-5) Run.
2-6) Change the operator in operation statement.

                answer = first_number / second_number;
2-7) Run.
Java has taken the first 6 numbers after the point and then rounded up the rest. So the double variable type can hold more numbers than float (refer the screenshot below).  Double is a 64 bit number and float is only 32 bit.
Lessons:
Float is traditionally used for 32-bit architecture which does not support longer digits.  If you are targetting old 32-bit machines, you may consider using float. Otherwise, use double data type.

REFERENCE

---

No comments:

Post a Comment