☰ Contents Data That Travels Together

Methods Provided by Java

Student: I was thinking through writing a method for a distance between points. I realized I needed to take a square root. There’s no operator that we’ve seen for that, right?

Prof: Right. Only the basic arithmetic operators, plus the comparisons like <, are operators. Java provides a number of built-in methods for things like this. For square root specifically, we can use a method defined on the built-in Math:

double sqrt(double n)

So you use it like:

Student: Oh, good. Now I can write my distance method.
Prof: What do you have so far?
Student: Here’s where I got to:
Student: So I guess now I can add the square root:
Prof: Cool! There are a lot of other useful methods in the Math library. For example, you could use Math.pow(xdiff, 2) instead of xdiff *
xdiff
, though either one is fine. There are also all the usual trig functions like sin and cos. Have a look there (or ask an AI agent about the Math library in Java) if you need to know about a specific one.

Practice

Math measures angles in radians. Finish Point so that angle() is the angle from the positive x axis, turning counterclockwise, up to the point, and degrees() is the same angle in degrees. For the point (1, 1) that is π/4 radians, or 45 degrees.
record Point(double x, double y) {
double angle() {
return Math.(y, x);
}
double degrees() {
return Math.(angle());
}
}
Point p = new Point(1.0, 1.0);
double angle = p.angle();
double degrees = p.degrees();