C # Operator 2 Arithmetic Operator

Source: Internet
Author: User
Tags arithmetic operators

The assignment operator is also used together with the arithmetic operator. It is mentioned in the appendix earlier. For example, to add x to 4 and then assign the value to x, you can write it as x + = 4.

Copy codeThe Code is as follows: public class MathOps {
Public static void main (String [] args ){
Random rand = new Random (47 );
Int I, j, k;
J = rand. nextInf (100) + 1;
System. out. println ("j:" + j );
K = rand. nextInt (100) + 1;
System. out. println ("k:" + k );
I = j-k;
System. out. println ("j-k:" + I );
I = k/j;
System. out. println ("k/j:" + I );
I = k * j;
System. out. println ("k * j:" + I );
J % = k;
System. out. println ("I % = k:" + j );
Float u, v, w;
V = rand. nextFloat ();
System. out. println ("v:" + v );
W = rand. nextFloat ();
System. out. println ("w:" + w );
U = v + w;
System. out. printlln ("v + w:" + u );
U = v-w;
System. out. println ("v-w:" + u );
U = v * w;
System. out, print ("v * w" + u );
U = v/w;
System. out. print ("v/w:" + u );
U + = v;
System. out. print ("u + = v:" + u );
U-= v;
System. out. print ("u-= v:" + u );
U * = v;
System. out. print ("u * = v:" + u );
U/= v;
System. out. print ("u/= v:" + u );
}
}

Output:
J: 59;
K: 56;
J + k: 115;
J-k: 3;
K/j: 0;
K * j: 3304;
K % j: 56;
J % = k: 3;
V: 0.5309454;
W: 0.0534122
V + w: 0.5843576
V-w: 0.47753322
V/w: 0.028358962
V/ w: 9.94025
US + = v: 10.471473
U-= v: 9.940527
US * = v: 5.2778773
US/= v: 9.940527
Through the Random class object, the program can generate many different types of Random numbers. The procedure is simple. You only need to call the nextInt () and nextFloat () methods (or nextLong () or nextDouble ()). The parameter passed to nextInt () sets the upper limit of the generated random number, and its deprecation is 0, but this deprecation is not what we want, because it will produce the possibility of division by 0, so we performed the + 1 operation.
In The unary operator, the compiler automatically determines the role of + and -.
For example, x = a *-B; the compiler can compile its meaning. B, the minus sign is a negative number, but the best way to avoid confusion is
X = a * (-B)
The unary minus sign is used to change the data symbol, while the unary plus sign is only used to correspond to the unary minus sign, but its only function is to increase the operand of a smaller type to int;
Arithmetic Operators

Operator

Use

Description

+

Op1 + op2

Returns the sum of op1 and op2.

-

Op1-op2

Returns the difference between op1 and op2.

*

Op1 * op2

Returns the product of op1 and op2.

/

Op1/op2

Returns the operator whose op1 is divided by op2.

%

Op1 % op2

Returns the remainder of op1 divided by op2.

Auto increment and decrease
The increment and decrement operations provided in Java are quite good and fast (usually called "auto increment" and "auto-incrementing" operations ). The decimal operator is "--", meaning that a unit is reduced for private affairs. The increment operator "++" means adding a unit.
++ A is equivalent to a = a + 1.
Increment and decrease are divided into prefix and suffix ".
For Prefix: ++ a, -- a, the operation is executed first and then the value is generated. For suffixes like a ++ and a --, the operation is executed.Copy codeThe Code is as follows: public class AutoInc {
Public static void main (String [] args ){
Int I = 1;
System. out. println ("I:" + 1 );
System. out. println ("++ I:" ++ I );
System. out. println ("I ++:" + I ++ );
System. out. println ("-I:" + -- I );
System. out. println ("I --:" + I --);
}
}

Output
I: 1
++ I: 2
I ++: 2
-- I: 1
I --: 1
In the above example, you can read the difference between prefix and suffix.
The incrementing operator is an explanation of the name c ++, "beyond step c"
Relational operators
Relational operators generate a boolean result. If the result of comparing values is true, true is returned. If the result is false, false is returned. Relational operators include <, >,< =,> =, = ,! = (Not equal to), equals and not equal are suitable for all basic data types, while other operators are not suitable for operations on boolean values, because the relationship between true and false is not greater than or lessCopy codeThe Code is as follows: public class Equivalence {
Public static void main (String [] arg ){
Integer n1 = new Integer (47 );
Integer n2 = new Integer (47 );
System. out. println (n1 = n2 );
System. out. println (n1! = N2 );
}
}

Output
False
True
The result may be different from what you think. Although the object content is the same here, the object reference is different, and = and! = Compare the object reference, not the content.
What should I do if the actual content of the two objects is the same? You need to use the equals () method applicable to all objects. However, this method does not apply to basic types. For basic types, use = directly ,! =Copy codeThe Code is as follows: public class internal method {
Public static void main (String [] args ){
Integer n1 = new Integer (47 );
Interger n2 = new Integer (47 );
System. out. println (n1.equals (n2 ));
}
}

Output
True
However, if the referenced object is a self-created class, the result will be different.Copy codeThe Code is as follows: class Value {
Int I;
}
Public class extends smethod2 {
Public static void main (String [] args ){
Value v1 = new Value ();
Value v2 = new Value ();
V1. I = v2. I = 100;
System. out. println (v1.equals (v2 ));
}
}

Output
False
The result is false because equals is actually a comparison reference by default. Therefore, unless you re-write the equals method in your new class, the expected effect cannot be achieved.
Relational operators

Operator

Use

Description

>

Op1> op2

Returns true if op1 is greater than op2.

> =

Op1> = op2

Returns true if op1 is greater than or equal to op2.

<

Op1 <op2

