简体   繁体   English

布尔值和== vs =

[英]Boolean and == vs =

The language is Java. 语言是Java。 Given this: 鉴于这种:

public static void main(String[] args) {
    Boolean b1 = true;
    Boolean b2 = true;
    int i1 = 1;

    if (b1 = true) //line 5
    if (b1 == true}  // line 6

I understand that b1 == true is a equivalent test , which will give the result : true OR false. 我知道b1 == true是一个等价的测试,它将给出结果:true或false。 However, with b1 = true , which to my understanding is a declaration, which should return nothing but in this case : b1 = true returns true, exactly the same as == test? 但是,如果b1 = true ,我理解的是一个声明,除了在这种情况下它应该返回: b1 = true返回true,与== test完全相同?

Can you explain why? 你能解释一下原因吗? Thanks! 谢谢!

if (identifier = literal) evaluates to: if (identifier = literal)求值为:

identifier = literal;  
if (identifier)

first you assign the literal to the identifier. 首先将文字分配给标识符。 then you test it post assignment 然后你测试它分配后

When you write 当你写作

b1 = true;

true is assigned to b1. true分配给b1。

When you write 当你写作

if(b1 = true)

first the assignation is done and then the expression is evaluated and the expression evaluates to value of b1 ie true . 首先完成赋值,然后计算表达式,表达式求值为b1即为true

Well the reason both return true is simply because both expressions are true. 两者都返回true的原因很简单,因为两个表达式都是真的。

b1 = true is an assignment --> You tell java that b1 is true and when it evaluates it becomes true because here you simply say b1 is true. b1 = true是一个赋值 - >你告诉java b1是真的,当它计算它时它变为真,因为这里你简单地说b1为真。

b1 == true is a condition --> This is the line that makes some sense because you are now checking if [value of] b1 equals to true and this will evaluate to true or false depending on if b1 is true. b1 == true是一个条件 - >这是一个有意义的行,因为你现在正在检查b1的[value]是否等于true,这将根据b1是否为真来评估为真或假。 Note that you could just write b1 because it's already a boolean (true or false). 请注意,您可以编写b1,因为它已经是布尔值(true或false)。

I don't think you have realized it but you are using the object-type Boolean and not the primitive type boolean. 我认为你没有意识到它,但你使用的是对象类型的布尔值而不是基本类型布尔值。 You should stick to the one with a lowercase b if you don't really know the diffrence between object-based types and primtive types in Java. 如果你真的不知道Java中基于对象的类型和原始类型之间的差异,你应该坚持使用小写字母b。

btw I didn't know that Java allowed assignment to be used as a expression. 顺便说一句我不知道Java允许赋值用作表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM