Java에서 &와 &&의 차이점은 무엇입니까?
나는 항상 &&
Java true
의 &
연산자가 부울 피연산자가 모두인지 여부를 확인하는 데 사용되고 연산자는 두 정수 유형에서 비트 단위 연산을 수행 하는 데 사용 된다고 생각했습니다 .
최근에 나는 &
연산자가 두 부울 피연산자가 모두인지 여부를 확인하는 데 사용될 수 있다는 것을 알게되었습니다. 단일 true
차이점은 LHS 피연산자가 false 인 경우에도 RHS 피연산자를 검사한다는 것입니다.
&
Java 의 연산자가 내부적으로 과부하 되었습니까? 아니면 이것 뒤에 다른 개념이 있습니까?
& <-두 피연산자를 모두 확인합니다.
&& <-결과가 거짓이므로 첫 번째 피연산자가 false로 평가되면 평가를 중지합니다.
(x != 0) & (1/x > 1)
<-이것은 평가 (x != 0)
하고 평가 (1/x > 1)
한 다음 &를 수행 한다는 의미 입니다. 문제는 x = 0 인 경우 예외가 발생한다는 것입니다.
(x != 0) && (1/x > 1)
<-이것은 평가를 의미 (x != 0)
하고 이것이 참인 경우에만 평가 (1/x > 1)
하므로 x = 0이면 완벽하게 안전하며 (x! = 0)이 거짓으로 평가되면 예외가 발생하지 않습니다. 모든 것이 직접 거짓으로 평가됩니다 평가하지 않고 (1/x > 1)
.
편집하다:
exprA | exprB
<-이것은 평가 exprA
하고 평가 exprB
한 다음 수행하는 것을 의미 합니다 |
.
exprA || exprB
<-이 수단을 평가 exprA
하고이 경우에만 false
다음 평가 exprB
와 수행 ||
.
두 피연산자를 모두 평가하여 지연 평가자가 아닌 비트 연산자의 주요 특성은 다음 예제와 같이 피연산자의 각 바이트를 비교한다고 생각합니다.
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
그것은 인수의 유형에 달려 있습니다 ...
정수 인수의 경우 단일 앰퍼샌드 ( "&")는 "비트 AND"연산자입니다. 이중 앰퍼샌드 ( "&&")는 두 개의 부울 인수 외에는 정의되지 않습니다.
부울 인수의 경우 단일 앰퍼샌드는 (무조건) "논리 AND"연산자를 구성하고 이중 앰퍼샌드 ( "&&")는 "조건부 논리 AND"연산자입니다. 즉, 단일 앰퍼샌드는 항상 두 인수를 모두 평가하지만 이중 앰퍼샌드는 첫 번째 인수가 참이면 두 번째 인수 만 평가합니다.
다른 모든 인수 유형 및 조합의 경우 컴파일 타임 오류가 발생해야합니다.
&&는 단락 연산자이고 &는 AND 연산자입니다.
이 시도.
String s = null;
boolean b = false & s.isEmpty(); // NullPointerException
boolean sb = false && s.isEmpty(); // sb is false
내 대답이 더 이해하기 쉽다고 생각합니다.
&
와 사이에는 두 가지 차이점이 있습니다 &&
.
그들이 논리 AND로 사용하는 경우
&
그리고 &&
논리적 일 수있다 AND
, 할 때 &
또는 &&
좌우 표현이 모두 사실 결과, 전체 연산 결과가 사실이 될 수 있습니다.
때 &
와 &&
논리적으로 AND
, 차이가있다 :
&&
logical로 사용할 때 AND
왼쪽 표현식 결과가 false이면 오른쪽 표현식이 실행되지 않습니다.
예를 들어 보자.
String str = null;
if(str!=null && !str.equals("")){ // the right expression will not execute
}
사용하는 경우 &
:
String str = null;
if(str!=null & !str.equals("")){ // the right expression will execute, and throw the NullPointerException
}
다른 예 :
int x = 0;
int y = 2;
if(x==0 & ++y>2){
System.out.print(“y=”+y); // print is: y=3
}
int x = 0;
int y = 2;
if(x==0 && ++y>2){
System.out.print(“y=”+y); // print is: y=2
}
비트 연산자로 사용할 수 있습니다
&
can be used as Bitwise AND
operator, &&
can not.
The bitwise AND " &" operator produces 1 if and only if both of the bits in its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0.
From the wiki page:
http://www.roseindia.net/java/master-java/java-bitwise-and.shtml
it's as specified in the JLS (15.22.2):
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
The "trick" is that &
is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.
‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.
For example: - Condition1 && Condition2
If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.
If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.
‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).
For example:-
int a=12; // binary representation of 12 is 1100
int b=6; // binary representation of 6 is 0110
int c=(a & b); // binary representation of (12 & 6) is 0100
The value of c is 4.
for reference , refer this http://techno-terminal.blogspot.in/2015/11/difference-between-operator-and-operator.html
&&
and ||
are called short circuit operators. When they are used, for ||
- if the first operand evaluates to true
, then the rest of the operands are not evaluated. For &&
- if the first operand evaluates to false
, the rest of them don't get evaluated at all.
so if (a || (++x > 0))
in this example the variable x won't get incremented if a was true
.
With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.
The difference lies behind the scene where the information is being processed. When you right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:
left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false
When you write an expression (a != 0) && ( b != 0)
when a= 0 and b = 1, the following happens:
a != 0 -->false
expression returns false
Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.
Besides && and || being short circuiting, also consider operator precedence when mixing the two forms. I think it will not be immediately apparent to everybody that result1 and result2 contain different values.
boolean a = true;
boolean b = false;
boolean c = false;
boolean result1 = a || b && c; //is true; evaluated as a || (b && c)
boolean result2 = a | b && c; //is false; evaluated as (a | b) && c
& is a bitwise operator plus used for checking both conditions because sometimes we need to evaluate both condition. But && logical operator go to 2nd condition when first condition give true.
all answers are great
, and it seems that no
more answer is needed
but I just wonted to point out something about &&
operator called dependent condition
In expressions using operator &&, a condition—we’ll call this the dependent condition
—may require another condition to be true for the evaluation of the dependent condition to be meaningful.
In this case, the dependent condition should be placed after the && operator to prevent errors.
Consider the expression (i != 0) && (10 / i == 2)
. The dependent condition (10 / i == 2)
must appear after
the &&
operator to prevent the possibility of division by zero.
another example (myObject != null) && (myObject.getValue() == somevaluse)
and another thing: &&
and ||
are called short-circuit evaluation because the second argument is executed or evaluated only if
the first
argument does not suffice
to determine
the value
of the expression
References: Java™ How To Program (Early Objects), Tenth Edition
참고URL : https://stackoverflow.com/questions/5564410/what-is-the-difference-between-and-in-java
'IT' 카테고리의 다른 글
클래스 내에서 정적 메소드를 호출합니까? (0) | 2020.06.09 |
---|---|
자바에서 문자열의 바이트 (0) | 2020.06.08 |
이진 파일을 비교하여 동일한 지 확인하는 방법은 무엇입니까? (0) | 2020.06.08 |
줄 바꿈이 파일의 마지막 문자 인 경우 어떻게 삭제합니까? (0) | 2020.06.08 |
curl을 사용하여 PHP에서 HTTP 코드 가져 오기 (0) | 2020.06.08 |