JAVA basics 3: Arithmetic Operators

Source: Internet
Author: User

JAVA basics 3: Arithmetic Operators

 

This article mainly introduces the operation operations in Java. It is the responsibility of every programmer to correctly use operators to prevent overflow.

1. Arithmetic Operations

Java supports the following arithmetic operations:

Operator Description Use Example
* Multiplication Expr1 * expr2 2*3 → 6
3.3*1.0 → 3.3
/ Division Expr1/expr2 1/2 → 0
1.0/2.0 → 0.5
% Remainder Expr1 % expr2 5% 2 → 1
-5% 2 →-1
5.5% 2.2 → 1.1
+ Addition (positive) Expr1 + expr2
+ Expr
1 + 2 → 3
1.1 + 2.2 → 3.3
- Subtraction (minus sign) Expr1-expr2
-Expr
1-2 →-1
1.1-2.2 →-1.1
2. arithmetic expressions

For the following expression:

Convert to encoding (1 + 2 * a)/3 + (4 * (B + c) * (5-d-e)/f-6 * (7/g + h ), note that the multiplication number (*) cannot be omitted (*).

Priority:
  • Multiplication (*), Division (/), and remainder (%) take precedence over addition (+) and subtraction, for example, 1 + 2*3-4/2 can be expressed as 1 + (2*3)-(4/2 ).
  • The positive signs (+) and negative signs (-) have higher levels.
  • Brackets () have the highest level and are often used to adjust the operation sequence.
  • For operators of the same level, the expression result is calculated from left to right. For example, 1 + 2-3 + 4 is equivalent to (1 + 2)-3) + 4, 1*2% 3/4 is equivalent to (1*2) % 3)/4. 3. Hybrid Operation

    Arithmetic operations are only applicable to basic types: byte, short, int, long, float, double, and char, excluding boolean.

    If the two operands are of the int, long, float, or double type, the operation directly uses this type for calculation, for example, int 5 + int 6 → int 11; double 2.1 + double 1.2 → double 3.3.

    It is worth noting that for the division operation of int, the calculation result will be truncated, for example, 1/2 → 0 rather than 0.5.

    If the two operands are of the byte, short, or char type, the operation uses the int type for calculation, and the char is converted to a 16-bit unsigned integer, for example, byte 127 + byte 1 → int 127 + int 1 → int 128.
    If the two operands belong to different types, the smaller types are implicitly converted to larger types, and the calculation operation uses larger types for calculation.

    Example:
    • Int/double → double, 1/2 → 0, 1.0/2.0 → 0.5, 1.0/2 → 0.5, 1/2. 0 → 0.5.
    • Char + float → int + float → float.
    • 9/5*20.1 → (9/5) * 20.1 → 1*20.1 → 1.0*20.1 → 20.1 (You may not think of this answer ).
    • Byte 1 + byte 2 → int 1 + int 2 → int 3 (the result is int, not byte ).

      The conversion of binary operation types is summarized as follows:

      • If one of the operands is double, the other operand is converted to double by default.
      • If one of the operations is float, the other operations are converted to float by default.
      • If one of the operands is long, the other operands are converted to long by default.
      • The rest of the operands are converted to int by default.

        The type conversion of the mona1 operation (positive and negative) is summarized as follows:

        • If the operand is double, float, long, or int, no conversion is required.
        • If the remaining values are byte, short, or char, they are converted to int by default. Example:
          Byte b1 = 1; byte b2 =-b1; // compilation will fail, because-b1 will return int and cannot be converted to byte
          Remainder Operator

          To calculate the remainder, the subtraction operation is repeated until the absolute value of the difference value is smaller than the absolute value of the right operand. For example:

          • -5% 2? -3% 2? -1
          • 5.5% 2.2? 3.3% 2.2? 1.1 Index

            There is no exponential operator in Java. The '^' operator you see is an exclusive or. However, you can use Math. exp (X, Y) to perform an exponential operation.

            4. Overflow up/down

            Study the following code and explain the output:

            /** "Int" overflow Description */public class OverflowTest {public static void main (String [] args) {// int value range [-2147483648,214 7483647] int i1 = 2147483647; // int maximum value System. out. println (i1 + 1); //-2147483648 (overflow) System. out. println (i1 + 2); //-2147483647 System. out. println (i1 * i1); // 1 int i2 =-2147483648; // int minimum value System. out. println (i2-1); // 2147483647 (overflow) System. out. println (i2-2); // 2147483646 System. out. println (i2 * i2); // 0 }}

            Java will not issue errors or warnings for overflow during the operation, but will produce incorrect results.
            On the other hand, Integer Division produces truncated integers, which are called downward overflow, for example, 1/2 → 0, rather than 0.5.
            As a programmer, you have the responsibility to check for program overflow.
            At this time, we may ask why the computer does not mark overflow? Due to historical reasons, the processor was slow at that time, and checking overflow would consume performance.

            5. type conversion

            In Java, if the double or float data is assigned to the int variable, a compilation error occurs.

            Double d = 3.5; int I; I = d; // compilation error int sum = 55.66f; // compilation Error
            Display type conversion and type conversion

            Double is assigned to the int variable. You need to convert the display type in the form of (int) value. The returned result is the truncated int data. For example:

            Double d = 3.5; int I; I = (int) d; // convert 3.5 of the double type to 3 of the int type, and assign it to I

            Only one operand is required for type conversion. There are two types of conversion in Java:

            • Converts the display type in the form of (new-type) operands.
            • If there is no missing precision, the compiler automatically performs implicit conversions.
              Int I = 3; double d; d = I; // correct, no type conversion required, d = 3.0d = (double) I; // You can also use the display type to convert double aDouble = 55; // The Compiler automatically converts int 55 to double 55.0 double nought = 0; // The Compiler automatically converts int 0 to double 0.0 // It is worth noting that int 0 and double 0.0 are different.

              The following figure shows the sequence of implicit type conversion in the compiler. The conversion rule is to promote small types to large types, so as to prevent missing precision. Type conversion is required for downgrading. The precision is missing. It is worth noting that char is regarded as a 16-bit unsigned integer with a value range of [0, 65535]. conversion is not supported for the boolean type.

              For example, calculate the average value from 1 to 100, and carefully study the following code

              Public class Sum1To100 {public static void main (String [] args) {int sum = 0; double average; int number = 1; while (number <= 100) {sum + = number; // The final result of sum is int 5050 + + number;} average = sum/100; // average = 50.0 instead of 50.5 System. out. println ("Average is" + average); // The Average value is 50.0 }}

              This is because both sum and 100 are of the int type. In addition, the return value is the truncated int. To get the correct result, you can use the following method:

              Average = (double) sum/100; // convert sum to double type average = sum/(double) 100 displayed before division; // before division, convert 100 to double average = sum/100.0; average = (double) (sum/100); // this operation is incorrect, do you know why?
              6. Compound value assignment

              In addition to the commonly used value assignment = described above, Java also provides other compound value assignment operations:

              Operator Explanation Use Example
              = Assignment
              Assign the right operand to the left operand
              Var = expr X = 5;
              + =

              Compound addition operation

              Var + = expr
              Equivalent to var = var + expr
              X + = 5;
              Equivalent to x = x + 5
              -= Compound Subtraction Var-= expr
              Equivalent to var = var-expr
              X-= 5;
              Equivalent to x = x-5
              * = Compound Multiplication Var * = expr
              Equivalent to var = var * expr
              X * = 5;
              Equivalent to x = x * 5
              /= Compound Division Var/= expr
              Equivalent to var = var/expr
              X/= 5;
              Equivalent to x = x/5
              % = Compound remainder operation Var % = expr
              Equivalent to var = var % expr
              X % = 5;
              Equivalent to x = x % 5
              7. Auto-increment/auto-Increment

              For unary operations such as auto-increment (++) and auto-increment (--), it is applicable to other basic types of bytes, short, char, int, long, float, and double except boolean.

              Operator Explanation Example
              ++ Add 1 to the original value
              X ++ or ++ x is equivalent to x + = 1 or x = x + 1.
              Int x = 5;
              X ++;
              ++ X;
              -- The original value minus 1
              X -- or -- x is equivalent to x-= 1 or x = x-1.
              Int y = 6;
              Y --;
              -- Y;

              Auto-increment and auto-increment are based on their own operations. For example, x ++ auto-increment is returned to x again.
              The auto-increment/auto-increment operators can be placed before or after the operands, but they have different meanings.

              If these operators are based on their own operations, the front and back of the operators have the same effect, for example, ++ x and x ++, because the values of the expressions are ignored.
              If it is used for other operations, such as y = x ++ or y = ++ x, there are different values before and after the operator for the y value.

              Operator Explanation Example
              ++ Var Auto-Increment
              First, add var and 1. The calculation result is var.
              Y = ++ x;
              Equivalent to x = x + 1; y = x;
              Var ++ Auto-Increment
              First, use var for the calculation result, and then add 1 to var.
              Y = x ++;
              It is equivalent to oldX = x; x = x + 1; y = oldX;
              -- Var Auto-Subtraction Y = -- x;
              Equivalent to x = X-1; y = x;
              Var -- Auto-Subtraction Y = x --;
              Equivalent to oldX = x; x = X-1; y = oldX;
              8. Relational and logical operators

              In many cases, you need to compare the two values before performing some operations. For example, if the mark value is greater than or equal to 50, the output "PASS! ".
              Java provides six comparison operators. After comparison, the return value is true or false.

              Operator Explanation Use Example (x = 5, y = 8)
              = Equal Expr1 = expr2 (X = y) → false
              ! = Not equal Expr1! = Expr2 (X! = Y) → true
              > Greater Expr1> expr2 (X> y) → false
              > = Greater than or equal Expr1> = expr2 (X> = 5) → true
              < Less Expr1 (Y <8) → false
              <= Less than or equal Expr1> = expr2 (Y <= 8) → true

              Each comparison operator requires two operands. The correct syntax is x> 1 & x <100, and the incorrect syntax is 1 <x <100, where & indicates and operates.
              Java provides four logic operations based on boolean. The priority order is as follows:

              Operator Explanation Use
              ! Non-logical ! BooleanExpr
              ^ Logic exclusive or BooleanExpr1 ^ booleanExpr2
              && Logic and BooleanExpr1 & booleanExpr2
              | Logic or BooleanExpr1 | booleanExpr2

              The truth table is as follows:

              And (&&) True False
              True True False
              False False False
                   
              Or (|) True False
              True True True
              False True False
                   
              Non (!) True False
              Result False True
                   
              XOR (^) True False
              True False True
              False True False

              Example:

              // If the value range of x is [0,100], true (x> = 0) & (x <= 100) is returned. // if the value range of x is not [0,100], returns true (x <0) | (x> 100 )! (X> = 0) & (x <= 100) // determines whether the calculation is a leap year. A year is 4, but cannot be divisible by 100, or be divisible by 400 (year % 4 = 0) & (year % 100! = 0) | (year % 400 = 0)

              Exercise: Study the following program and explain the output.

              public class RelationalLogicalOpTest {   public static void main(String[] args) {      int age = 18;      double weight = 71.23;      int height = 191;      boolean married = false;      boolean attached = false;      char gender = 'm';      System.out.println(!married && !attached && (gender == 'm'));      System.out.println(married && (gender == 'f'));      System.out.println((height >= 180) && (weight >= 65) && (weight <= 80));      System.out.println((height >= 180) || (weight >= 90));   }}
              Exercise:

              Based on the provided Date: year, month (1-12) and Day (1-31), calculate whether the date is earlier than January 1, October 15, 1582.

              Operator priority

              Priority from high to low :'! ',' ^ ',' & ',' | '. If you are not sure about programming, use parentheses ().

              System. out. println (true | true & false); // true (same as the following) System. out. println (true | (true & false); // trueSystem. out. println (true | true) & false); // falseSystem. out. println (false & true ^ true); // false (same as the following) System. out. println (false & (true ^ true); // falseSystem. out. println (false & true) ^ true); // true
              Short-circuit Operator

              Logic and (&) and logic or (|) are called short-circuit operators. This means that if the calculation result can be determined by the left operand, the right operand is ignored, for example, false &&... returns false, true |... returns true.


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.