这个Java返回语句是什么意思?

4

我正在查看一些代码片段,发现了一个我以前从未见过的return语句。这是什么意思?

return checkDB != null ? true : false;

这是整个方法的代码,供参考:

private boolean checkDataBase(){
        SQLiteDatabase checkDB = null;
        try{
            String pathToDB = dbPath + dbName;
            checkDB = SQLiteDatabase.openDatabase(pathToDB, null, SQLiteDatabase.OPEN_READONLY);
        }catch(SQLiteException e){
            //database does't exist yet.
        }
        if(checkDB != null){
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

“快速问题”问:“生命的意义是什么?”虽然这是一个“快速”的问题,但是答案需要更长时间。 - Andrew Thompson
4个回答

8

return checkDB != null?相同,它是一个“三元运算符”。例如:a ? b : c的作用与以下方法体相同:{ if(a) { return b; } else { return c; } }


是的,这是一个巧妙伪装的if (x == true) { return true }的版本。 - Voo
感谢Aaron和其他回复的人。现在一切都清楚了! - james246

4

这是一个三元语句,可以理解为:

if(checkDB != null) {
   return true;
}
else {
    return false;
}

1

return checkDB != null ? true : false;return checkDB != null; 是完全相同的。


1

它被称为三元操作,是一种漂亮的单行变体,可用于if else逻辑。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接