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 are in a different form than ordinary method calls, but the effect is the same.

  + : addition and unary plus (another mean:string concatenation 这算不算Operators?)

  - : subtraction and unary minus

  * : multiplication

  / : division

  = : assignment

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

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

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

Precedence

  The easiest one to remember is 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 explicit.

  ( 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 are copied into a. If you then go  on to modify a, 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 that, 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 its argument Letter y inside the scope of the method. But once again a reference is 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/C++ that performs an operation and an assignment at the same time.

  This is denoted by an operator followed by an equal sign and is 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, and will thus produce different output for each execution of the program.)
  (an initialization value for the random number generator that will always produce the same sequence for a particular seed value)

  Random rand = new Random(47);
  int j = rand.nextInt(100) + 1; //固定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 is intended by the way you write the expression.

Auto increment and decrement

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

  i++, i--: the value is produced, 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 an object form equivalence, you must use the special method equals() that exist for all objects. But if you create 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 you can in C and C++.

  Short-circuiting

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

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

Literals

  Ordinarily, when you insert a literal value into a program, the compiler knows exactly what type to make it. Sometimes, however, the type is ambiguous. When this happens, you must guide the compiler by 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,大写

  Long l2 = 100l // Long suffix ,小写,和数字1会混淆

  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 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 16), which works with all the integral data types, is 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 will give you an error message. Notice in the preceding code the maximum possible hexadecimal values for char, byte, and short. If you exceed these, the compiler will automatically make the value an int and tell you that you need a narrowing cast for the assignment (casts are defined later in this chapter). You’ll know you’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 when passing smaller types to Integer.toBinaryString( ), the type is 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 you to manipulate individual bits in an integral primitive data type(注意:不只是integer类型).Bitwise operators perform Boolean algebra on the corresponding bits in the two argument to produce the result.

  The bitwise And operator (&) produces a one in the output bit if both input bits are one; otherwise, it producces z zero

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

  The bitwise EXCLUSIVE OR or XOR (^), produces a one in the output bit if one or the other input bit is 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 is 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, so it is somewhat different. You can perform a bitwise AND, OR, and XOR, but you can't perform a bitwise NOT (presumably to prevent confusion with the logical NOT). For booleans, the bitwise operators have the same effect as the logical operators except that they do not shor circuit. Also, bitwise operations on booleans include an XOR logical operator that is not included under the list of "logical" operators. You cannot user boolean in shift expression.

shift operators (用到的机会比较少,暂时不深入学习)

  The shift operators also manipulate bits. They can be used solely with primitvie, integral type(注意:不只是integer类型).

  The left-shift operator (<<)

  The signed right-shift operator (>>)

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

  (注意:为了简化例子,以8位字节为例)

    如: 5<<3 等于40  00000101 -> 00101000 低位补0  即 5 * 2的3次方

         -5>>3   11111011 -> 11111111 高位补1

        5>>3  00000101 -> 00000000 高位补0

     -5>>>3  11111011-> 00011111 高位补0

  If you shift a char, byte, or short, it will be promoted to int befor the shift takes place, and the result will be an int.

  If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from 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 will be used, so you 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 an operator in Java: The + and += operators can be 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 is attempting to leave out the parentheses when you are even the least bit uncertain about how an expression will evaluate. This is still true in Java.

  2. while(x=y)

    In Java, the result of this expression is not a boolean, but the compiler expects a boolean and won’t convert from an int, so it will 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 is when x and y are boolean, in which case x = y is a legal expression, and in the preceding example, probably an error.)

