Java 当一个方法返回null时会发生什么
我是Java新手,需要弄清楚一个方法何时返回null和引用变量 以下是该方法的代码:Java 当一个方法返回null时会发生什么,java,Java,我是Java新手,需要弄清楚一个方法何时返回null和引用变量 以下是该方法的代码: public Lot getLot(int lotNumber) { if((lotNumber >= 1) && (lotNumber < nextLotNumber)) { // The number seems to be reasonable. Lot selectedLot = lots.get(lotNumber - 1);
public Lot getLot(int lotNumber)
{
if((lotNumber >= 1) && (lotNumber < nextLotNumber)) {
// The number seems to be reasonable.
Lot selectedLot = lots.get(lotNumber - 1);
// Include a confidence check to be sure we have the
// right lot.
if(selectedLot.getNumber() != lotNumber) {
System.out.println("Internal error: Lot number " +
selectedLot.getNumber() +
" was returned instead of " +
lotNumber);
// Don't return an invalid lot.
selectedLot = null;
}
return selectedLot;
}
else {
System.out.println("Lot number: " + lotNumber +
" does not exist.");
return null;
}
}
public Lot getLot(int lotNumber)
{
if((lotNumber>=1)和&(lotNumber
当一个方法返回null和引用变量,同时拥有一个类数据类型时,会发生什么
请简单解释。
null
是Java
中任何对象的有效值。因为Lot
也是Java
对象<代码>空值
有效
但是
如果不小心,可能会导致NullPointerException
例如:
然后
您将在此处结束NullPointerException
您需要小心处理这些情况,以避免出现NullPointerException
例如:
null
是Java
中任何对象的有效值。因为Lot
也是Java
对象<代码>空值
有效
但是
如果不小心,可能会导致NullPointerException
例如:
然后
您将在此处结束NullPointerException
您需要小心处理这些情况,以避免出现NullPointerException
例如:
由于
null
是一个值,因此您的程序将可以正常编译
但是,根据您使用
null
变量的情况,在运行应用程序时,您可能会遇到NullPointerException
。由于null
是一个值,因此您的程序可以正常编译
但是,根据您使用
null
变量的情况,在运行应用程序时可能会出现NullPointerException
。null
在java中意味着您的实例(变量)不包含任何对象。您可以使用它,但不能对该对象调用任何方法,因为如果这样做,您将得到一个NullPointerException
当从方法返回null
时,通常意味着该方法无法创建有意义的结果。例如,从数据库中读取数据的方法无法找到指定的对象,或者在方法运行期间发生了一些错误
如果一个方法可以返回null,那么您应该在进一步处理之前检查结果,如。请参见提高员工薪酬的示例:
Employee e = database.getEmployeeById(1);
if (e==null) //this is the check
{
System.out.println('There is no such employee');
}
else
{
e.setSallary(e.getSallary() * 1.1);
}
Null
在java中表示实例(变量)不包含对象。您可以使用它,但不能对该对象调用任何方法,因为如果这样做,您将得到一个NullPointerException
当从方法返回null
时,通常意味着该方法无法创建有意义的结果。例如,从数据库中读取数据的方法无法找到指定的对象,或者在方法运行期间发生了一些错误
如果一个方法可以返回null,那么您应该在进一步处理之前检查结果,如。请参见提高员工薪酬的示例:
Employee e = database.getEmployeeById(1);
if (e==null) //this is the check
{
System.out.println('There is no such employee');
}
else
{
e.setSallary(e.getSallary() * 1.1);
}
如果你不小心的话,你可能会得到一个NPE没有什么特别的事情发生。返回
null
类似于返回对任何其他实例的引用。如果不小心,您可能会得到一个NPE..:没有什么特别的事情发生。返回null
类似于返回对任何其他实例的引用。
Lot lot=someInstance.getLot(2);
if(lot!=null){
String something=lot.getThis();
}
Employee e = database.getEmployeeById(1);
if (e==null) //this is the check
{
System.out.println('There is no such employee');
}
else
{
e.setSallary(e.getSallary() * 1.1);
}