Model G20 2027 at FLAME University, registrations now open

Mathematical Library Methods | ICSE Class 9 Computer Applications Notes

24 min read

On this page

This note covers Java mathematical library methods, the java.lang package, the Math class, method syntax, arguments and return types, powers and roots, rounding, absolute values, comparisons, random values, hypotenuse calculations, exact integer arithmetic, and the use of methods in Java expressions.

What are mathematical library methods?

A library method is a named operation supplied as part of a programming library. A library is a collection of reusable programming facilities. Java provides mathematical operations through Math, a class containing methods for common numerical tasks.

A class is a named definition that groups related members, such as methods. A method is a named block of code that performs an operation. Calling a method asks Java to perform that operation, using any supplied input.

How are the package and class related?

A package groups related Java classes and other types under a common name. Math belongs to java.lang. Java makes the accessible types in this package available automatically, so a separate import statement is unnecessary for ordinary use of Math.

Definition: An import statement allows a program to refer to an accessible type by its simple name. The Math class can be referred to directly because java.lang is automatically imported.

Math methods used here are static methods: they belong to the class and can be called through its name. There is no need to create an object, meaning an individual instance of a class, before calling them.

The mathematical task determines the method to choose. Power, root, rounding, comparison and exact arithmetic are different operations. Recognising the task is the first step; checking the method's input and output types is the next.

A library method returns a result according to its defined behaviour. It does not decide whether that operation suits the problem. A correctly spelt call can still produce an unsuitable calculation if the programmer selects the wrong method.

How do you read a Math method call and its types?

An argument is a value or expression supplied to a method. An expression is a combination of values, operators or method calls that produces a value. A return value is the result supplied by a method to its caller; its data type is the return type.

Throughout the syntax below, x and y represent numerical arguments, while a and b represent numerical arguments used in comparisons or arithmetic. Their required types depend on the method. A variable is a named storage location; assignment stores a value in it. These letters are placeholders, not prescribed variable names.

Syntax: Math.sqrt(x) calls sqrt through the Math class. The dot selects a member of the class; parentheses enclose the argument. Math.pow(x, y) supplies two arguments, separated by a comma.

Why does the return type matter?

A data type specifies the kind of value a program element can hold. Java's int and long are signed integer types: they store whole numbers within fixed ranges. The long range is wider than the int range.

float and double are floating-point types, which represent numerical values with limited precision and can represent fractional values. Double provides greater precision than float. Precision describes how much significant numerical information a representation can retain.

Overloading means providing methods with the same name but different parameter lists. A parameter is a named input declared by a method; an argument supplies its value at a call. Math.abs, Math.max, Math.min and Math.round have overloaded forms.

Read a method's name, argument count, argument types and return type together. An integer-valued result is a value without a fractional part; it need not have an integer data type. Several rounding methods return double even when their ordinary results are integer-valued.

How does Math.pow calculate a power?

Math.pow(x, y) returns x raised to the power y. Here x is the base, the quantity being raised to a power, and y is the exponent, which specifies that power. The order of these arguments matters.

The method accepts double arguments and returns double. An int argument can undergo widening conversion, an automatic conversion to a type permitted by Java's conversion rules. Passing whole-number arguments therefore does not make the return type int.

Rule: Use Math.pow(x, y) for exponentiation in Java. The symbol ^ is not Java's power operator; do not substitute it for a call to Math.pow.

What should be checked before using a power?

For a positive integer exponent, the mathematical meaning is repeated multiplication of the base. The method also accepts other double exponents. However, accepting an argument type does not mean every combination has a real, finite result.

A finite value is a value that is neither infinity nor NaN. NaN means “Not a Number”, a special floating-point value representing an undefined numerical result. A negative finite base with a finite non-integer exponent produces NaN in Math.pow.

The domain of a mathematical operation is the set of inputs for which the intended result is defined. Check the domain before interpreting the returned value. For a negative quantity's real cube root, Math.cbrt directly expresses the required operation.

Floating-point calculation also has representational limits. A power call is useful for expressing exponentiation clearly, but its double return type does not promise exact representation of every mathematical answer. Keep the distinction between the intended mathematical quantity and its stored Java value.

How do Math.sqrt and Math.cbrt find roots?

