Thinking in Java,fourth Edition (Java programming Idea, fourth edition) learning Note IV) operators

Source: Internet
Author: User

At the lowest level, data in Java is manipulated using operators

Using Java Operators

An operator takes one or more argument and produces a new value. The arguements is in a different form than ordinary method calls, but the effect is the same.

+: addition and unary plus (another mean:string concatenation does that count as operators?)

-: Subtraction and unary minus

*: Multiplication

/: Division

=: Assignment

All operators produce a value from their operands. In addition, some operators change the value of a operand.

But the value produced was avaiable for your use,just as in operators without side effects

All of the operators work is only with primitives. The exceptions is =, = = and! =, which work with all objects (and is a point of confusion for objects). In addition, the String class supports + and + =

Precedence

The easiest one to remember are that multiplication and division happen before addition and subtraction. Programmers often forget the other precedence rules, so you should use parentheses to make the Order of evaluation Explici T.

(When the compiler sees a String followed by a ' + ' followed by a non-string, it attempts to convert the non-string into a String.)

Assignment

Rvalue:constant,variable,expression that produces a value

Lvalue:variable

Primitive Type:

A = b; The contents of B is copied into a. If you then go in to modify a, and B is naturally unaffected by this modification.

Object:

A = b; Copying a reference from B to a. End up with both A and B pointing to the object, originally, only b pointed to.

This phenomenon is often called aliasing

aliasing during method calls 

Class Letter {
char c;
}
public class Passobject {
static void F (letter Y) {
y.c = ' Z ';
}
public static void Main (string[] args) {
Letter x = new Letter ();
x.c = ' a ';
Print ("1:x.c:" + x.c);
f (x);
Print ("2:x.c:" + x.c);
}
}

 The method F () would appear to be making a copy of their argument letter y inside the scope of the method. But once again a reference was being passed, so the line
y.c = ' Z ';
is actually changing the object outside of F ().

Mathematical Operators

+-*/% (which produces the remainder from integer Division)

 Integer division truncates, rather than rounds, the result.

Java also uses the shorthand notation from C + + that performs an operation and a assignment at the same time.

This was denoted by a operator followed by a equal sign and are consistent with all the operators in the Laguage.

+=, -=, *=, /=, %=

