[Java programming ideology-learning notes] Chapter 1 operators and java programming ideology

Source: Internet
Author: User

[Java programming ideology-learning notes] Chapter 1 operators and java programming ideology
3.1 simpler print statements

The first program encountered by learning the programming language is nothing more than printing "Hello, world". However, it must be written in Java

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

We will all feel too long. Can it be simpler? Static import can be omittedSystem, Just like this

import static java.lang.System.*;public class Hello {    public static void main(String[] args) {        out.println("Hello, world");    }}

Can it be simpler? Like C language? In factSystemYes, and out isSystemOnePrintStreamType of static members, becauseSystemClass.

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

I can be inspired to write a class myself, and then import the class statically, so that I can directly output the content like the C language.

package p1;import static java.lang.System.*;public class Print {    public static void println(String x) {        out.println(x);    }}

Then write a Hello program

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

NOTE: You can package your printed output class into a jar file and run the command jar cvf p1.jar p1/Print. class, where p1 is the package name, Print is the class name, and then put it in the lib directory under the jdk directory, such as D: \ jdk \ lib \ p1.jar, and then modify the environment variable, add % JAVA_HOME % \ lib \ p1.jar to CLASSPATH, so that you can use it once and for all. You only need to import static p1.Print. *; you can directly use the println method.

3.2 use Java Operators

The side effects of operators are mentioned here. This blog post gives a very detailed http://www.cnblogs.com/lazycoding/archive/2011/04/27/side-effect.html

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 do not need to remember it, because the omnipotent parentheses () can reduce errors and make the program easy to read.

3.4 assignment

Assign a value is simple, just assign a value to a variable, such

int x = 5;

Beginners need to pay attention to the left Value Problem and cannot write it

Int x = 5; 2 = x; // The left value cannot be a direct value. The constant x + 1 = 5; // The left value cannot be an expression.
3.5 Arithmetic Operators

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

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

These five Arithmetic Operators are only basic mathematical operators. They will naturally multiply, divide, and add or subtract the modulus as they do in mathematics. In this example, first 6/3 = 2, then 2*5 = 10, then 10% 3 = 1, and then 9-8 + 1 = 2

To simplify the statement, you can use a simplified operator like the C language, as follows:

int a = 5;int b = 6;int c;int d = a += b -= c = 2;// d = 9

As described in row 14th of the priority, the assignment and simplified operators are all computed from right to left. Therefore, the above program is c = 2, B-= c, and B = 4, next we get a + = B, a = 9, d = a, and d = 9.

3.6 auto increment and decrease

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

X ++ and ++ x, x -- and -- x

Prefix increment + + x means to add 1 to x and then use x. suffix increment x ++ means to use x first and then add 1 to x, the decline operator is the same, for example, the following program

int a = 5;print(++a);// 6int b = 5;print(b++);// 5int c = 5;print(--c);// 4int d = 5;print(c--);// 5

Let's look at the complicated program.

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

The above program is equivalent

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

Note: you cannot use two or more increasing and decreasing Operators for the same variable. For example, the following program

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

Relational operators include <(less than), <= (less than or equal to),> (greater than), >=( greater than or equal to), ==( equal to), and! = (Not equal to), the result isBooleanValue, as shown below

int x = 7;out.print(x < 8); // trueout.print(x <= 8);// trueout.print(x > 8); // falseout.print(x >= 8);// falseout.print(x == 8);// falseout.print(x != 8);// true

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

