Java BASICS (7): java Basics

Source: Internet
Author: User

Java BASICS (7): java Basics
I. Introduction to Math class 1 and Math class

The Math class is under the java. lang Package and contains methods used to perform basic mathematical operations, such as Elementary Indexes, logarithm, square root, and trigonometric functions. This class is modified by final.

Common fields:

1. E indicates the base number of the natural logarithm of 2.71828.

2. The week indicates the circumference rate is 3.1415926.

2. Common Math methods

The following X indicates double, float, int, long

1,Abs(X x): returns the absolute value, for example, static double abs (double ).

2,Max(X x1, X x2): calculate the maximum value, for example, static double max (double a, double B.

3,Min(X x1, X x2): minimum value.

4,Pow(Double a, double B) returns the power of the first parameter.

5,Random(): Returns the number between 0 and 1,Double type.

6. public static intRound(Float a): returnsint. The result will be rounded to an integer: Add 1/2, call the floor for the result and forcibly convert the resultintType.

Public static longRound(Double a): returnslong. The result will be rounded to an integer: Add 1/2, call the floor for the result and forcibly convert the resultlongType.

7. public static doubleSqrt(Double a): returns the correctly roundeddoubleThe positive square root of the value.

Ii. BigInteger and BigDecimal Classes 1. BigInteger

An integer of any precision that is not changeable. In all operations, BigInteger (such as the basic integer type of Java) is expressed in the form of binary complement ). BigInteger provides the counterparts of all basic integer operators in Java and all related methods of java. lang. Math. BigInteger also provides the following operations: modulo arithmetic, GCD calculation, prime number testing, prime number generation, bit operations, and some other operations.

BigInteger is similar to long.

BigInteger method:

1. BigIntegerAdd(BigInteger val );

Return the BigInteger whose value is (this + val) (the current object is added with the input object, and a new value is returned ).

2. BigIntegerMultiply(BigInteger val );

Return the BigInteger whose value is (this * val.

3. BigIntegerDivide(BigInteger val );

Return the BigInteger whose value is (this/val.

2. BigDecimal class

Immutable, any-precision signed decimal number.BigDecimalInteger with any precisionNon-standard valueAnd 32-bit IntegersScale(Scale. If it is zero or positive, the scale is the number of digits after the decimal point. If it is a negative number, the non-standard degree value of this number is multiplied by the negative scale power of 10. Therefore,BigDecimalThe value is(UnscaledValue × 10-scale).

BigDecimal can accurately represent a decimal.Business and scientific computing; Float, double cannot accurately represent a decimal point.

The BigDecimal class is similar to the BigInteger class, for exampleAdd(Addition ),Multiply(Multiplication)Divide(Division ).

1 import java. math. bigDecimal; 2 3 public class BigDecimalTest {4/** 5 * inaccurate calculation 6 */7 @ Test 8 public void test1 () {9 System. out. println (0.05 + 0.01); // output: 0.06000000000000000510 System. out. println (1.0-0.42); // output: 0.580000000000000111 System. out. println (4.015*100); // output: 401.4999999999999412 System. out. println (123.3/100); // output: 1.232999999999999913} 14 15/** 16 * use BigDecimal. The parameter type is double, the calculation is still inaccurate. 17 */18 @ Test19 public void test2 () {20 BigDecimal b1 = new BigDecimal (0.05); 21 BigDecimal b2 = new BigDecimal (0.01); 22 System. out. println (b1.add (b2); // output: 0.0600000000000000029837243786801082023885101079940795898437523} 24 25/** 26 * use BigDecimal. The parameter type is String, the calculation result is accurate to 27 */28 @ Test29 public void test3 () {30 BigDecimal b1 = new BigDecimal ("0.05"); 31 BigDecimal b2 = new BigDecimal ("0.01 "); 32 System. out. println (b1.add (b2); // output: 0.0633} 34}
3. Summary

BigInteger and BigDecimal have many commonalities:

1. BigInteger and BigDecimal are subclasses of Number, indicating the Number type.

2. Integer is the int packaging class. BigInteger, BigDecimal have no relationship with Integer. BigInteger and BigDecimal are both of the same level and are subclasses of Number.

3. Although BigInteger and BigDecimal are both numeric reference types, they cannot use basic operators (such as +,-, *,/). They must be computed using special methods.

Iii. Random Number 1. method for obtaining random numbers

1. Math.Random()

Returns a positive double value. The value must be greater than or equal to 0.0 and less than 1.0. (Return Value: double, range: [0.0, 1.0 )).

2. A Random class is provided separately in Java.

IntNextInt() Returns the next pseudo-random number, which is the int value uniformly distributed in the sequence of the random number generator. (Random int value is obtained within the entire int range ).

IntNextInt(Int n) returns a pseudo-random number, which is an int value that is evenly distributed between 0 (inclusive) and specified value n (excluded) from the sequence of the random number generator. (Obtain an int value ranging from 0 to n ).

3. Random contains a subclass (ThreadLocalRandom). You can specify the range [n, m) to be left closed and right open.

4. Unique UUID

1 import java. util. random; 2 import java. util. UUID; 3 import java. util. concurrent. threadLocalRandom; 4 5 public class RandomTest {6/*** 7 * test Math. random 8 */9 @ Test10 public void test1 () {11 System. out. println (Math. random (); // output: 0.464589968189838212} 13 14/** 15 * test Random Class 16 */17 @ Test18 public void test2 () {19 Random random = new Random (); 20 int nextInt1 = random. nextInt (); 21 int nextInt2 = random. nextInt (); 22 System. out. println (nextInt1); 23 System. out. println (nextInt2); 24 // Random (long seed) if the seed is a fixed value, the result is also a fixed value of 25 Random random1 = new Random (123456 ); 26 int nextInt3 = random1.nextInt (); 27 // int nextInt (int n) n must be greater than 0, returns a random number between n 28 int nextInt4 = random1.nextInt (9 ); 29 System. out. println (nextInt3); 30 System. out. println (nextInt4); // output: 431} 32 33/** 34 * test ThreadLocalRandom class 35 */36 @ Test37 public void testThreadLocalRandom () {38 // new cannot be used to create ThreadLocalRandom object 39 ThreadLocalRandom random = ThreadLocalRandom. current (); 40 int nextInt1 = random. nextInt (); 41 // nextInt (int n) n must be greater than 0, and a random number between n is returned. 42 int nextInt2 = random. nextInt (9); 43 System. out. println (nextInt1); // output: 34750064844 System. out. println (nextInt2); // output: 745} 46 47/** 48 * unique UUID 49 */50 @ Test51 public void testUUID () {52 UUID uuid = UUID. randomUUID (); 53 System. out. println (uuid); // output: 2cc14224-72e3-4e3a-8c7b-017abb433f7454} 55}
Iv. Date and Time 1. Date

Java. util. Date uses a class to represent time, which encapsulates time into a class.

1 import java. util. date; 2 3 public class DateTest {4/** 5 * Test Date 6 */7 @ Test 8 public void test1 () {9 Date date = new Date (); 10 System. out. println (date); // returns the current time 11} 12}
2. Time formatting

The subclass SimpleDateFormat of the DateFormat class

Method:

1. format (convert Date to String) String format (Date date ).

2. parse (convert String to Date) Date parse (String source ).

The time formatting method can be encapsulated into a tool class:

1 import java. text. parseException; 2 import java. text. simpleDateFormat; 3 import java. util. date; 4 import java. util. locale; 5 6/** 7 * time tool class 8 */9 public class DateUtil {10/** 11 * Format date 12 * @ param date13 * @ return14 */15 public static String DateToString (Date date) {16 SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss", Locale. CHINA); 17 String format = dateFormat. format (date); 18 return format; 19} 20 21/** 22 * String converted to Date format 23 * @ param date24 * @ return25 * @ throws ParseException26 */27 public static date StringToDate (String Date) {28 SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss", Locale. CHINA); 29 Date parse = null; 30 try {31 parse = dateFormat. parse (date); 32} catch (ParseException e) {33 e. printStackTrace (); 34} 35 return parse; 36} 37}
2. Calendar

The Calendar class is an abstract class under the java. util package. You cannot use new to create an object. You can use Calendar. getInstance () to obtain a Calendar Object ().

Calendar method:

1. public final voidSet(Int year, int month, int date)

Set calendar FieldsYEAR,MONTHAndDAY_OF_MONTH.

2. public intGet(Int field)

Returns the value of a given calendar field. In lenient mode, all calendar fields are standardized. In non-lenient mode, all calendar fields are verified. If any calendar field has a value out of the range, this method throws an exception.

1 public class DateTest {2/** 3 * Test the Calendar class 4 */5 @ Test 6 public void testCalendar () {7 Calendar ar calendar = Calendar ar. getInstance (); // create a Calendar Object. It cannot use new. It is an abstract class 8 int year = calendar. get (Calendar. YEAR); // get YEAR 9 int month = calendar ar. get (Calendar. MONTH) + 1; // obtain the first MONTH of the MONTH as JANUARY, which is 0; therefore, you need to add 110 int day = calendar ar. get (Calendar. DAY_OF_MONTH); // obtain day11 System. out. println ("current date:" + year + "year" + month + "month" + day + "); // output: current date: february 7, 2018 12 Date time = calendar. getTime (); // One-time get date 13 System. out. println (time); // Wed Feb 07 16:11:00 GMT + 08:00 201814} 15 16/** 17 * Calculation of the Calendar class 18 */19 @ Test20 public void testCalendar2 () {21 Calendar calendar = Calendar. getInstance (); 22 calendar. add (Calendar. YEAR, 1); // increase by 1 YEAR by 23 calendar. add (Calendar. MONTH, 2); // increase by 2 months 24 calendar ar. add (Calendar. DAY_OF_MONTH, 8); // increase by 8 days 25 int year = calendar. get (Calendar. YEAR); 26 int month = calendar. get (Calendar. MONTH) + 1; // obtain the first MONTH of the MONTH as JANUARY, which is 0; therefore, you need to add 127 int day = calendar ar. get (Calendar. DAY_OF_MONTH); 28 System. out. println ("current date:" + year + "year" + month + "month" + day + "); // output: current date: April 15, 2019 29} 30}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.