search
HomeJavajavaTutorialHow to use the Math class in Java programming

1. Math class

1. The class contains basic mathematical operation methods, such as addition, subtraction, multiplication, division, remainder, etc. They cannot perform complex operations. In the Math class, find Absolute value, square root, trigonometric functions, etc., all classes in the Math class are static and can be called using its class name.

2. Static constants

The Math class contains two static constants, PI and E, which represent mathematical π (pi) and e (natural logarithm) respectively

3. Static constant example

public class p61 { public static void main(String[] args) {         // TODO Auto-generated method stub         System.out.println("PI它的常量值:"+Math.PI);         System.out.println("E它的常量值:"+Math.E);   } }

The running result is:

How to use the Math class in Java programming

2. Math class absolute value

1.Absolute value The characteristic of is a positive number, the absolute value of zero is itself, and the absolute value of a negative number is its opposite.

2. Math class absolute value method:

public static int abs(int a) method: returns the absolute value of int type value;

public static float abs( float a) method: returns the absolute value of the float type value;

public static double abs(double a) method: returns the absolute value of the double type value;

public static long abs(long a ) method: return the absolute value of the long type value;

3. Math class absolute value method example:

import java.util.Scanner; public class p67 { public static void main(String[] args) {         // TODO Auto-generated method stub         System.out.println("请输入一个整数");         Scanner scan=new Scanner(System.in);         int a=scan.nextInt();         if(a>0){             System.out.println("正数绝对值是它本身");             System.out.println(Math.abs(a));         }else if(a<p>The result of the operation is: </p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/164/168583812524231.png?x-oss-process=image/resize,p_40" class="lazy" alt="How to use the Math class in Java programming"></p> <h4 id="Maximum-value-of-Math-class">3. Maximum value of Math class</h4><p>1. The method of maximum value of Math class is to compare which of the two values ​​is larger. </p><p>2.Math class maximum value method: </p><p>public static int max(int ​​a, int b) method: Get the maximum value of two int type values;</p><p>public static float max(float a, float b) method: Get the maximum value of two float type values; </p><p>public static double max(double a, double b) method: Get the maximum value of two double type values ;</p><p>public static long max(long a, long b) method: Get the maximum value of two long type values;</p><p>3. Example of the maximum value method of Math class</p><pre class="brush:php;toolbar:false">import java.util.Scanner; public class p68 { public static void main(String[] args) {         // TODO Auto-generated method stub         System.out.println("请输入二个整数");         Scanner scan=new Scanner(System.in);         int a=scan.nextInt();         int b=scan.nextInt();         System.out.println(a+"和"+b+"的最大值是:"+Math.max(a, b));   } }

Run result:

How to use the Math class in Java programming

4. Math class minimum value

1. The Math class minimum value method is to compare two values ​​which is smaller.

2. Math class minimum value method:

public static int min(int a, int b) method: Get the minimum value of two int type values;

public static float min(float a, float b) method: Get the minimum value of two float type values;

public static double min(double a, double b) method: Get the minimum value of two double type values Value;

public static long min(long a, long b) method: Get the minimum value of two long type values;

3.Math class minimum value method example:

import java.util.Scanner; public class p69 { public static void main(String[] args) {         // TODO Auto-generated method stub         System.out.println("请输入二个整数");         Scanner scan=new Scanner(System.in);         int a=scan.nextInt();         int b=scan.nextInt();         System.out.println(a+"和"+b+"的最小值是:"+Math.min(a, b));   } }

The result of the operation is:

How to use the Math class in Java programming

The above is the detailed content of How to use the Math class in Java programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor