double Exercises

Declaring a double

Declare a double variable called price and assign it the value 12.99

Show answer:
double price = 12.99;

Reassigning values

Create a double variable score with value 50.0. Change its value to 75.5 and print the result.

Show answer:
double score = 50.0;
score = 75.5;
System.out.println(score); // prints 75.5

Using scientific notation

Assign the value 1.5E3 to a double variable and print its value. What number is displayed?

Show answer:
double number = 1.5E3;
System.out.println(number); // prints 1500.0

Parsing a String

Convert the string "45.6" into a double and store it in a variable called number

Show answer:
double number = Double.parseDouble("45.6"); // returns 45.6

String conversion

Convert the double value 99.99 into a String

Show answer:
String text = Double.toString(99.99); // returns "99.99"

Maximum value

Use an appropriate method to find the larger of 2 values – 98.9 and 78.7

Show answer:
Double.max(98.9, 78.7) // returns 98.9

Replace the value

Create a double variable balance with value 100.0. Change it to 75.0

Explain in a comment what happens to the original value

Show answer:
double balance = 100.0;
balance = 75.0;
System.out.println(balance);
// The original value (100.0) is replaced by 75.0
// Primitive types store values directly, not references

Comparing two Doubles

Compare the two objects below using equals() and compareTo(). Write down the results

Double a = 10.0;
Double b = 15.0;
Show answer:
System.out.println(a.equals(b));    // returns false
System.out.println(a.compareTo(b)); // returns -1

Valid vs invalid parsing

Which of the following lines will work, and which will cause an error? Explain why

Double.parseDouble("123.45");
Double.parseDouble("-9.8");
Double.parseDouble("hello");
Double.parseDouble("12.3.4");
Show answer:
Double.parseDouble("123.45"); // ✅ works
Double.parseDouble("-9.8");   // ✅ works
Double.parseDouble("hello");  // ❌ NumberFormatException
Double.parseDouble("12.3.4"); // ❌ NumberFormatException

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