I am new to Java, and need to figure out process when a method return null and reference variable.
Here is the code of the method:
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;
}
}
What happens when a method returns null and reference variable, while having a class data type?
Please explain in easy words.
null is valid value for any Object in Java. Since Lot is also a Java object. null is valid.
But
If you are not careful you may end up with NullPointerException.
Eg:
Lot lot=someInstance.getLot(2); // say lot is null
Then
String something=lot.getThis(); // here is null.getThis()
You will end up NullPointerException here.
You need to handle with care these cases to avoid NullPointerException.
Eg:
Lot lot=someInstance.getLot(2);
if(lot!=null){
String something=lot.getThis();
}
Null in java means, that your instance (variable) contains no object. You can use it, but you must not call any method on that object, because If you did so, you'd get a NullPointerException.
When null is returned from a method, it usually means that the method was not able to create a meaningful result. For example the method, that reads data from database was not able to find the specified object or some error occurred during the method run.
If a method can return null, then you should check the result before further processing like. See the example of raising a sallary of an employee:
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);
}
Since null is a value, your program will compile fine.
But depending in the situation you are using a null variable you may end up with NullPointerException while running your app.
Related
I'm trying to catch an exception. I thought that checking whether the String is empty would help, but it doesn't seem to work. The value in the actual column for the object in my class is "(undefined)". It seems to be that by default. How can I explicitly check to see if it is undefined?
notifications.getString(ParseConstants.KEY_FEED_TYPE).isEmpty()
Heads up. The following doesn't work either:
notifications.getString(ParseConstants.KEY_FEED_TYPE).equals("(undefined)");
it's checking using Android default function like
if (!TextUtils.isEmpty(notifications.get(ParseConstants.KEY_FEED_TYPE))) {
// its not null value success
} else {
// here getting to null value Fail
}
I did the following. Instead of looking for a String (in which case the field entry would be truly empty, and not (undefined)), I checked to see if the object was null after dropping the String from getString.
if (notifications.get(ParseConstants.KEY_FEED_TYPE) != null) {
// Do something.
} else {
// Do something else.
}
I have this:
String object = "";
try {
object = data.getString("url");
System.out.println("Url Object:" + object);
}
catch (JSONException e) {
e.printStackTrace();
}
System.out.println("object is:" + object);
if (object!= null ) {
// doSomething
} else {
// is Null
}
and although this is printed:
object is: null
The code enters the if condition and not the else.
What am I missing?
EDIT: where data is a JSONObject. I now want to test the case that url is null. Therefore, I know that data is null and I can see it printed.
Your code is an anti pattern. Move the code that processes 'string' inside the 'try' block. Don't just catch exceptions and then continue as though they didn't happen, and have to sort out again whether you're in a valid state. That's what the 'try' block is for. If you're still in it, you're in a valid state.
Please note that getString(..) is returning "null" (as a String, when ob.toString() do that). So when you assign it to object, it is a String: "null", not null.
To correct your code one way would be:
if (!object.equals("null")) {
// doSomething
} else {
// is Null
}
Another solution would be setting object to be null if getString() returns "null":
if (data.getString("url").equals("null"))
object = null;
Don't initialize your String object to "" if you want it to be null if the json parsing bits fail.
Change your top line to:
String object = null;
More to the point, check out https://stackoverflow.com/a/21246501/599075
The only explanation to your case is that the data.getString("url"); is returning a "null" String value.By the way I recommend you these points :
Initialize your object by a null reference (String object = null;)
Change the if condition (if(object!=null) && !object.isEmpty())
Otherwise, try to print entirely the content of the data object to the console so you can check the json content you are trying to parse.
(Sorry if I made some language mistakes)
I have the following code within a for loop to see if a string equals a search string:
if(Data.coord[i].equals(Data.search))
I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:
Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)
Thanks
You should compare the constant to your parameter since it can be null.
For example if Data.search is a constant which you are searching for you should do this:
if(Data.search.equals(Data.coord[i]))
In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.
You have an unpopulated element in your array i.e.
Data.coord[i]
is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.
String[] coord = new String[100];
This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.
You can try.
String data= Data.coord[i];
if(data != null && data.equals(Data.search))
you can avoid your problem in two ways:
In the case coord[i] should not be null
if (Data.coord[i] != null) {
if(Data.coord[i].equals(Data.search)) {
}
} else {
logger.error("Unexpected Behavior: coord[i] should not be null");
}
Note: You can replace the logger message by a more appropriated code that fit to your requirement.
In the case your your coord[i] can be null
comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.
if (Data.search.equals(Data.coord[i])) {}
Read this to understand What is a Null Pointer Exception?
if coord[] is initialized properly, value of Data.coord[i] may be null. You can check
if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}
Try this:
if(DATA != null && Data.coord[i].equals(Data.search))
Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.
I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null