Thinking in Java notes (chapter III operators)

Source: Internet
Author: User
Tags arithmetic operators bitwise operators time 0

Chapter III operator 3.2 using Java operators

The operator takes one or more arguments and generates a new value. The form of the parameter differs from the normal method invocation, but the effect is the same. Common subtraction and sign are similar to other programming languages.

Some operators may have "side effects" that alter the value of the operands, and the most common use of these zoff is to produce side effects. The values produced by using such operators do not differ from those produced by operators that do not have side effects.

Almost all operators can only operate "basic type", with the exception of "=", "=", "! = ", these operators can manipulate all objects. In addition to this exception, the String class supports "+" and "+ =".

3.3 Priority level

The precedence of an operator determines the order in which each part is evaluated, and the Java heap Calculation order is specified. The simplest rule is to first multiplication and subtract, if you forget the order of precedence, you should use parentheses to identify the order of execution. For example, the following two statements:

a = x + y - 2/2 + z;b = x + (y - 2)/(2 + z);

Two calculation meanings are different.

3.4 Assigning values

The assignment uses the operator "=", meaning that the right value is copied to the left value. The right value can be any constant, variable, or expression that requires the expression to produce a value. But the left value must be a definite, named variable. can be a = 4, but not 4 = A;

The assignment to the base type is simple. The base type stores the actual numeric value directly, rather than pointing to a reference to an object, a=b between the basic types, that is, the value of B is paid to a, and the value B of a is not affected.

But when we give the object "assignment", we actually manipulate the object's reference when we manipulate an object. Actually just pass the address of the object between two references, if a=b between the two references of the same type, change the value in the object that a points to, B will also be affected, actually they point to the same piece of object memory space, as if this object memory space has two names.

class Cat {    public int age;}public class Test {    public static void main(String[] args) {        Cat hello = new Cat();        Cat kitty = new Cat();        hello.age = 1;        kitty.age = 2;        //两个引用之间的赋值,实际上指向了同一块内存空间,也就是kitty先指向的那块新建的内存空间        hello = kitty;        hello.age = 3;    }}

In the example above, two new objects were created, with Hello and Kitty two references pointing to the two objects, followed by Hello = kitty; This statement, using the Hello Reference, points to the memory that Kitty points to, changes the value of age, This is the equivalent of giving Kitty the cat another name, Hello, they are actually talking about the same thing ~. The memory that the previous Hello pointed to is actually lost and is recycled by the Java collector.

If you just want the two pointed objects to have the same age, it should be written like this hello.age = Kitty.age; Keep in mind that it is safe to operate directly on a basic type of operation.

3.5 Arithmetic operators

Java basic arithmetic operators are the same as most other programming languages. These include: +,-? *、/、%。

It is important to note that the division between integers (/) is directly stripped of the decimal place, not rounded rounding.

Java also uses a simplified notation from C and C + + to operate and assign operations at the same time, and the representation is followed by an equal sign, such as "+ =", immediately following the operator. A+=4 represents a = a + 4;

3.5.11 Yuan Plus and minus operators

That is, a unary minus "-" and a unary plus "+". For example, statements:

x = - a;x = a * -b;

The compiler automatically recognizes as X = A * (-B), a unary minus is used to transform the symbol of the data, and the unary Plus is only for the unary minus, and its only effect is to promote the smaller operand to int.

3.6 Auto Increment and decrement

Like C, Java provides a number of quick operations. Sometimes it makes the code easier to read, but sometimes it makes the code difficult to read.

The "+ +" and "self-reduction"-"-" are two fairly good shortcut operations, the former meaning "reduce a unit", the latter meaning "add a unit".
Both operators have "prefix" and "suffix", "prefix" means "+ +" before the operand, such as "++a", the first calculation of the value, and "a++" is the value of the husband, and then calculate.

a = 1;x = a++;//执行完上面一条语句,a的值为2,x为1y = --a;//在这里a的值变为1,y的值也为1;

These two operators, in addition to operators that involve assignment, have the only operator with a "side effect" that alters the operand, not just its own generated value.

3.7 Relational operators

The relational operator generates a Boolean (Boolean)-type result that calculates the relationship between the operands ' values. True, the false is false.

The equivalence of 3.7.1 objects

The following example:

public class Test{    public static void main(String[] args) {        Integer n1 = new Integer(47);        Integer n2 = new Integer(47);        System.out.println(n1 == n2);    }}

The output is false, although the objects that the two references point to have the same contents, but the objects they point to are not the same. When it comes to comparing the actual contents of two objects, apply to the equals () method, note that the base type is not applicable to equals (). If the above output
System.out.println (N1.equals (N2)), true is output.

But if it involves a class of its own definition, for example:

class A{    public int x;}public class Test{    public static void main(String[] args) {        A a1 = new A();        A a2 = new A();        System.out.println(a1.equals(a2));    }}

The output here becomes false for the following reasons.
All classes in Java are inherited from the base class of object, and a method of equals is defined in the base class of object, and the initial behavior of this method is to compare the memory addresses of the objects (that is, the comparison method of = =), but in some class libraries this method is overwritten. As string,integer,date in these classes, equals has its own implementation, and is no longer a comparison class in the heap memory of the storage address.

The following is an introduction to the implementation of equals in the integer class in the official Java documentation.

equalspublic boolean equals(Object obj)Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.Overrides: equals in class Object Parameters:obj - the object to compare with. Returns:true if the objects are the same; false otherwise.
3.8 Logical operators

Logical operator with (&&), or (| |), NON (!) Can generate a Boolean value based on the logical relationship of the parameter. Unlike C, C + +, you cannot use a non-Boolean value as a Boolean value in a logical expression. For example if (a=b), so similar as logical judgment.

3.8.1 Short Circuit

When using a logical operator, once the boolean value of the expression has been determined, the subsequent expression will not be recalculated, such as if(a>b && c>d && e>f) the expression, and if A>b is established, subsequent two expressions will no longer be compared.

3.9 Direct Constants

When using constants, you need to add appropriate hints to the compiler, such as "float f = 1F;" such as In C, C + +, and Java, there is no direct constant representation of the binary number. However, when you use the hexadecimal and octal notation, it is useful to display the results in binary form. Tobinarystring () is easy to implement by using the static method of the integer and long types. If the smaller type is passed to the Integer.tobinarystring () method, it is automatically transformed to int.

3.10 Bitwise Operators

The bitwise operator is used to manipulate a single bit in an integer base data type, which is bits. The bitwise operator performs a Boolean algebra operation on the corresponding bits in the two parameters, resulting in a final result.

The bitwise operator originates from the C language-oriented operation, which often requires direct manipulation of the hardware.

