Practical-30
Write a Java Program to implement the methods of Math Class.
Introduction
Java, as a programming language, provides all the necessary classes and methods to solve mathematical problems and perform mathematical calculations. The Math class in Java offers various methods to work with mathematical constants and functions. This program will demonstrate the short examples and the usage of methods from Math class in Java. The program is designed for beginners and users who are just getting started with the language are expected to follow the instructions carefully.
Code
public class Math_Class {
public static void main(String[] args) {
double result;
//to calculate the absolute value
result = Math.abs(-1.444);
System.out.println("Absolute value of -1.444 is : " + result);
//to calculate the ceiling value
result = Math.ceil(1.444);
System.out.println("Ceiling value of 1.444 is : " + result);
//to calculate the floor value
result = Math.floor(1.444);
System.out.println("Floor value of 1.444 is : " + result);
//to calculate the maximum value
double num1 = 1.3;
double num2 = 0.9;
result = Math.max(num1, num2);
System.out.println("Maximum value of two numbers 1.3 & 0.9 is : " + result);
//to calculate the minimum value
double num3 = 1.3;
double num4 = 0.9;
result = Math.min(num3, num4);
System.out.println("Minimum value of two numbers 1.3 & 0.9 is : " + result);
//to calculate the power
result = Math.pow(2, 3);
System.out.println("2 to the power 3 is : " + result);
//to calculate the root
result = Math.sqrt(9);
System.out.println("Square root value of 9 is : " + result);
}
}
Output
Absolute value of -1.444 is : 1.444
Ceiling value of 1.444 is : 2.0
Floor value of 1.444 is : 1.0
Maximum value of two numbers 1.3 & 0.9 is : 1.3
Minimum value of two numbers 1.3 & 0.9 is : 0.9
2 to the power 3 is : 8.0
Square root value of 9 is : 3.0
This code implements the Math Class methods in order to calculate the absolute value of a number, the ceiling and floor values, the maximum and minimum values of two numbers, the power of a number and the square root. The main() method is the entry point of execution and each of the methods from the Math class is utilized with the corresponding arguments (number, power, etc.). The result of each method is printed out to the console for verification.