什么是声明在Java中布尔变量的正确方法? [英] What is the correct way to declare a boolean variable in Java?

查看:471
本文介绍了什么是声明在Java中布尔变量的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Java。在网上当然我之后,我被要求尝试以下code:

I have just started learning Java. In the online course I am following, I am asked to try the following code:

String email1 = "meme@me.coh";
String email2 = "meme@me.com";
Boolean isMatch = false;

isMatch = email1.equals (email2);

if (isMatch == true){
    System.out.println("Emails match");
}
else{
    System.out.println("Emails don't match");
}

我不明白为什么我要求宣布 isMatch 当下一行我正在比较的电子邮件地址和值赋给<$ C假$ C> isMatch 。结果
我试过以下code这似乎工作一样的:

I don't understand why I'm asked to declare isMatch as false when on the next line i am comparing the email addresses and assigning the value to isMatch.
I've tried the following code which seems to work just the same:

String email1 = "meme@me.coh";
String email2 = "meme@me.com";
Boolean isMatch;

isMatch = email1.equals (email2);

if (isMatch == true){
    System.out.println("Emails match");
}
else{
    System.out.println("Emails don't match");
}

在过程中它并没有解释为什么我声明了 isMatch 为假第一。是否有一个原因,我必须比较的电子邮件地址之前申报 isMatch 假?

On the course it doesn't explain why I'm declaring isMatch as false first. Is there a reason why I must declare isMatch as false before comparing the email addresses?

推荐答案

您不必,但有些人喜欢明确的初始化所有变量(我也是)。尤其是那些谁在各种语言进行编程,它只是更容易有总是初始化的变量,而不是决定逐案规则/语言用的语言。

You don't have to, but some people like to explicitly initialize all variables (I do too). Especially those who program in a variety of languages, it's just easier to have the rule of always initializing your variables rather than deciding case-by-case/language-by-language.

例如Java有布尔默认值,诠释等等。C,另一方面不会自动给出初始值,无论发生什么事是在内存中的是你到底是什么了,除非你自己分配一个值明确。

For instance Java has default values for Boolean, int etc .. C on the other hand doesn't automatically give initial values, whatever happens to be in memory is what you end up with unless you assign a value explicitly yourself.

在你上面的情况下,当你发现时,code的作品一样好没有初始化,尤其自变量中的下一行,这使得它显得尤为冗余设置。有时候,你可以结合这两个行(声明和初始化 - 在一些其他职位所示),并获得最佳的两种方法,即用 email1.equals的结果初始化您的变量(EMAIL2); 操作

In your case above, as you discovered, the code works just as well without the initialization, esp since the variable is set in the next line which makes it appear particularly redundant. Sometimes you can combine both of those lines (declaration and initialization - as shown in some of the other posts) and get the best of both approaches, i.e., initialize the your variable with the result of the email1.equals (email2); operation.

这篇关于什么是声明在Java中布尔变量的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