4. JAVA programming ideology-control program flow

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

4. JAVA programming ideology-control program flow

Control Procedure Flow

In Java, we use operators to manipulate objects and data and use execution control statements to make choices. Java is based on C ++. Therefore, for C and C ++ programmers, most statements and operators in Java should be very familiar. Of course, Java has also made some improvements and simplification work.

1. Use the Java Operator

The usage of the plus sign (+), minus sign and minus sign (-), multiplication sign (*), division sign (/), and equal sign (=) is similar to that of all other programming languages.

An example of arithmetic operations is as follows:

ClassNumber {

IntI;

}

PublicclassTest {

PublicstaticvoidMain (String [] args ){

Number n1 =NewNumber ();

Number n2 =NewNumber ();

N1. I = 9;

N2. I = 47;

System.Out. Println ("1: n1. I:" + n1. I +

", N2. I:" + n2. I );

N1 = n2;

System.Out. Println ("2: n1. I:" + n1. I +

", N2. I:" + n2. I );

N1. I = 27;

System.Out. Println ("3: n1. I:" + n1. I +

", N2. I:" + n2. I );

}

}

The Number class is very simple. Its two instances (n1 and n2) are created in main. The I value in each Number is assigned a different value. Then, n2 is assigned to n1, and n1 changes.

The output is as follows:

1: n1. I: 9, n2. I: 47

2: n1. I: 47, n2. I: 47

3: n1. I: 27, n2. I: 27

Let's take a look at the alias processing in the method call:

ClassLetter {

CharC;

}

PublicclassTest {

StaticvoidF (Lettery ){

Y. c = 'Z ';

}

PublicstaticvoidMain (String [] args ){

Letter x =NewLetter ();

X. c = 'a ';

System.Out. Println ("1: x. c:" + x. c );

F(X );

System.Out. Println ("2: x. c:" + x. c );

}

}

The f () method appears to have a copy of its independent variable Letter y within the scope of the method.

Actually, a handle is passed. So the following program line:

Y. c = 'Z'; actually, objects other than f () are changed. The output result is as follows:

The output is as follows:

1: x. c:

2: x. c: z

 

2 Arithmetic Operators

Java's basic arithmetic operators are the same as most programming languages. These include the plus sign (+), minus sign (-), division sign (/), multiplication number (*), and modulus (%, which obtain the remainder from the integer division ). Integer division directly removes decimal places rather than carry places. Java also performs operations in short form and assigns values at the same time. This is marked by an operator before the equal sign, and all operators in the language are fixed. For example, to add 4 to the variable x and assign the result to x, use: x + = 4.

Example:

ImportJava. util .*;

PublicclassTest {

// Create a shorthand to save typing:

StaticvoidPrt (Strings ){

System.Out. Println (s );

}

// Shorthand to print a string andInt:

StaticvoidPInt (Strings,IntI ){

Prt(S + "=" + I );

}

// Shorthand to print a string and a float:

StaticvoidPFlt (Strings,FloatF ){

Prt(S + "=" + f );

}

PublicstaticvoidMain (String [] args ){

// Create a random number generator,

// Seeds with current time by default:

Random rand =NewRandom ();

IntI, j, k;

// '%' Limits maximum value to 99:

J = rand. nextInt () %100;

K = rand. nextInt () %100;

PInt("J", j );PInt("K", k );

I = j + k;PInt("J + k", I );

I = j-k;PInt("J-k", I );

I = k/j;PInt("K/j", I );

I = k * j;PInt("K * j", I );

I = k % j;PInt("K % j", I );

J % = k;PInt("J % = k", j );

// Floating-point number tests:

FloatU, v, w; // applies to doubles, too

V = rand. nextFloat ();

W = rand. nextFloat ();

PFlt("V", v );PFlt("W", w );

U = v + w;PFlt("V + w", u );

U = v-w;PFlt("V-w", u );

U = v * w;PFlt("V * w", u );

U = v/w;PFlt("V/w", u );

// The following also works

// Char, byte, short,Int, Long,

// And double:

U + = v;PFlt("U + = v", u );

U-= v;PFlt("U-= v", u );

U * = v;PFlt("U * = v", u );

U/= v;PFlt("U/= v", u );

}

}///:~

The prt () method prints a String; pInt () prints a String first and then an int; and pFlt () prints a String first and then a float. Of course, they all end with System. out. println.

To generate numbers, the program first creates a Random (Random) object. Since the independent variables are passed during the creation process, Java uses the current time as a "seed value", which is used by the random number generator. Through the Random object, the program can generate many different types of Random numbers. You only need to call Different Methods: nextInt (), nextLong (), nextFloat (), or nextDouble ().

