|和||,&和&&的区别

| : 会检查每个 条件的真伪,再作“或”运算 (光棍的不怕死)
||: 按照条件写的顺序,直到一个为true时,后面的条件则再也不检查,直接进入条件 
& : 会检查每个 条件的真伪,再作“与”运算  (光棍的不怕死)
&&: 按照条件写的顺序,直到一个为false时,后面的条件则再也不检查,直接跳出java

&是位运算符,表示按位与运算。&&是逻辑运算符,会短路。it

 

 

 

例如:io

 public static void main(String []args)
 {
  String str=null;
  if(str!=null && str.length()==1)
  {
   System.out.println("sssssss");
  }else
  {
   System.out.println("ccccccccccc");
  }
 }thread

打印cccccccstatic

 

str为null  str!=null结果为false,后面的str.length()==1就不会检查后面的值了,if()中直接返回false。不会报错。di

 

改一下:位运算

 public static void main(String []args)
 {
  String str=null;
  if(str==null && str.length()==1)
  {
   System.out.println("sssssss");
  }else
  {
   System.out.println("ccccccccccc");
  }
 }运算符

结果:void

Exception in thread "main" java.lang.NullPointerException
 at edit.main(edit.java:6)

str==null结果为true,则会检查后面的值

 

&为按位与(AND)  按位与运算符“&”,若是两个运算数都是1,则结果为1。其余状况下,结果均为零。看下面的例子:  00101010 (值为42) &   0001111 (值为15)   00001010 (值为10)