A square root of a number is a value whose square equals that number; squaring means multiplying a value by itself. Math.sqrt(x) returns the non-negative square root for an ordinary non-negative finite argument x. Non-negative means zero or positive.

A cube root is a value whose cube equals the original number; cubing means multiplying three copies of a value. Math.cbrt(x) returns the cube root. Both methods accept a double argument and return double.

How do their input restrictions differ?

MethodMeaningNegative finite argument
Math.sqrt(x)Non-negative square root for non-negative ordinary inputReturns NaN for input below zero
Math.cbrt(x)Cube root of the argumentReturns a negative cube root

For a positive number, the equation formed by squaring an unknown may have both positive and negative solutions. Math.sqrt returns the non-negative root, not a pair of solutions. If a problem requires both solutions, that is a further mathematical step.

The sign of an ordinary negative input is retained by its cube root because multiplying three negative factors gives a negative product. Removing the input's negative sign before calling cbrt would change the problem and produce a root with the wrong sign.

Note: A root method returns double even when its result is a whole-number value. The mathematical appearance of a result and its Java data type are separate facts.

When tracing a root expression, identify the entire argument enclosed by the method's parentheses. Any arithmetic inside those parentheses must produce the argument before the method operates on it. Do not apply the root to just one term of a larger argument.

How do Math.ceil and Math.floor differ?

Math.ceil(x) returns the least integer-valued double greater than or equal to x. Math.floor(x) returns the greatest integer-valued double less than or equal to x. Both accept double and return double.

“Greater than or equal to” includes equality; “less than or equal to” does too. For an ordinary finite input already having an integer value, neither method needs to move to another integer. The return type nevertheless remains double.

Why is direction more useful than “up” or “down”?

Think of a number line as an ordered line on which values increase towards the right. Ceiling moves towards the next permitted integer value on the greater side; floor moves towards the next permitted integer value on the smaller side.

For a negative non-integer value, moving towards a greater integer moves towards zero. Moving towards a smaller integer moves away from zero. This is why a rule based on “removing the decimal part” cannot describe both methods.

FeatureMath.ceil(x)Math.floor(x)
Direction for ordinary non-integer inputTowards the greater neighbouring integerTowards the smaller neighbouring integer
Selection ruleLeast integer value not below the argumentGreatest integer value not above the argument
Return typedoubledouble

Rule: Ceiling and floor are directional operations. Neither chooses a result by asking which neighbouring integer is closer to the argument.

These methods should therefore be selected from the required direction, not from the size of a fractional part. A requirement for the nearest integer is different and calls for considering round or rint instead.

How do Math.round and Math.rint handle the nearest integer?

Math.round selects a nearest integer, with ties towards positive infinity. A tie occurs when a value lies exactly halfway between neighbouring integers. “Towards positive infinity” means choosing the greater of those two integers.

Math.rint(x) returns the nearest integer-valued double, with ties going to the even integer. An even integer is an integer divisible by two without a remainder. Here x is a double argument, and the method returns double.

Which return types must you remember?

Call formOrdinary finite rounding ruleReturn type
Math.round with a float argumentNearest integer; halfway ties towards the greater integerint
Math.round with a double argumentNearest integer; halfway ties towards the greater integerlong
Math.rint with a double argumentNearest integer value; halfway ties towards the even integerdouble

For ordinary finite values within the relevant integer range, round and rint can select the same mathematical integer while returning different types. At halfway values their selection rules can differ. Specify both the value rule and the type when comparing them.

For a negative halfway value, round selects the greater neighbouring integer, which lies closer to zero. It does not use a general rule of moving away from zero. Rint instead examines whether the neighbouring integer is even, regardless of the input's sign.

Syntax: Write Math.rint(x), supplying the double argument inside the parentheses. Math.random() takes no argument; Math.rint does require one.

At the limits of an integer type, Math.round cannot return an arbitrary integer outside that type's range. Values beyond the relevant range give its limiting integer value. For a NaN argument, its result is zero. Do not extend ordinary rounding reasoning beyond the return type's limits.

What does Math.abs return?

The absolute value of a real number is its distance from zero on the number line. For ordinary values, Math.abs(a) leaves a non-negative argument unchanged and gives the corresponding positive value for a negative argument.

The argument a is the number whose absolute value is required. Math.abs has forms accepting int, long, float and double. Each of these forms returns the same type as its argument; absolute value does not automatically mean conversion to double.

What qualification is needed for integer limits?

Java's int and long ranges are not symmetrical about zero. Each has a most-negative value whose positive counterpart cannot be represented by the same type. For that particular argument, Math.abs returns the same negative value.

Note: Do not claim that Math.abs always returns a positive number. Ordinary zero remains zero, and the most-negative int and long values require the fixed-range qualification.

A type's range is the interval between the smallest and largest values it can represent. This exceptional integer behaviour arises from the range, not from a different mathematical definition of absolute value. Mathematical integers and fixed-range Java integers are distinct ideas.

Absolute value also differs from choosing a larger or smaller number. Math.abs examines one argument and its sign. Math.max and Math.min compare two arguments. Replacing one of these operations with another changes the requested calculation.

When a later operation needs the original sign, keep the original value available. A Math.abs call returns a value; it does not itself assign that value back to the variable supplied as its argument. Assignment is a separate programming operation.

How do Math.max and Math.min compare values?

Math.max(a, b) returns the greater of its two arguments; Math.min(a, b) returns the smaller. Here a and b are the two values being compared. These methods select a numerical value rather than calculate their difference.

Both methods have forms for int, long, float and double pairs. For a pair of arguments of the same one of these types, the corresponding overload returns that type. If argument types differ, consider Java's conversions and overload selection.

What exactly is being compared?

For ordinary finite values, comparison follows numerical order. A negative value nearer zero is greater than a negative value farther from zero. Do not compare just the digits while ignoring their signs, or confuse numerical order with absolute magnitude.

Magnitude means size without regard to sign in this context. A comparison of absolute values asks a different question from a comparison of the original values. Use abs only if that is what the required calculation calls for.

Required operationMethodArguments
Select the greater valueMath.max(a, b)Two numerical values
Select the smaller valueMath.min(a, b)Two numerical values
Find one value's absolute magnitudeMath.abs(a)One numerical value

If two ordinary finite arguments are equal, their common numerical value is the result of either comparison. Neither method returns a label saying which argument position was chosen, and neither returns a statement that the values are equal.

A boolean is Java's type for true or false. Max and min return numerical results, not boolean answers. If a program requires a true-or-false condition, a relational comparison is a different operation from these selection methods.

What does Math.random produce?

Math.random() returns a pseudorandom double in the range from zero, inclusive, to one, exclusive. Pseudorandom means generated by an algorithm to behave like a random sequence. Inclusive means an endpoint is allowed; exclusive means it is excluded.

Therefore, zero is allowed and one is excluded. The return type is double. The empty parentheses indicate that the call takes no arguments. Supplying numerical limits inside those parentheses is not the syntax of this method.

What can and cannot be predicted?

The permitted interval is known before a call executes; the particular returned value should not be treated as a predetermined constant. A question asking for an exact output cannot assign a specific decimal to a random call without further information.

Rule: For Math.random(), state the return type and the inclusive and exclusive endpoints. Do not replace a varying result with an invented fixed output.

Repeated calls produce values that are approximately uniformly distributed over the permitted interval. Approximately uniform means the generator is designed to spread results approximately evenly across equal portions of that interval. It does not promise a perfectly even pattern in every short sequence.

Nor does the method promise that successive calls must all differ. Random-looking results can repeat. A requirement for unique values would need additional program logic; uniqueness is not part of the behaviour described by this call.

If a program needs to reuse one generated result, it must store that return value in a variable. Calling random again requests another result. Reading a stored value and making a fresh method call are different actions.

How does Math.hypot calculate a hypotenuse?

A right-angled triangle has an angle of ninety degrees. Its hypotenuse is the side opposite that angle. If a and b represent the perpendicular side lengths, the hypotenuse length is the square root of the sum of their squares.

Math.hypot(a, b) returns that numerical quantity. It accepts two double arguments and returns double. In a geometric calculation, both supplied lengths must use the same unit, and the result uses that unit too.

Why use the dedicated method?

Hypot expresses the intended calculation directly. It is designed to calculate the square root of the sum of squares without intermediate overflow or underflow. Overflow means a result exceeds the representable range; underflow concerns very small floating-point results losing representable magnitude or precision.

Intermediate results are values calculated along the way to a final answer. Directly squaring large arguments can overflow before the square root is taken. Hypot avoids that intermediate problem even when a direct sequence of ordinary operations would encounter it.

Note: Avoiding intermediate overflow is not a promise that every final mathematical result fits into double. Distinguish the method's calculation strategy from the representable range of its result.

The Java method can accept negative arguments because the calculation involves their squares. When a and b stand for triangle lengths, however, the physical lengths are non-negative. The program's numerical arguments and their interpretation in a problem must agree.

Hypot requires both arguments. Knowing only one perpendicular side does not determine a unique hypotenuse. Before tracing a geometric calculation, identify both lengths, confirm their units, and distinguish the hypotenuse from either of the perpendicular sides.

How do the exact integer arithmetic methods work?

Math.addExact(a, b), Math.subtractExact(a, b) and Math.multiplyExact(a, b) perform addition, subtraction and multiplication with overflow checking. In their int forms, both arguments are int and the result, when representable, is int.

The word exact here concerns representable integer arithmetic and detecting overflow. These methods do not turn int into a type with an unlimited range. They do not perform decimal rounding, and they are not substitutes for floating-point root or power methods.

What happens when a result is outside the range?

If the mathematical result cannot be represented by int, the relevant int method throws ArithmeticException. An exception is a signal of an exceptional condition during program execution. Throwing one interrupts normal execution unless suitable handling takes over.

Method with int argumentsOperationWhen the result exceeds int range
Math.addExact(a, b)Sum of a and bThrows ArithmeticException
Math.subtractExact(a, b)a minus bThrows ArithmeticException
Math.multiplyExact(a, b)Product of a and bThrows ArithmeticException

Argument order is significant for subtraction: the second argument is subtracted from the first. The addition and multiplication methods calculate their respective arithmetic results and check whether those results fit. A method call that throws an exception supplies no normal return value.

Rule: Ordinary int addition, subtraction and multiplication do not throw an overflow exception. The corresponding exact methods detect an out-of-range result and throw ArithmeticException.

Saving an ordinary int calculation into a long variable afterwards does not undo overflow that already occurred during the int calculation. Check the types used during the operation, not just the type of the variable intended to receive the final result.

How should Math methods be used in Java expressions?

A Math call can supply a value to a larger expression, an assignment or an output statement. Assignment stores a value in a variable, a named storage location. An output statement displays a value; System.out.println displays its argument and then ends the line.

Syntax means the rules for writing valid program text. Java is case-sensitive, so uppercase and lowercase letters are significant. Preserve Math's capital M and the internal capitals in addExact, subtractExact and multiplyExact.

What order of checks helps with tracing?

  1. Identify the operation. Decide whether the expression requires a power, root, comparison, rounding operation, random result or checked integer calculation.
  2. Read the arguments. Check their number, order, numerical values when provided, and data types. Locate any arithmetic inside the argument parentheses.
  3. Determine the return type. Follow the selected method or overload. Do not infer a type merely from the appearance of the mathematical answer.
  4. Check exceptional cases. Consider domain restrictions, overflow, NaN and random variation before claiming a particular output or normal return value.
  5. Use the returned value. Apply the surrounding expression, assignment or output operation, keeping any further conversions separate from the method call.

Integer division is division performed on integer operands; its result discards any fractional part towards zero. If it occurs while calculating an argument, a later conversion to double does not restore the discarded fraction. Argument calculations therefore deserve separate attention.

Operator precedence determines how an expression is grouped when parentheses do not settle the grouping. Parentheses can make the intended grouping explicit. A nested method call is a call used inside another call; the inner result supplies an argument to the outer method.

Syntax: Read Math.pow(x, y), Math.sqrt(x), Math.abs(a) and Math.max(a, b) as expressions. A semicolon ends a Java statement; the comma inside a call separates arguments.

Keep a final distinction between returning and printing. A mathematical method supplies a result to the calling expression. It does not, just by being called, display that result. The surrounding program must explicitly use an output operation when visible output is required.

Glossary

  • Library method — A reusable named operation supplied by a programming library for programs to call.
  • Package — A named grouping of related Java classes and other types.
  • Static method — A method belonging to a class and callable through the class name.
  • Argument — A value or expression supplied as input when calling a method.
  • Parameter — A named input declared by a method to receive an argument value.
  • Return type — The data type of the value a method supplies to its caller.
  • Overloading — Providing methods with the same name but different parameter lists.
  • Floating-point type — A numerical type with limited precision that can represent fractional values.
  • Absolute value — A real number's distance from zero, without regard to its sign.
  • Rounding tie — A value lying exactly halfway between the two neighbouring integer values.
  • Pseudorandom — Generated by an algorithm to behave like values from a random sequence.
  • NaN — Not a Number, a special floating-point value representing an undefined numerical result.
  • Overflow — A condition in which a numerical result exceeds the representable range.
  • Hypotenuse — The side of a right-angled triangle opposite its right angle.
  • ArithmeticException — An exception signalling an exceptional arithmetic condition, including overflow detected by exact integer methods.

Common errors and misconceptions

  • Misconception: Math needs an object and an explicit import before every call. Correct: The methods here are static, and Math belongs to the automatically imported java.lang package.
  • Misconception: A whole-number answer means the method returns int. Correct: Methods including sqrt, pow, ceil, floor and rint return double, even when the value has no fractional part.
  • Misconception: Floor removes a negative number's fractional part towards zero. Correct: Floor selects the greatest integer value not above the input, moving towards smaller values for non-integer input.
  • Misconception: Round and rint use the same halfway rule. Correct: Round chooses towards positive infinity; rint chooses the even neighbouring integer. Their return types also differ.
  • Misconception: Random returns a fixed decimal or can return its upper endpoint. Correct: The generated double varies, with zero included and one excluded.
  • Misconception: Rint takes no arguments. Correct: Math.rint requires a double argument; Math.random is the no-argument method among these two methods.
  • Misconception: Abs makes every possible integer argument positive. Correct: Zero remains zero, and the most-negative int or long cannot become positive within the same type.
  • Misconception: Exact methods provide integers of unlimited size. Correct: Their int forms return an int when representable and throw ArithmeticException when the mathematical result exceeds that range.

Exam-style questions with model answers

Q1. Name the package containing Math and explain whether an object is needed to call the Math methods in this chapter. [2 marks]
  1. Math belongs to java.lang, whose accessible types are automatically available without a separate import statement.
  2. These Math methods are static, so they can be called through the class name without creating a Math object.
Q2. Let x be a finite double value. Compare Math.ceil(x) and Math.floor(x) by giving each selection rule and their common return type. [3 marks]
  1. Math.ceil(x) selects the least integer-valued result greater than or equal to x. For ordinary non-integer input, it moves towards the greater neighbouring integer.
  2. Math.floor(x) selects the greatest integer-valued result less than or equal to x. For ordinary non-integer input, it moves towards the smaller neighbouring integer.
  3. Both methods return double. Having an integer value does not change the result into the int data type.
Q3. Let x be a finite double value exactly halfway between neighbouring integers, within the long range. Compare Math.round(x) and Math.rint(x), giving both tie rules and both return types. [4 marks]
  1. Math.round(x) resolves the halfway tie towards positive infinity, selecting the greater of the two neighbouring integer values.
  2. Math.rint(x) resolves the halfway tie by selecting the even integer, rather than invariably selecting the greater neighbour.
  3. Math.round(x) returns long because the supplied argument x has the double type, selecting the double-argument overload.
  4. Math.rint(x) returns double, even though its finite returned value has no fractional part after this rounding operation.
Q4. Describe Math.random() under five headings: argument count, return type, lower endpoint, upper endpoint, and whether its next exact decimal output is fixed in advance by the call. [5 marks]
  1. The call takes no arguments. Its empty parentheses are required call syntax and do not stand for omitted numerical limits.
  2. The method returns double, a floating-point type. It does not directly return an integer selected from an unspecified range of integers.
  3. The lower endpoint is zero and is inclusive. Zero is therefore permitted, so describing every possible result as strictly positive is incorrect.
  4. The upper endpoint is one and is exclusive. One is therefore excluded, even though returned values can lie below and near it.
  5. The call generates a pseudorandom value. Its next exact decimal output cannot be deduced from this call alone and should not be replaced with a fixed invented value.
Q5. Let a and b be int arguments. Explain the operation of Math.addExact(a, b), Math.subtractExact(a, b) and Math.multiplyExact(a, b), their normal return type, and their behaviour when the mathematical result is outside the int range. [5 marks]
  1. Math.addExact(a, b) calculates the sum of the two supplied integers. It also checks whether that mathematical sum can be represented by int.
  2. Math.subtractExact(a, b) subtracts b from a. The first argument is the starting value, so reversing the argument order changes the requested subtraction.
  3. Math.multiplyExact(a, b) calculates the product of a and b. Its overflow check concerns the representability of that integer product.
  4. With these int arguments, a normally completed call returns int. The method name does not promise an unlimited-range integer or an automatic long result.
  5. If the mathematical result lies outside the int range, the method throws ArithmeticException. It does not return an ordinary numerical result from that call.
Q6. Let x be a negative finite double value. Explain how Math.sqrt(x) and Math.cbrt(x) differ, and give their common return type. [3 marks]
  1. Math.sqrt(x) returns NaN, meaning Not a Number, because a negative finite input has no real square root represented by this operation.
  2. Math.cbrt(x) returns a negative cube root. Cubing a negative value gives a negative result, so the original input's sign is retained.
  3. Both methods return double. The different treatment of this negative input concerns the operation and its domain, not a difference in their return types.
Q7. Let a and b be the non-negative perpendicular side lengths of a right-angled triangle, stored as double values in the same unit. State the suitable Math call, the quantity and type it returns, and its benefit concerning intermediate calculations. [3 marks]
  1. Use Math.hypot(a, b), supplying the two perpendicular side lengths as its arguments. Both lengths must use the same unit for this geometric interpretation.
  2. The method returns double representing the hypotenuse length, calculated as the square root of the sum of the side lengths' squares.
  3. It avoids intermediate overflow or underflow during that calculation. This does not guarantee that a final mathematical result beyond the double range becomes representable.
Q8. Explain why the claim “Math.abs always gives a positive result” is incorrect, referring to zero and to the most-negative int argument. [2 marks]
  1. The absolute value of zero is zero, which is not a positive number.
  2. The most-negative int has no representable positive counterpart in int, so Math.abs returns that same negative value.

Key takeaways

  • Math belongs to java.lang, and its mathematical methods can be called through the class name without creating an object.
  • Check argument count, argument order, argument types and return type before interpreting any mathematical method call.
  • Pow calculates a power; sqrt and cbrt calculate roots, with different behaviour for negative finite arguments.
  • Ceil and floor select integer values by direction, while round and rint select nearest integers using different tie rules.
  • A method's return type is distinct from its numerical value; an integer-valued result can still have type double.
  • Random returns a pseudorandom double from zero inclusive to one exclusive, without accepting any arguments.
  • Hypot calculates the square root of a sum of squares while avoiding intermediate overflow and underflow.
  • The int exact-arithmetic methods return representable int results and throw ArithmeticException when their mathematical results exceed that range.

Test yourself

Why can Math be used without a separate import statement?

Math belongs to java.lang, whose accessible types are automatically imported into Java programs.

In Math.pow(x, y), what do x and y represent?

The argument x is the base, and y is the exponent specifying the power.

Does Math.floor return int when its argument is double?

No. Math.floor returns double, although its ordinary finite result is integer-valued.

Which nearest-integer method chooses the even integer at a halfway tie?

Math.rint chooses the even neighbouring integer and returns the result as double.

Does Math.max compare absolute magnitudes automatically?

No. It compares numerical values; comparing their absolute magnitudes requires a different expression.

Can Math.random return one, and does it require an argument?

It cannot return one because its upper endpoint is excluded. It takes no arguments.

What happens when Math.multiplyExact with int arguments has an out-of-range product?

It throws ArithmeticException because the mathematical product cannot be represented by int.

Does merely calling Math.sqrt display its result?

No. The call returns a value; displaying it requires an output operation in the surrounding program.