If it is used along with the result of the random number generator, the modulus operator (%) can limit the result to the upper limit of the calculation object minus 1 (in this example, 99.

The output is as follows:

J =-58

K = 13

J + k =-45

J-k =-71

K/j = 0

K * j =-754

K % j = 13

J % = k =-6

V = 0.88164216

W = 0.17560738

V + w = 1.0572495

V-w = 0.7060348

V * w = 0.15482287

V/w = 5.02053

U + = v = 5.9021726

U-= v = 5.02053

U * = v = 4.426311

U/= v = 5.02053

 

3. Auto increment and decrease

Similar to C, Java provides a wide range of quick operations. These quick operations make the code more fresh, easier to input, and easier for readers to identify and read.

There are two good quick operations: increment and decrease operators (often called "auto increment" and "auto increment" operators ). Here, the decimal operator is "--", meaning "reduce a unit"; the increasing operator is "++", meaning "add a unit ".

There are two versions available for each type of operators. They are usually called "prefix" and "suffix ". "Increment first" indicates that the ++ operator is located before a variable or expression, while "increment later" indicates that the ++ operator is located behind a variable or expression. Similarly, "decrease before" means that the -- operator is before the variable or expression, and "decrease after" means that the -- operator is behind the variable or expression. For the ascending and descending values (for example, ++ A or -- A), the operation is performed first and then the value is generated. For post-increment and post-incrementing (such as A ++ or A --), the post-increment and post-incrementing values are converted into values and then executed. The following is an example:

PublicclassTest {

PublicstaticvoidMain (String [] args ){

IntI = 1;

Prt("I:" + I );

Prt("++ I:" ++ I );//Pre-Increment

Prt("I ++:" + I ++); // Post-increment

Prt("I:" + I );

Prt("-- I:" + -- I );//Pre-Decrement

Prt("I --:" + I --); // Post-decrement

Prt("I:" + I );

}

StaticvoidPrt (Strings ){

System.Out. Println (s );

}

}///:~

The output is as follows:

I: 1

++ I: 2

I ++: 2

I: 3

-- I: 2

I --: 2

I: 1

 

4 Relational operators

Relational operators generate a Boolean result. They evaluate the relationship between calculation object values. If the link is true, the relational expression generates true (true). If the link is not true, false (false) is generated ). Relational operators include less than (<), greater than (>), less than or equal to (<=), greater than or equal to (> =), equal to (=), and not equal (! = ). Equals and not equals apply to all built-in data types, but other comparisons do not apply to boolean types.

Example:

PublicclassTest {

PublicstaticvoidMain (String [] args ){

Integer n1 =NewInteger (47 );

Integer n2 =NewInteger (47 );

System.Out. Println (n1 = n2 );

System.Out. Println (n1! = N2 );

}

}///:~

The output is as follows:

False

True

The formula System. out. println (n1 = n2) can print the internal Boolean comparison result. Generally, the output result must be true first, followed by false because both Integer objects are the same. However, although the content of the object is the same, the handle is different, and = and! = The object handle is compared. Therefore, the output result is actually false, followed by true.

What should I do if I want to compare the actual content of the two objects? In this case, you must use the special method equals () that applies to all objects (). However, this method does not apply to "primary type". For those types, use = and! =.

 

5 logical operators

Logical operators AND (&), OR (|), and not (!) Generate a Boolean value (true or false) based on the Logical Relationship of the independent variable. The following example shows how to use relational and logical operators.

 

Example:

ImportJava. util .*;

 

PublicclassTest {

PublicstaticvoidMain (String [] args ){

Random rand =NewRandom ();

IntI = rand. nextInt () %100;

IntJ = rand. nextInt () %100;

Prt("I =" + I );

Prt("J =" + j );

Prt("I> j is" + (I> j ));

Prt("I <j is" + (I <j ));

Prt("I> = j is" + (I> = j ));

Prt("I <= j is" + (I <= j ));

Prt("I = j is" + (I = j ));

Prt("I! = J is "+ (I! = J ));

 

// TreatingIntAs a boolean is

// Notlegal Java

//!Prt("I & jis" + (I & j ));

//!Prt("I | j is" + (I | j ));

//!Prt("! I is "+! I );

 

Prt("(I <10) & (j <10) is"

+ (I <10) & (j <10 )));

Prt("(I <10) | (j <10) is"

+ (I <10) | (j <10 )));

}

StaticvoidPrt (Strings ){

System.Out. Println (s );

}

}///:~

 

6 bitwise operators

The bitwise operator allows us to operate a single "bit" in an integer primary data type, that is, a binary bit. The bitwise operator executes Boolean algebra on the bits corresponding to the two independent variables and generates a result.

Bitwise operations come from low-level operations in C language. We often need to directly manipulate the hardware and frequently set the binary bit in the hardware register.

Java was originally designed to be embedded in the TV pin box, so this low-level operation is still preserved. However, due to advances in the operating system, it may not be necessary to perform bitwise operations too frequently.

If both input bits are 1, a 1 is generated by the bitwise AND operator (&) in the output bits; otherwise, 0 is generated. If at least one of the two input bits is 1, the bitwise OR operator (|) generates a 1 in the output bits. Only when both input bits are 0, it generates a 0. If one of the two input bits is 1, but not all are 1, XOR (^, exclusive or) generates 1 in the output bits. By bit NOT (~, It is also called the "Non" operator), which belongs to the unary operator. It operates only one independent variable (all other operators are binary operators ). Generate a value opposite to the input bit by bit NOT -- if the input is 0, 1 is output; if the input is 1, 0 is output.

