[Thinking in Java] Chapter 3rd-operators, Chapter 3rd

Source: Internet
Author: User
Tags bitwise operators

[Thinking in Java] Chapter 3rd-operators, Chapter 3rd
3.1 simpler print statement 3.2 use Java operator 3.3 Priority Assignment 3.4 Arithmetic Operator 3.5 auto increment and decrease 3.6 relational operator 3.7 logical operator 3.8 direct constant 3.9 bitwise operator 3.10 shift operator 3.11 Condition operator 3.13 string operator + and + = 3.14 type conversionDirectory

3.1 simpler print statements

The first program encountered by students studying programming languages is simply printing Hello and world. However, in Java

System.out.println("Hello, world");

We will all feel too long. Can it be simpler? Static import can omit System, just like this

import static java.lang.System.*;

Then write the Hello, world

out.println("Hello, world");

Can it be simpler? Like C language? In fact, the System here is a class, and the out is a static member of the System, which is of the PrintStream type, because it is written in the System class in this way,

public final class System {    ......    public final static PrintStream out = null;    ......}

I can be inspired to write a class myself, and then import the static output method of this class to output the content like the C language.

Package p1; import static java. lang. system. *; public class MyPrint {public static void print (String x) {out. print (x);} // reload print public static void println (String x) {out. println (x);} // reload println}

Write the first java program

import static p1.MyPrint.*;public class Example {    public static void main(String[] args) {        println("Hello,world");    }}

NOTE: You can package your printed output class into a jar file and use the command jar cvf p1.jar p1/MyPrint. class, where p1 is the package name and MyPrint is the class name, which can be customized and placed in the lib directory under the jdk directory, such as D: \ jdk \ lib \ p1.jar, then, modify the environment variable and add % JAVA_HOME % \ lib \ p1.jar to CLASSPATH. In this way, you only need to import static p1.MyPrint. *; you can directly use the println method.

 

3.2 use Java Operators

The side effects of operators are mentioned here. This blog post details the side effects of expressions.

Simply put, if the value of variable X is not changed after an expression operation, the operator has no side effects. If the value is changed, the operator has side effects.

 

3.3 Priority
Priority Operator Associativity
1 () []. From left to right
2 ! + (Positive)-(negative )~ ++ (Ascending) -- (descending) From right to left
3 */% From left to right
4 + (Plus)-(minus) From left to right
5 <>>>> From left to right
6 <, <=,>, >=, Instanceof From left to right
7 =! = From left to right
8 & (Bitwise AND) From left to right
9 ^ (Exclusive or) From left to right
10 | (By bit or) From left to right
11 & (Logical and, short circuit and) From left to right
12 | (Logical or, short circuit or) From left to right
13 ? : From right to left
14

=, + =,-=, * =,/=, % =, & =, | =, ^ = ,~ =,

<=, >>=, >>>=

From right to left

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

In fact, you don't need to remember it. As long as there are omnipotent parentheses, it not only makes the program easier to read, but also reduces errors.

 

3.4 assignment

 

3.5 Arithmetic Operators

Arithmetic Operators include + (plus),-(minus), * (multiplication),/(Division), and % (modulo operation)

int sum = 9 - 8 + 6 / 3 * 5 % 3;// sum = 2

The operators of the same row in the priority table have the same priority. In this example, first 6/3 = 2, then 2*5 = 10, then 10% 3 = 1, and then 9-8 + 1 = 2

You can also use a simplified operator from the C language, that is, the 14th row operator in the priority table.

int x = 1;int y = x += 2;// y = 3

Note that the concatenation of the 14th rows operator is from right to left, so first x + = 2, get x = 3, finally y = x, get y = 3

 

3.6 auto increment and decrease

The increment operators are divided into prefix increment and suffix increment. The increment operators are also divided into prefix increment and suffix increment, such

X ++ x

X -- x

Just like the incrementing operator, x ++ means to use the value of x first, and then x automatically adds 1 after the calculation. ++ x means to automatically add 1 to x first, then use the value of x

int x = 5;int y = x++ + x-- + ++x + --x;// x = 5, y = 22

The example above is equivalent

int x = 5;int y = x++;y = x--;y = ++x;y = --x;

Note: you cannot use two or more increasing/Decreasing Operators for the same variable. For example, the following example is incorrect.

X ++ --; // error. You cannot use two increment/decrease operators for the same variable at the same time.

 

3.7 Relational operators

The result of Relational operators is a boolean value with <(less than), <= (less than or equal to),> (greater than), >=( greater than or equal ), = (equal to) and! = (Not equal)

A simple example

int x = 7;print(x < 8); // trueprint(x <= 8);// trueprint(x > 8); // falseprint(x >= 8);// falseprint(x == 8);// falseprint(x != 8);// true            

= And! in Java! = Can also be used to compare objects, such

 1 public class Person { 2     int age; 3      4     public static void main(String[] args) { 5         String s1 = "ggg"; 6         String s2 = "ggg"; 7         Person zhangSan = new Person(18); 8         Person liSi = new Person(18); 9         println(s1 == s2);// true10         println(zhangSan == liSi);// false11     }12     13     Person(int newAge) {14         age = newAge;15     }16 }

Unexpectedly, 9th rows are true, but 10th rows are false! This is because, = and! = Compare the object reference, not the object content. S1 and s2 of the String type reference the same String constant, so they are equal. Although zhangSan and liSi of the Person type share the same content, they belong to two different objects, just as there are two Xiao Ming in the same class, the same age, but their genes are different.

In this case, how should we compare the content of two objects? You can use the equals () method inherited from the root class.

 1 public class Person { 2     int age; 3      4     public static void main(String[] args) { 5         String s1 = "ggg"; 6         String s2 = "ggg"; 7         Person zhangSan = new Person(18); 8         Person liSi = new Person(18); 9         println(s1.equals(s2));// true10         println(zhangSan.equals(liSi));// false11     }12     13     Person(int newAge) {14         age = newAge;15     }16 }

The result is confusing. Why is the result of 9th rows true, and the result of 10th rows false? In fact, the String class overwrites the equals () method of the Object class, but this example does not cover it. In fact, the equals () method inherited from the Object class is like this by default.

public boolean equals(Object obj) {   return (this == obj);}

Therefore, the result returned by row 10th is false.

 

3.8 logical operators

Logical operators "and" (&), "or" (|), and "Non "(!) Generate a Boolean value (true or false) based on the Logical Relationship of the parameter ).

It is worth noting that & | is short-circuited. For example, if p & q is false, q is not required. If p is true, q is calculated again, for example, p | q. If p is true, q is not required. If p is false, q is calculated again.

 1 public class Demo { 2     boolean flag; 3      4     public static void main(String[] args) { 5         boolean x = new Demo(false).flag && new Demo(true).flag && new Demo(true).flag;// false  6         boolean y = new Demo(false).flag || new Demo(true).flag || new Demo(true).flag;// false true  7     } 8      9     Demo(boolean newFlag) {10         flag = newFlag;11         print(flag + " ");12     }13 }

Because of short circuit, only false (Space) is printed on line 1, and false (Space) is printed on line 3)

 

3.9 direct Constants

Directly reference Thinking in Java code

1 public class Literals {2 public static void main (String [] args) {3 int i1 = 0x2f; // hexadecimal, lowercase 4 println ("i1:" + Integer. toBinaryString (i1); 5 int i2 = 0X2F; // hexadecimal, uppercase 6 println ("i2:" + Integer. toBinaryString (i2); 7 int i3 = 0177; // octal, starting with 0 8 println ("i3:" + Integer. toBinaryString (i3); 9 10 char c = 0 xffff; // hexadecimal, char type maximum 11 println ("c:" + Integer. toBinaryString (c); 12 byte B = 0x7f; // hexadecimal notation, maximum byte value 13 println ("B:" + Integer. toBinaryString (B); 14 short s = 0x7fff; // in hexadecimal notation, the short maximum value is 15 println ("s:" + Integer. toBinaryString (s); 16 17 long n1 = 200L; // long type, suffix large L18 long n2 = 200l; // long type, suffix small l19 long n3 = 200; // long type, no suffix 20 float f1 = 1; // float type, no suffix 21 float f2 = 1F; // float type, suffix F22 float f3 = 1f; // float type, suffix small f23 double d1 = 1d; // double type, suffix small d24 double d2 = 1D; // double type, suffix D25} 26}/* output result 27 i1: 10111128 i2: 10111129 i3: 111111130 c: 111111111111111131 B: 111111132 s: 11111111111111133 */

In C, C ++, or Java, binary data does not directly represent constants. However, using hexadecimal or octal to represent binary data is more intuitive, concise, and easier to read.

Since it is a direct constant, the program will not want to modify its value. For example, the following code cannot be compiled.

int x = 1++;

 

3.10 bitwise operators

The bitwise operator is used to operate a single bit in the integer basic data type, that is, the binary bit. The bitwise operator performs Boolean algebra on the bits corresponding to the two parameters and generates a result.

If both input bits are 1, 1 & 1 = 1;

Otherwise, 1 & 0 = 0; 0 & 1 = 0;

If one of the two input bits is 1, 1 | 0 = 1; 0 | 1 = 1;

Otherwise, 0 | 0 = 0;

If the two input BITs do not hurt, 1 ^ 0 = 1; 0 ^ 1 = 1;

Otherwise, 1 ^ 1 = 0; 0 ^ 0 = 0;

The bitwise "Non" is the unary operator ,~ 1 = 0 ;~ 0 = 1

Bitwise operators and logical operators both use the same symbol, so we can easily remember their meaning: Because the bit is very "small, therefore, the bitwise operator only uses one character.

The bitwise operator can be used with equal signs (=) To merge operations and assign values: & =, | =, and ^ = ~ It is a one-dimensional operator, so it does not exist ~ =)

We treat the boolean type as a single-bit value, so it is somewhat unique. For Boolean values, the bitwise operator will not be short-circuited. We can perform &, |, and ^ on boolean values, but not ~ (To avoid! ), Where the bitwise variance or (^) is used as follows

boolean p = true;boolean q = false;boolean r;r = p ^ p;// falser = p ^ q;// truer = q ^ p;// truer = q ^ q;// false

 

3.11 Shift Operator

Shift Operators include shifts left <, shifts right with symbols>, shifts right without symbols>

X <n; move x to the left to add 0 at the low position.

X> n; move x to the Right to n places. If x is a positive number, 0 is added for the high position. If x is a negative number, 1 is added for the high position.

X >>> n; moves x to the Right to n places. In any case, add 0 to the upper position.

No matter how you move the value 0, the result is 0.

If the char, byte, or short numeric values are displaced, they are converted to the int type before the shift, and the result is also an int type value.

"Shift" can be combined with "equal sign" (<<=or >=or >>>=)

 

3.12 conditional Operators

The syntax of conditional operators is as follows:

Expression? Value1: value2;

If expression is true, value1 is returned; otherwise, value2 is returned. Note that the combination of conditional operators is from right to left, for example

int x = 2 > 1 ? 10 : 100 > 99 ? 1000 : 10000;// x = 10

Run 100> 99 first? 1000: 10000; the result is 1000, and then 2> 1? 10: 1000; therefore, the result is 10.

 

3.13 string operators + and + =
String s1 = "Hello,";String s2 = "world";String s3 = s1 + s2;// s3 = "Hello,world"String s1 += s2;// s1 = "Hello,world"

 

3.14 type conversion

As long as the type is smaller than the int type (that is, byte, char, or short), these values are automatically converted to the int type before calculation. In this way, the final result is the int type. If you want to assign a value to a smaller type, you must use forced type conversion (since the result is assigned to a smaller type, information may be lost ). Generally, the maximum data type in an expression determines the Data Type of the final result of the expression. If you multiply a float value by a double value, the result is double. If you add an int and a long, the result is long.

Application of type conversion: accurate to n digits after the decimal point

// Precise to the third decimal point, double pi = 3.141592653; double x = (int) Math. round (pi * 1000)/1000.0; // x = 3.142

 

Related Article

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.