Returns true if op1 is smaller than op2.

<=

Op1 <= op2

Returns true if op1 is smaller than or equal to op2.

=

Op1 = op2

Returns true if op1 is greater than op2.

! =

Op1! = Op2

Returns true if op1 is not equal to op2.

Logical operators
Logical operators and (&), or (|), not (!) Returns a Boolean value based on the relationship between parameters.Copy codeThe Code is as follows: public class Bool {
Public static void main (String [] args ){
Random rand = new Random (47 );
Int I = rand. nextInt (100 );
Int j = rand. nextInt (100 );
System. out. println ("I =" + I );
System. out. println ("j =" + j );
System. out. println ("I> j is" + (I> j ));
System. out. println ("I <j is" + (I <j ));
System. out. println ("I> = j is" + (I> = j ));
System. out. println ("I <= j is" + (I <= j ));
System. out. println ("I = j is" + (I = j ));
System. out. println ("I! = J is "+ (I! = J ));
System. out. println ("(I <10) & (j <10) is" + (I <10) & (j <10 )));
System. out. println ("(I <10) | (j <10) is" + (I <10) | (j <10 )));
}
}

Output
I = 58
J = 55
I> j is true
I <j is false
I> = j is true
I <= j is false
I = j is false
I! = J is true
(I <10) & (j <10) is false
(I <10) | (j <10) isfalse
And or non-operations can only be applied to boolean values. If boolean is used where it should be a String value, the boolean value is automatically converted to an appropriate form.
It should be noted that the program comparison of floating point numbers is very strict.
Conditional Operators

Operator

Use

Description

&&

Op1 & op2

If op1 and op2 are both true, true is returned. If op1 is false, the right operand is not calculated.

|

Op1 | op2

If one of op1 and op2 is true, true is returned. If op1 is true, the right operand is not calculated.

!

! Op

If op is false, true is returned. If op is true, false is returned.

&

Op1 & op2

Operation op1 and op2; If op1 and op2 are both boolean values and both are true, true is returned; otherwise, false is returned. If op1 and op2 are both numbers, bit and Operation

|

Op1 | op2

Operation op1 and op2; If op1 and op2 are both boolean values and one is equal to true, true is returned; otherwise, false is returned. If op1 and op2 are both numbers, the bitwise OR operation is performed.

^

Op1 ^ op2

Operation op1 and op2; If op1 and op2 are different, that is, if one is true and the other is not, true is returned; otherwise, false is returned. If op1 and op2 are both numbers, the bitwise XOR operation is performed.

Short Circuit
When using logical operators, a short circuit is encountered. Once the value of the entire expression is clearly determined, the remaining part of the expression is no longer calculated. Therefore, the back part of the entire logical expression may not be computed. The following example shows the short circuit.Copy codeThe Code is as follows: public class ShortCircuit {
Static Boolean test1 (int val ){
System. out. println ("test1 (" + val + ")");
System. out. println ("result:" + (val <1 ));
Return val <1
}
Static Boolean test2 (int val ){
System. out. println ("test1 (" + val + ")");
System. out. println ("result:" + (val <2 ));
Return val <2
}
Static Boolean test3 (int val ){
System. out. println ("test1 (" + val + ")");
System. out. println ("result:" + (val <3 ));
Return val <3
}
Public static void main (String [] args ){
Boolean B = test1 (0) & test2 (2) & test3 (2 );
System. out. println ("expression is" + B );
}
}

Output
Test1 (0)
Result: true
Test (2)
Result: false
Expression is false
Because you call three methods, you will naturally feel that all three methods should be run, but the output is not actually like this, because a false result is generated in the second test. This means that the entire expression must be false, so there is no need to continue to calculate the remaining expressions, which is just a waste. This is the reason for a "Short Circuit. In fact, all logical expressions do not have to be computed, which improves performance.
Ternary Operators
The ternary operator is also a conditional operator. It seems special because it has three operands, but it does belong to one of the operators.
The format is
Boolean-exp? Value0: value1
If the boolean-exp expression returns true, value0 is calculated, and the calculation result is the final value produced by the operator. If the boolean-exp expression returns false, value1 is calculated. Similarly, the result is the final value of the operator.
Of course, it can also be replaced by if-else, but the ternary operator and if-else are completely different, and the operator will generate a value.Copy codeThe Code is as follows: public class TernaryIfElse {
Static int ternary (int I ){
Return I <10? I * 100: I * 10;
}
Static int standardIfElse (int I ){
If (I <10)
Return I * 100;
Else
Return I * 10;
}
Public static void main (String [] args ){
System. out. println (ternary (9 ));
System. out. println (ternary (10 ));
System. out. println standardIfElse (9 ));
System. out. println standardIfElse (10 ));
}
}

Output
900
100
900
100
In contrast, the ternary operators are much more compact, and if-else is easier to understand.
String operator + and + =
In Java, the ++ and ++ = operators can be used as character links in special context, in addition to the functions described earlier. So they are also called string operators, which have some interesting behaviors. If the expression starts with a string, all subsequent operands must be string type (the compiler automatically transmits the Character Sequence in double quotation marks to a string ):Copy codeThe Code is as follows: public class StringOperators {
Public static void main (String [] args ){
Int x = 0, y = 1, z = 2;
String s = "x, y, z ";
System. out. println (s + x + y + z );
System. out. println (x + "" + s );
S + = "(summed) = ";
System. out. println (s + (x + y + z ));
System. out. println ("" + x );
}
}

Output
X, y, z 012
0 x, y, z
X, y, z (summed) = 3
0
It should be noted that the first line outputs 012 rather than sum 3, because the compiler automatically converts them into the string form, and the last part appends a string to s with ++ =, in addition, brackets are used to control the compiler conversion so that they can sum smoothly.

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.