float Exercises

Declare a float

Create a float variable called price and assign it the value 12.99

Show answer:
float price = 12.99F;

Fix the error

Why does this code not compile? Fix it.

float score = 87.5;
Show answer:
float score = 87.5F; // The F is required at the end

Change a value

Create a float variable speed and assign it 45.5. Then change its value to 60.0.

Show answer:
float speed = 45.5F;
speed = 60.0F;

System.out.println(speed); // prints 60.0

Maximum value

Print the maximum value a float can store using the Float class

Show answer:
System.out.println(Float.MAX_VALUE); // prints 3.4028235E38

String to float

Convert the string "19.75" into a float and store it in a variable called total.

Show answer:
float total = Float.parseFloat("19.75");
System.out.println(total); // prints 19.75

Comparison

Given two float values:

float a = 5.5F;
float b = 8.2F;

Use a Float method to determine which value is larger

Show answer:
float a = 5.5F;
float b = 8.2F;

float max = Float.max(a, b);
System.out.println(max);

Float size

Write code to print:

  • The size of a float in bits
  • The size of a float in bytes
Show answer:
System.out.println(Float.SIZE);   // bits
System.out.println(Float.BYTES);  // bytes

Fix the error

What is the result of running this code and how can you fix it?

float converted = Float.parseFloat("abc");
Show answer:
float converted = Float.parseFloat("123"); // String needs to be numeric, otherwise a NumberFormatException will be thrown

Float equality

Why might this code produce an unexpected result?

float x = 0.1F + 0.2F;
float y = 0.3F;

System.out.println(x == y);
Show answer:
float x = 0.1F + 0.2F;
float y = 0.3F;

System.out.println(x == y); // false
// Floating-point numbers are stored in binary.
// Some decimal values cannot be represented exactly,
// which leads to small precision errors.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories