As we have learned at the beginning of this book in Part I, the Java programming language has defined the integer, double, Boolean, String, etc., as basic types. In Java, we cannot assign any value to a variable without defining the variable with a type beforehand. Only after a variable has been defined clearly by a type—for example, integer—are we then allowed to assign an integer value to it and start using it as an integer in the calculation. Once a variable’s type is defined, it cannot be assigned a value with a different type, logically speaking. For instance, if a variable is defined as Boolean, it cannot be assigned an integer value. Otherwise, we will get a type mismatch compilation error.
Type Casting
This is the output:
When the integer 5 is assigned to a double typed variable, the variable will get an equivalent value with a decimal point presentation, that is, double value 5.0.
When an integer is divided by another integer, the result follows the same integer type, for example, 5 / 3 = 1. But when the fraction “5 / 3” is assigned to a double typed variable, the resulting value will be automatically converted to double value 1.0.
(double)(5 / 3) converts an integer result of (5/ 3) to a double value. This is called type casting. The result is 1.0, a double value.
How do we produce a precise value from 5 / 3? The trick is to use (double)5 / 3, instead of 5 / 3. The outcome of (double)5 / 3 is a double value. Or, you may use 5.0 / 3 to generate the same outcome. Another way is 5d / 3, or 5 / 3d. The outcomes of both expressions are the same double value.
Math: Slope of a Line
In the x-y 2D Cartesian coordinates system, the slope of a line between points (x1, y1) and (x2, y2) is equal to (y2 - y1) / (x2 - x1).
Example
Implement a public method called double getSlope() , which returns the slope of a line. If the two points have the same x-coordinates, the denominator is zero and the slope is undefined, so you should throw an IllegalArgumentException in this case. This will stop your program running and show the specified error message.
Answer
Math: Collinearity
Points are collinear if a straight line can be drawn to connect them. Two basic examples are when three points have the same x- or y-coordinate. The more general case can be determined by calculating the slope of the line between each pair of points and checking whether the slope is the same for all pairs of points.
We use the formula (y2 - y1) / (x2 - x1) to determine the slope between two points (x1, y1) and (x2, y2).
It needs to return true if the given point is collinear with the points of this line.