The bitwise AND logical operators both use the same character, but the number is different. Therefore, we can easily remember their respective meanings: Since "bit" is very "small", the bitwise operator only uses one character.

The bitwise operator can be used with equal signs (=) To merge operations and assign values: & =, | = and ^ = ~ Is a unary operator, so it cannot be used together with = ).

We treat the boolean type as a "unit" or "single bit" value, so it is somewhat unique. We can execute bitwise AND, OR, and xor, but NOT (probably to avoid confusion with logical NOT ). For Boolean values, bitwise operators have the same effect as logical operators, but they do not "short-circuit" in the middle ". In addition, the bitwise operation for boolean values adds an XOR logical operator, which is not included in the list of logical operators. In a shift expression, Boolean operations are not allowed.

 

7 Shift Operators

The operation object oriented to the shift operator is also the binary "bit ". You can use them to process integer types (one of the main types) separately ). The Left shift operator (<) can move the operator object on the left of the operator to the specified number of digits on the right of the operator (0 in the low position ). The "Signed" right shift operator (>) moves the operator object on the left of the operator to the right of the specified number of digits on the right of the operator. The "Signed" right shift operator uses the "symbol extension": If the value is positive, 0 is inserted at the high position; if the value is negative, 1 is inserted at the high position. Java also adds an "unsigned" right shift operator (>>>), which uses "Zero extension": no matter whether it is positive or negative, 0 is inserted at a high position. This operator is not available in C or C ++.

If char, byte, or short is displaced, they are automatically converted to an int before the shift. Only the five low positions on the right can be used. This prevents us from moving the unrealistic digits in an int number. If a long value is processed, the final result is long. At this time, only the six low positions on the right will be used to prevent the long value from being moved beyond the existing ones. However, a problem may also occur during "unsigned" right shift. If you perform the right shift operation on the byte or short value, the result may not be correct (especially highlighted in Java 1.0 and Java 1.1 ). They are automatically converted to the int type and shifted to the right. But "Zero extension" does not happen, so in those cases, the result of-1 will be obtained.

PublicclassTest {

PublicstaticvoidMain (String [] args ){

IntI =-1;

I >>>= 10;

System.Out. Println (I );

LongL =-1;

L >>>= 10;

System.Out. Println (l );

ShortS =-1;

S >>>= 10;

System.Out. Println (s );

ByteB =-1;

B >>> = 10;

System.Out. Println (B );

}

}///:~

Output:

4194303

18014398509481983

-1

-1

Shift can be combined with equal signs (<<=or >=or >>>=. At this time, the value on the left of the operator moves the number of digits specified by the value on the right, and then returns the result to the value on the left.

 

8 shape Operators

Cast is used to match a model ". When appropriate, Java will automatically convert one data type to another. For example, if we assign an integer to a floating point variable, the computer automatically converts the int value to float. Through modeling, we can clearly set the conversion of this type, or force it when it is generally not possible. To perform a shape, place the expected data type (including all modifiers) in the brackets to the left of any other value.

As you can see, you can either shape a value or shape a variable. But in the two cases shown here, the shape is redundant, because the compiler will automatically convert the int value to the long value when necessary. Of course, you can still set a shape, remind yourself to pay attention to it, and make the program clearer. In other cases, the styling is important only when the code is compiled. In C and C ++, styling can sometimes lead to headaches.

In Java, styling is a safer operation. However, if you perform an operation named "Narrowing Conversion" (that is, the script is a data type that can accommodate more information, converts a data type to a type with a smaller capacity. At this point, the compiler will force us to shape, as if to say: "This may be a dangerous thing-if you want me to do anything in desperation, so sorry, please make it clear." For "Widening conversion", you do not need to make a clear shape, because the new type will certainly accommodate the original type of information and will not cause any information loss.

Java allows us to "shape" any primary type to any other primary type, except for boolean values, which do not allow any styling. "Class" cannot be modeled. In order to convert one type to another, special methods must be used (strings are a special case. This book will discuss how to shape objects into a "family" type; for example, "Oak" can be shaped as "Tree", and vice versa. But for other external types, such as "rocks", they cannot be shaped as "Trees ").

9 Java does not have "sizeof"

In C and C ++, the sizeof () operator can meet one of our special needs: Get the number of characters allocated to the Data Project. In C and C ++, the most common application of size () is "porting ". Different data may have different sizes on different machines, so when performing some size-sensitive operations, programmers must be aware of the size of those types. For example, one computer can store integers in 32 bits, while the other can only store integers in 16 bits. Obviously, the program can save a larger value on the first machine. As you may have imagined, porting is a headache for C and C ++ programmers.

Java does not need the sizeof () operator to meet this requirement, because all data types have the same size on all machines. We don't have to worry about porting-Java itself is a "platform-independent" language.

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.