(If you create a random object with no arguments, Java uses the current time as a seed for the random number generator, an D would thus produce different output for each execution of the program.)
(An initialization value for the random number generator that would always produce the same sequence for a particular seed Value

 Random rand = new Random (47);
Int j = Rand.nextint (100) + 1; Fixed 59

unary minus and plus operators

The unary minus (-) and unary plus (+) are the same operators as binary minus and plus. The compiler figures out which use are intended by the the the-the-same expression.

Auto increment and decrement

++i,--i:the operation is performed and the value is produced

i++, i--: The value is produced and then the operation is performed

Relational Operators

<, <=, >,>=,==,!=

==,!=: Work with all primitives

<,<=,>,>=: Won ' t work with type Boolean.

Testing Object Equivalence

The operators = = and! = Compare Object references

If you want to compare the actual contents of a object form equivalence, you must use the Special method equals () that E Xist for all objects. If you create a new type (Class), the default behavior of equals () is to compare references.

Logical Operators

&&,| |,!

You can ' t use a non-boolean as if it were a Boolean in a logical expression as the can in C and C + +.

short-circuiting

This means the expression would be evaluated only until the truth or falsehood of the entire expression can Unambig uously determined. As a result, the latter parts of a logical expression might not be evaluated.

The reason for shortciruiting, in fact, is so you can get a potential performance increase if all the parts of a logical expression does not need to be evaluated.

Literals

Ordinarily, when you insert a literal value in a program, the compiler knows exactly what type to make it. Sometimes, however, the type is ambiguous. When this happens is must guide, the compiler is adding some extra information in the form of characters associated with The literal value.

int i1 = 0x2f//hexadecimal 47

int i2 = 0x2F//hexadecimal 47

int i3 = 0177//octal 127

int i4 = 0xFFFF//hexadecimal 65535

Long l1 = 100L//long suffix, uppercase

Long L2 = 100l//long suffix, lowercase, and number 1 are confusing

Float F1 = 1F//float suffix

float F2 = 1f//float suffix

Double D1 = 1d//double suffix

Double D2 = 1D//doubule suffix

 (Hex and octal also work with long)

A trailing character after A literal the value establishes its type. Uppercase or lowercase L means long (however, using a lowercase l is confusing because it can look like the number one). Uppercase or lowercase F means float. Uppercase or lowercase D means double.
Hexadecimal (base), which works with all the integral data types, are denoted by a leading 0x or 0X followed by 0-9 or a-f either in uppercase or lowercase. If you try to initialize a variable with a value bigger than it can hold (regardless of the numerical form of the value), The compiler would give you a error message. Notice in the preceding code the maximum possible hexadecimal values for char, Byte, and short. If you exceed these, the compiler would automatically make the value of an int and to tell you this need a narrowing cast for The assignment (casts is defined later in this chapter). You'll know ' ve stepped over the line.

There is no literal representation for binary numbers in C, C + +, or Java. However, when working with hexadecimal and octal notation, it's useful to display the binary form of the results. This is easily accomplished with the static tobinarystring () methods from the Integer and Long classes. Notice that was passing smaller types to integer.tobinarystring (), the type was automatically converted to an int.

Exponentail notation

Exponents use a notation that I ' ve always found rather dismaying

1.39 e-43f in Java; It means 1.39 x 10-43

Bitwise operators

The bitwise operators allow for manipulate individual bits in an integral primitive data type (note: Not just the integer type). Bitwise operators perform Boolean algebra on the corresponding bits in the both argument to produce the result.

  The bitwise AND operator (&) produces a one in the output bit if both input bits is one; Otherwise, it producces Z Zero

The bitwise OR Operator (|) produces a one in the output bit if either input bit are a one and product a zero only if both Input bits is zero.

The bitwise EXCLUSIVE OR or XOR (^), produces a one in the output bit if one OR the other input bit was a one, but not both .

The bitwise NOT (~, also called the ones complement operator) is a unary operator; It takes only one argument. Bitwise not produces the opposite of the input bit--a one if the input bit was zero, a zero if the input bit is one.

Bitwise operators can be combined with the = sign: &=,|=,^=, Exception ~ (Since ~ is a unary operator)

  The Boolean type is treated as a one-bit value and so it is somewhat different. You can perform a bitwise and, or, and XOR, but can ' t perform a bitwise not (presumably to prevent confusion with the Logical not). For Booleans, the bitwise operators has the same effect as the logical operators except that they does not shor circuit. ALSO, bitwise operations on Booleans include a XOR logical operator that's not included under the list of "logical" oper Ators. You cannot the user Boolean in shift expression.

shift operators (less chance of use, no further learning)

The shift operators also manipulate bits. They can used solely with Primitvie, integral type (note: Not just the integer type).

The left-shift operator (<<)

The signed Right-shift operator (>>)

The unsigned Right shift >>> (uses zero extension)

(Note: To simplify the example, take 8-bit bytes as an example)

such as: 5<<3 equals 00000101 00101000 low 0 that is 5 * 2 3-Time Square

-5>>3 11111011 11111111 High 1

5>>3 00000101 00000000 High 0

-5>>>3 11111011-> 00011111 High Fill 0

If you shift a char, byte, or short, it'll be promoted to int befor The shift takes place, and the result would be a int .

If you shift a char, byte, or short, it'll be promoted to int before the shift takes place, and the result would be a in T. Only the five low-order bits of the right-hand side would be used. This prevents is shifting more than the number of bits in an int. If you ' re operating on a long, you'll get a long result. Only the six low-order bits of the right-hand side would be is used so can ' t shift more than the number of bits in a long .

The binary representation of the numbers is referred to as signed twos complement.

ternary if-else operator

Boolean-exp? Value0:value1

String operator + and + =

There's one special usage of a operator in Java:the + and + = operators can used to concatenate strings.

The binary representation of the numbers is referred to as signed twos complement.

public class Stringoperators {
public static void Main (string[] args) {
int x = 0, y = 1, z = 2;
String s = "x, y, z";
Print (s + x + y + z);
Print (x + "" + s); Converts x to a String

s + = "(summed) ="; concatenation operator
Print (s + (x + y + z));
Print ("" + x); Shorthand for integer.tostring ()
}
}/* Output:
X, y, Z 012
0 x, y, Z
X, Y, Z (summed) = 3
0

*/

Common pitfalls when using operators

1. One of the pitfalls when using operators was attempting to leave out the parentheses when you are even the least bit UNC Ertain about what an expression would evaluate. This is still true in Java.

2. while (x=y)

In Java, the result of this expression was not a Boolean, but the compiler expects a Boolean and won ' t convert from an int, So it would conveniently give you a compile-time error and catch the problem before you ever try to run the program. So the pitfall never happens in Java. (The only time you won ' t get a compile-time error was when X and Y were Boolean, in which case x = y is a legal expression, And in the preceding example, probably an error.)

Case Operators

Java allows you-to-cast any primitive type to any other primitive type, except-Boolean, which doesn ' t allow any castin G at all. Class types does not allow casting. To convert one to the other, there must is special methods. (You'll find out the later in the This book so objects can be cast within a family of types; an Oak can is cast to a Tree and VI Ce versa, but not to a foreign type such as a Rock.)

Truncation and rounding

 That casting from a float or double to an integral value always truncates the number. If instead you want the result of the rounded, use the round () methods in Java.lang.Math:

Promotion

In general, the largest data type in a expression is the one that determines the size of the the result of the; If you multiply a float and a double, the result would be double; If you add an int and a long, the result would be a long.

Java has no "sizeof"

Java does not need a sizeof () operator for this purpose, and because all the data types is the same size on all machines. You don't need to think about portability in this level-it are designed into the language.

A Compendium of Operators

(Long string example.)

In Char, Byte, and short, you can see the effect of promotion with the arithmetic operators. Each arithmetic operation in those types produces an int result, which must is explicitly cast back to the original Type (a narrowing conversion that might lose information) to assign back to that type.

Don ' t be lulled to thinking everything is safe, though. If you multiply and ints that is big enough, you ll overflow the result. You get no errors or warnings from the compiler, and no exceptions at run time. Java is good, but it's not good.

Compound assignments do not require casts for char, Byte, or short, even though they is performing promotions that has T He same results as the direct arithmetic operations. On the other hand, the lack of the cast certainly simplifies the code.

You can see this, with the exception of a Boolean, any primitive type can is cast to any other primitive type. Again, you must is aware of the effect of a narrowing conversion when casting to a smaller type; Otherwise, you might unknowingly lose information during the cast.

Thinking in Java,fourth Edition (Java programming Idea, fourth edition) learning Note IV) 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.