Case operators

  In Java, casting is safe, with the exception that when you perform a so-called narrowing conversion (that is, when you go from a data type that can hold more information to one that doesn’t hold as much), you run the risk of losing information. Here the compiler forces you to use a cast, in effect saying, “This can be a dangerous thing to do—if you want me to do it anyway you must make the cast explicit.” With a widening conversion an explicit cast is not needed, because the new type will more than hold the information from the old type so that no information is ever lost.

  Java allows you to cast any primitive type to any other primitive type, except for boolean, which doesn’t allow any casting at all. Class types do not allow casting. To convert one to the other, there must be special methods. (You’ll find out later in this book that objects can be cast within a family of types; an Oak can be cast to a Tree and vice 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 to be rounded, use the round( ) methods in java.lang.Math:

  Promotion

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

Java has no "sizeof"

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

A compendium of operators

  (长串例子.略)

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

  Don’t be lulled into thinking everything is safe, though. If you multiply two ints that are 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 that good.

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

  You can see that, with the exception of boolean, any primitive type can be cast to any other primitive type. Again, you must be 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 编程思想,第四版)学习笔记(四)之Operators的更多相关文章

  1. 《Linux命令、编辑器与shell编程》第三版 学习笔记---002

    <Linux命令.编辑器与shell编程>第三版 学习笔记---001 Linux命令.编辑器与shell编程 Shell准备 1.识别Shell类型 echo  $0 echo $BAS ...

  2. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control

    Access control ( or implementation hiding) is about "not getting it right the first time." ...

  3. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup

    Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...

  4. 《C++编程思想》部分章节学习笔记整理

    简介 此笔记为<C++编程思想>中部分章节的学习笔记,主要是第15章--多态性和虚函数 的学习笔记,此外还有少量其他章节的内容. 目录 文档:<C++编程思想>

  5. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings

    Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...

  6. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(二)之Introduction to Objects

    The genesis of the computer revolution was a machine. The genesis of out programming languages thus ...

  7. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十四)之Type Information

    Runtime type information (RTTI) allow you to discover and use type information while a program is ru ...

  8. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions

    The ideal time to catch an error is at compile time, before you even try to run the program. However ...

  9. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十一)之Holding Your Objects

    To solve the general programming problem, you need to create any number of objects, anytime, anywher ...

随机推荐

  1. 解决2020-3-27 github无法访问

    早上的github无法访问了 查找资料后,发现可以修改 hosts 文件 右键 属性 将只读去掉 进行修改 其中的ip去如下地址拿 试一下,大功告成

  2. 小米官网轮播图js+css3+html实现

    官网轮播: 我的轮播: 重难点: 1.布局 2.图片和右下角小圆点的同步问题 3.setInterval定时器的使用 4.淡入淡出动画效果 5.左右箭头点击时,图片和小圆点的效果同步 6.另一种轮播思 ...

  3. MySQl数据类型和条件限制

    数据库的增删改查已经介绍完毕,今天从表的详细操作开始讲解 表操作 今日内容 1.数据类型 建表的时候,字段都有对应的数据类型 整型 浮点型 字符类型(char与varchar) 日期类型 枚举与集合 ...

  4. PHP session反序列化

    先来了解一下关于session的一些基础知识 什么是session 在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 ...

  5. ThreadPoolTaskExecutor 中 corePoolSize vs. maxPoolSize

    1. 概览 Spring中的 ThreadPoolTaskExecutor 是一个 JavaBean ,提供围绕java.util.concurrent.ThreadPoolExecutor 的抽象实 ...

  6. 算法学习 八皇后问题的递归实现 java版 回溯思想

    1.问题描述 八皇后问题是一个以国际象棋为背景的问题:如何能够在 8×8 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行.纵行或 ...

  7. .NET Core技术研究-配置读取

    升级ASP.NET Core后,配置的读取是第一个要明确的技术.原先的App.Config.Web.Config.自定义Config在ASP.NET Core中如何正常使用.有必要好好总结整理一下,相 ...

  8. postman设置全局变量及参数化

    笔者第一次记录使用过程,仅供参考 测试过程中接口的前缀都是一样的,所以我们可以将这个前缀作为全局变量来使用 首先,打开postman点击这里的小齿轮设置 在这里就可以进行变量的一个添加,添加好之后记住 ...

  9. coding++ :HttpClientUtils 封装

    1.关键 JAR  <!-- <<===================>> httpClient <<===================>> ...

  10. 将图片base64格式转换为file对象并读取(两种方式读取)

    两种方式读取,一种URL.createObjectURL,另一种fileReader   var base64 = ` data:image/jpeg;base64,/9j/4AAQSkZJRgABA ...