public class Person {    private int age;    public Person(int newAge) {        age = newAge;    }    public static void main(String[] args) {        String s1 = "abc";        String s2 = "abc";        Person xiaoMing = new Person(18);        Person xiaoFu = new Person(18);        out.println(s1 == s2);// true        out.println(xiaoMing == xiaoFu);// false    }}

The result is unexpected. Row 3 isTrueWhich can contain 12th rowsFalse! This is because, = and! = Compare the object address, not the object content.StringType s1 and s2 reference the same String constant, so equal, whilePersonTypeXiaoMingAndXiaoFuAlthough the content is the same, it belongs to two different objects, just as there are two Xiao Ming in the same class. Although they are of the same age, their genes are different.

In this case, how should we compare the content of two objects? You can use the slave root classObjectInheritedEquals ()Method

out.println(s1.equals(s2));// trueout.printlnl(xiaoMing.equals(xiaoFu));// false

The result is confusing. Why is the result of row 1st?TrueAnd the result of row 2nd isFalse? Actually classStringOverride classObjectOfEquals ()Method, but this example has not covered it, actually from the classObjectInheritedEquals ()This is the default method.

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

We canPersonOverwrite)Equals ()Method, and then compare two objects, as shown below

public class Person {    private int age;    public Person(int newAge) {        age = newAge;    }    public boolean equals(Object obj) {        if (age == ((Person)obj).age)            return true;        else            return false;    }    public static void main(String[] args) {        Person xiaoMing = new Person(18);        Person xiaoFu = new Person(18);        out.println(xiaoMing.equals(xiaoFu));// true    }}

Let's take a look at two more.StringObject comparison:

String s1 = "abc";String s2 = "abc";String s3 = new String("abc");String s4 = new String("abc");out.println(s1 == s2);// trueout.println(s2 == s3);// falseout.println(s3 == s4);// falseout.println(s2.equals(s3));// true

In fact, the string constant "abc" pointed to by the reference variable s1 is placed in the constant pool. When s2 also references "abc", the JVM will not open up another memory space, instead, let s2 also reference the existing "abc", so s1 will be equal to s2. S3 and s4 are different. The objects referenced by them exist in the heap and are different objects. Even though they share the same content, they are not equal. BecauseStringImplementedEquals ()Method to compare the twoStringObject content, not the address, so the result of row 8th isTrue.

3.8 logical operators

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

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.

public class Demo {    boolean flag;    public static void main(String[] args) {        boolean x = new Demo(false).flag && new Demo(true).flag             && new Demo(true).flag;// false         boolean y = new Demo(false).flag || new Demo(true).flag             || new Demo(true).flag;// false true     }    Demo(boolean newFlag) {        flag = newFlag;        print(flag + " ");    }}

The above program, because of short circuit, the result of Line 3 isFalseAnd space. The result of row 7th isFalse trueAnd space

3.9 direct Constants

Directly reference the code of Java programming ideology

Public class Literals {public static void main (String [] args) {int i1 = 0x2f; // hexadecimal, lowercase out. println ("i1:" + Integer. toBinaryString (i1); int i2 = 0X2F; // hexadecimal, uppercase out. println ("i2:" + Integer. toBinaryString (i2); int i3 = 0177; // octal, starts from 0. println ("i3:" + Integer. toBinaryString (i3); char c = 0 xffff; // hexadecimal, char type maximum value out. println ("c:" + Integer. toBinaryString (c); byte B = 0x7f; // hexadecimal, maximum out of byte. println ("B:" + Integer. toBinaryString (B); short s = 0x7fff; // The maximum value of short out in hexadecimal format. println ("s:" + Integer. toBinaryString (s); long n1 = 200L; // long type, suffix L long n2 = 200l; // long type, suffix small l long n3 = 200; // long type, no suffix float f1 = 1; // float type, no suffix float f2 = 1F; // float type, suffix F float f3 = 1f; // float type, suffix small f double d1 = 1d; // double type, suffix small d double d2 = 1D; // double type, suffix D }}/ * output result i1: 101111i2: 101111i3: 1111111c: 111111111111b: 1111111 s: 111111111111111 */

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 = ++5;
3.10 bitwise operators

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

The bitwise operators include bitwise AND (&), bitwise OR (|), bitwise XOR or (^), and bitwise non (~), Their calculation methods are as follows:

The actual application is as follows:

Decimal 7: 00000111 decimal 9: 000010017 & 9, that is, 00000111 & 00001001 = 00000001 (decimal 1) 7 | 9, that is, 00000111 | 00001001 = 00001111 (decimal 15) 7 ^ 9, that is, 00000111 ^ 00001001 = 00001110 (decimal 14 )~ 7, that is ~ 00000111 = 11111000 (decimal-8)

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

The shift operators are shifted left <shifted right>, unsigned, and shifted right>. Their operations are as follows:

X <n; // move x to the left to n places and fill in 0x> n in the low position. // move x to the Right to n places. If x is a positive number, if x is a negative number, the value of 1x> n is greater than 1x. // The value of x is shifted to the right. In any case, add 0 at the high position. // no matter how you move the value to 0, the result is 0.

IfChar,ByteOrShortBefore the shift, convert the values of the type to the int type.IntType 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;

In fact, it is equivalentIf-elseStatement, as follows:

if (expression)    value1;else    value2;

If expression isTrueThe result is value1. Otherwise, it is value2. 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 + =

A brief demonstration of the application

String s1 = "Hello,";String s2 = "world";String s3 = s1 + s2;// s3 = "Hello,world"String s1 += s2;// s1 = "Hello,world"
3.14 type conversion

Those who have learned C language should all know what type conversion is. As long as the type ratioIntSmall (that isByte,CharOrShort), These values are automatically convertedIntIn this way, the final result isIntType. 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. IfFloatValue andDoubleThe result isDouble; If youIntAnd oneLongThe result isLong

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

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.