    • If the input bit is 1, the bitwise AND operator (&) generates an output bit of 1, otherwise an output bit 0 is generated;
    • But one of the two input bits is 1, then the bitwise OR operator (|) Generate an output bit 1, at the same time 0 output 0;
    • If the input bit is 1, but not all 1, the bitwise XOR operation (^) generates a 1, otherwise the output bit is 0;
    • Bitwise NON (~), also becomes the inverse operator, which belongs to the unary operator, the output bit is the opposite of the input bit.

Bitwise operators (except the unary operator (~)) can be used in conjunction with the equal sign, which is combined to assign values to operations.

We treat the Boolean type as a single-bit value that can be bitwise "and", but not bitwise "NON" (possibly to avoid confusion with logical not). When a bitwise operation is performed on a Boolean, it has the same effect as the logical operator, except that there is no short circuit in the middle.

3.11 Shift operator

The left shift operator (<<) moves the operand to the left of the operator to the left by the number of digits specified to the right of the operator (low 0). The signed right shift operator (>>) shifts the operand to the right by the number specified to the right of the operator, and the high-level complement is interpolated by the operand symbol during the move. In Java, an "unsigned" right-shift operator (>>>) is added, which uses "0 expansion", which, regardless of the symbol of the operand, is 0 high. is not in C and C + +.

The ternary operator is also a conditional operator in the following form:

boolean-exp ? value0 : value1

This means that if the value of the BOOLEAN-EXP expression is true, the ternary operator returns VALUE0, otherwise it returns value1. This operator is created by the C language.

3.13 string operator + and + =

These two operators can be used to link strings. The operator overloading (operator overloading) mechanism is introduced in C + + and operator overloading is easier to implement in Java than C + +, but because it is still too complex, Java programmers cannot be like C + + and C # Programmers to implement their own overloaded operators.

If an expression starts with a string, all subsequent operands must be of the character type (the compiler automatically converts the sequence of characters in double quotation marks into a string), and sometimes the following occurs:

int a = 1;String b = "hello";System.out.println(b + a):

Is that OK? That's because this is a simple calling method, which in this case avoids the call to the Integer.tostring () method.

3.15 Type conversion operators

The original intent of type conversion (CAST) is "model casting". At the right time, Java automatically converts one data type to another. For example, if we assign an integer value to a floating-point variable, the compiler will automatically convert int to float. If you need to perform a type conversion, you need to tell the desired data type to be inside the parentheses, and put it on the left side of the value for the type conversion.

public class Casting {    public static void main(String[] args){        int i = 200;        long lng = (long)i;    }}

In C and C + +, type conversions can sometimes be a headache, but in Java, type conversions are a more secure operation. However, if you are performing an operation called a narrowing conversion (narrowing conversion) (that is, converting a data type that can hold more information into a type that cannot hold that much information), you may lose information. The compiler will force us to display type conversions. Java allows us to convert any basic data type to other basic data types except the Boolean type. Type conversion is not allowed for the class data type. In order to convert one kind into another, special methods must be used.

3.15.1 Truncation and rounding
public static void main(String[] args) {    double above = 0.7;    float below = 0.4;    float fabove = 0.7f;    float fbelow = 0.4f;    System.out.println((int)above);    System.out.println((int)fabove);    System.out.println((int)below);    System.out.println((int)fbelow);}

The above output is 0 because the number is truncated when the float and double are transformed into int. If you want to get rounded results, you need to use the round () method in java.lang.Math :

System.out.println(Math.round(above));System.out.println(Math.round(fabove));System.out.println(Math.round(below));System.out.println(Math.round(fbelow));

The above output is 1,0,1,0. And rounding is the same.

Thinking in Java notes (chapter III 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.