Syntax Quiz 2, Step 15

Assignment:

Write an expression to find the square root of the number stored in the variable instanceVar.

My solution:

Math.sqrt(this.instanceVar)
or
Math.sqrt(instanceVar)
(Again, the this. isn't required by Java, but I prefer it.)

Common mistakes:

Putting this.instanceVar in front, rather than inside the parentheses, e.g. this.instanceVar.sqrt()
Arguments of primitive types (int, double, and boolean) are always passed inside the parentheses, not in front of the period.
Omitting the Math..
Every method in Java belongs to some class, and therefore must be called on some object. The sqrt method, however, takes only a numeric parameter, which as stated above must be inside the parentheses. So what object can we call it on? The answer, in this case, is the Math class itself; it's what we call a static method. In fact, most of the methods in the predefined Math class are static, and therefore are called with the syntax Math.methodName(numericArgs).
Putting a semicolon at the end.
Math.sqrt(this.instanceVar) is an expression, not a statement, so it doesn't end with a semicolon. However, the expression is about to be part of a statement.

Stephen Bloch / sbloch@adelphi.edu