What you don't know, the secret of Java operators?

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise bitwise operators integer division

In the process of Java programming, our processing of data is implemented by operators. For example, an assignment operator for assignment, an operator for an operation, and a comparison operator for comparison, including logical operators, bitwise operators, shift operators, ternary operators, and so on. There are many kinds of operators and different usages, let's take a look at the various Java operators, some of which deserve our special attention.

Assignment operator

For the assignment operation, I believe we all play very well, for example, to assign a value to the basic data type,

521;

In "Object ramble," We know that the basic data types are stored on the stack, not new out. In addition, the base data type stores the actual numeric value, not the reference to the object, so when it is assigned to it, it copies the contents of one place directly to a different place. When assigning a value to an object, we are actually a reference to an object that assigns a reference to another object, so that two objects point to the same piece of storage space through the same reference. Interested students, you can run the following program to test,

Package Com.hit.chapter3;/** * author:charies Gavin * date:2017/12/09,12:40 * https:github.com/guobinhit * Description: Test assignment operator */PublicClassAssignmentoperator {PublicStaticvoidMainString[] (args) {Create two objects Apple Apple1 =New Apple ("Green"); Apple Apple2 =New Apple ();Outputs two initialization objects, apple1 initializes color to Green,apple2 to initialize the color null System.Out.println ("Initial:apple1 color is" + Apple1.color +", Apple2 color is" + apple2.color);Assign the Apple1 reference to apple2 apple2 = Apple1; (Java Learning Group 669823128)//output two objects after assignment, two objects have the same reference System. out.println ( "Assignment:apple1 color is" + Apple1.color + //modify apple2 Reference apple2.color =  "red"; //output Apple2 modified two objects, two objects are changed by System. out.println ( "Modify:apple1 color is" + Apple1.color + class apple {//member variable String color; Span class= "hljs-comment" >/** * default constructor */Apple () {} /** * Parameter builder * * @param color */apple (stri ng color) {this.color = Color;}}         

As shown, when we assign an object apple1 to an object apple2 , two objects have the same reference, so after we modify apple2 the value, apple1 the value is also affected, which we call "the same name phenomenon." If you want to avoid the same name phenomenon above, we can modify the assignment code to

Apple2.color = Apple1.color;

In this case, we are only assigning values to values apple1 color instead of apple2 color manipulating object references.

Arithmetic operators

In Java's arithmetic operators, the division () of integers omits the decimal digits of the / result, rather than rounding it.

Package Com.hit.chapter3;import Java.util.Random;/** * author:charies Gavin * date:2017/12/09,13:50 * https:github.com/guobinhit * Description: Test arithmetic operator */PublicClassArithmeticoperator {PublicStaticvoidMainstring[] args) {/** * test for random integer division */Randomdivide ();} /** * Random integer Division */private static void randomdivide (new random (); int x = Random.nextint (10) + 1; int y = random.nextint (10) + 1; int z = x/y; System. out.println ( "integer division, default omitted decimal digits of the result:" + x +  "=" + Z);}}       

As shown above, we created a random integer division and tested that integer division would default to omitting the decimal place of the result. In the randomDivide() method, we used the Random class, and if we Random didn't pass in any parameters when we created the object, then Java would use the current time as the seed of the random number generator, so we would get different results each time we executed the program. Where the seed of the random number generator is used for the initialization value of the random number generator, the same random number sequence is always produced for the same seed. In addition, when we call the nextInt() method, we do the +1 operation, because the parameters passed to nextInt() the set can produce the upper limit of the random number, and its lower bound is 0 , the lower limit can be taken, the upper limit cannot be taken, so +1 the operation can prevent 0 the divisor of the case 。

In arithmetic operators, the unary minus sign ( - ) and the unary plus sign () and the + two-dollar minus sign and the two-dollar plus sign all use the same symbol. Depending on how the expression is written, the compiler automatically determines which arithmetic operator to use. Where the unary minus is used to transform the symbol of the data, and the unary Plus is just for the unary minus relative to, it ( + ) only function is to promote the smaller type of operand to the int type .

In addition, there are two special operators in arithmetic operators, that is increment ( ++ ) and decrement ( -- ), increment and decrement operators not only change the variable, but also take the value of the variable as the result of its production. For prefix increment and decrement of prefix (such as i++ or i-- ), the operation is performed first, and then the value is generated, and for the suffix increment and suffix decrement (for example, ++i or --i ), the value is calculated, and then the operation is performed.

Relational operators

In the Java language, relational operators include,,,, and, among > < >= <= == != Other things, the resulting boolean type, with two relational operators that require our special attention, that is, == and , perform the following procedure to test:

Package Com.hit.chapter3;/** * author:charies Gavin * date:2017/12/10,14:43 * https:github.com/guobinhit * Description: Test relational operator */PublicClassRelationoperator {PublicStaticvoidMainString[] (args) {Create two integer object integer i1 =New Integer (521); Integer i2 =New Integer (521);Call two private static methods to compare and Judge Equivalentoperator (I1, I2); Equalsfunction (I1, I2); }/** * Compare two objects with an identity operator * * @param O1 * @param O2 */PrivateStaticvoidEquivalentoperator (Object O1, Object O2) {System.Out.println (O1 +"= =" + O2 +":" + (O1 = = O2)); System.out.println (O1 +  "! =" + O2 +  ":" + (O1 ! = O2)); } /** * Compare two objects with the Equals () method * * @param O1 * @param o2 * private static void equalsfunction (object O1, Object O2) {System.out.println (" ("+ O1 + ") equals ("+ O2 + equals (O2)); System. out.println ( "! (" + O1 +  ") Equals (" + O2 +  "):" + (! ( O1). equals (O2)); }} 

As shown above, we created two Integer types of objects, which were compared by relational operators, and found that the results were surprisingly, and that two Integer types 521 were judged to be false unequal. In fact, this is normal, because == and != compared to the object reference , we new created two Integer types of objects, although the contents of the two objects are the same, but they have different storage space on the heap, also have different object references. By equalsFunction Testing the tests, we found that the method of calling the java.lang package (the default import) equals() can correctly compare the contents of two objects. But, the following procedure may be to make us skeptical about the previous judgment,

Package Com.hit.chapter3;/** * author:charies Gavin * date:2017/12/10,14:43 * https:github.com/guobinhit * Description: Test relational operator */PublicClassRelationoperator {PublicStaticvoidMainString[] (args) {Create two custom Cartoon objects Cartoon C1 =New Cartoon (); Cartoon C2 =New Cartoon ();Assigns a value of two Cartoon objects c1.name = C2.name ="Naruto";Call the Equals () method to compare Equalsfunction (c1, C2); }/** * Compare two objects with the Equals () method * * @param O1 * @param o2 */private static void equalsfunction (object O1, Object O2) {System.out.println (" ("+ O1 + ") equals ("+ O2 + equals (O2)); System. out.println ( "! (" + O1 +  ") Equals (" + O2 +  "):" + (! ( O1). equals (O2)); }}/** * Custom cartoon class */class Cartoon { String name,                

As shown above, we created two custom classes of objects, and then the same equals() way to compare two objects containing the same content, the result is false ? Isn't it a good equals() way to compare the contents of an object? How can you be beaten face in a blink of an eye? Well, here's a fix, the equals() default method is to compare references to Objects , but in most Java class libraries, methods are implemented to equals() compare the contents of an object, rather than a reference to a comparison object. Therefore, if we want to use equals() methods to compare the contents of our custom types instead of references, we need to override the Object methods in the class (the ultimate root Class), and we recommend overriding the methods while equals() overriding equals() the methods hashCode() . Here equals() is an example of a simultaneous overlay hashCode() :

/** * Custom Cartoon class * *ClassCartoon {String name;/** * Overwrite the Hashcode () method in the Object root class *@return Hash value * /@Override public int hashcode () { return Name.hashcode ();} /** * overrides the Equals () method in the Object root class * @param o * @return True or False */ @Override public Boolean equals (Object o) { if (o instanceof Cartoon) { if (this.name.hashCode () = = ((Cartoon) O). Name.hashcode ()) return TR Ue return false;} else { return false;              }}} 

Here, it is strongly recommended that you do not use the == operator to detect the equality of two strings ! Because == the operator can only determine whether two strings are placed in the same position. Of course, if two strings are placed in the same position, they are necessarily equal, but it is entirely possible to place the copy locations of multiple strings of the same content in different locations. If the virtual machine always shares the same string, you can use an == operator to detect whether two strings are equal. In practice, however, only string constants are shared .

Other operators

In logical operators, with ( && ), or ( || ), non-() ! operations can only be used for Boolean values. If String A Boolean value is used where the value should be used, the Boolean value is automatically converted to the appropriate text form. For Boolean values, the bitwise operator and the logical operator have the same effect, except that the bitwise operator does not "short-circuit" halfway.

In shift operators, if char , byte or type, short the values are shifted, they are converted to types before they are shifted, and the resulting int result is int the value of the type. For binary numbers, if the highest (first) digit (the sign bit) is 0 , then a positive number; Yes 1 , negative.

When performing arithmetic operations on basic data types or bitwise operations, these values are automatically converted to types, as long as the types are int smaller (i.e. char , byte or short ) int . Typically, the largest data type that appears in an expression determines the data type of the result of the expression.

If an expression begins with a string, all subsequent operands must be of the string type, and if subsequent operands are not string, they are automatically converted to a string type, and the compiler automatically converts the sequence of characters within the double quotation marks to a string.

When you convert float or double transform to an integer value, you always perform a truncated operation on that number. If you want to get rounded results, you need to use java.lang.Math the round() method in. booleaIn addition to classes, any basic data type can be converted to another base type by type conversion.

In addition, when using the exponential notation, for example

5.21e2f;

The editor usually double handles the exponent as a double-precision number () , and if it does not follow the initialization value, the F compiler will give an f error, prompting us to use the type conversion to double convert to a float type.

Java Learning Group 669823128

What you don't know, the secret of Java operators?

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.