This question already has answers here:
Error while using .equals() method on multi dimensional array java [duplicate]
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
System.out.print("Enter the Item number of what is to be changed");
String itemNO = in.next();
for (int i = 0; i<NewItem.itemArray.length; i++)
{
String value = NewItem.itemArray[i][3];
if(value.equals(itemNO))
{
//Rest of the code here
}
}
When running the program, it throws an exception at "if(value.equals(itemNO))". This is the error it shows.
Exception in thread "main" java.lang.NullPointerException
at DeleteItem.deleteItem(DeleteItem.java:34)
at EditItemDetails.editItem(EditItemDetails.java:25)
at CD_Universe.editItemDetailsActions(CD_Universe.java:84)
at CD_Universe.main(CD_Universe.java:109)
value can still be null in your code, and therefore attempting to invoke equals() on it will throw an exception. Just because you are able to iterate over given element does not mean it has been initialized. I assume you have created an array of given size, but certain elements of that array have never been assigned a value.
You may fix this by populating the elements or adding a null check: if (value != null)...
In Java, only arrays of primitives are initialized with default values (since primitive type cannot be null. Arrays of reference types will not have their values initialized.
Related
This question already has answers here:
How can I properly compare two Integers in Java?
(10 answers)
Is it safe to compare two `Integer` values with `==` in Java? [duplicate]
(2 answers)
How do I compare two Integers? [duplicate]
(9 answers)
Comparing Integer objects [duplicate]
(5 answers)
Closed 1 year ago.
List<Integer> test = List.of(955, 955);
if (test.get(1) == test.get(0))
...
Above condition results in false
List<Integer> test = List.of(955, 955);
int a = test.get(1);
int b = test.get(0);
if (a == b)
...
The above condition returns true.
Why is that the case? What is the difference between the snippets?
In one case, you're comparing two Integer object references. In the other case, you're comparing two ints. When using the == operator to compare object references, it will return False if they are not the same object, even if they do wrap the same value.
In the first example, you are comparing references. In your example, you have two different objects with different references and the same values.
In the second example, you are using automatic unboxing which creates new integers in stack memory, and integer comparison which works what you expect. Automatic unboxing can produce NullPointerException in case of null.
First Code Snippet:
You are comparing the object reference, meaning the specific object reference that the object is pointing too. In this case you are comparing an Integer which is a wrapper class for int.
Second Code Snippet:
You are comparing the an 'int' to another 'int'.
Example:
Think about it this way: if two people had the name John, in the first scenario we are comparing the people named John, whereas in the second scenario we are comparing the name John only. I hope that helped!
This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}
This question already has answers here:
Comparator.nullsFirst with null-safe-comparator
(3 answers)
Closed 4 years ago.
When i am trying this :
if (serviceEndDateList != null && !serviceEndDateList.isEmpty()) {
LOG.info("serviceEndDateList::"+serviceStartDateList);
Collections.sort(serviceEndDateList,
Collections.reverseOrder());
}
I am getting below stacktrace:
java.lang.NullPointerException
at java.util.Collections$ReverseComparator.compare(Collections.java:5117)[:1.8.0_181]
at java.util.Collections$ReverseComparator.compare(Collections.java:5108)[:1.8.0_181]
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)[:1.8.0_181]
at java.util.TimSort.sort(TimSort.java:220)[:1.8.0_181]
at java.util.Arrays.sort(Arrays.java:1512)[:1.8.0_181]
at java.util.ArrayList.sort(ArrayList.java:1462)[:1.8.0_181]
at java.util.Collections.sort(Collections.java:175)[:1.8.0_181]
The output of the log is :
serviceEndDateList::[2001-05-17]
serviceEndDateList::[2001-05-17, 2001-05-17]
As the object is not null why this Exception is being Thrown!!
The issue is that your input list serviceEndDateList contains with the highest probability a null value that causes trouble in comparison.
You have to define, whether the null values will be included at the beginning or the end of a collection. Use the special wrapper for this case that pushes all the null values to the end:
Collections.sort(serviceEndDateList, Comparator.nullsLast(Comparator.reverseOrder()));
From the Comparator JavaDoc (emphesizes mine):
Comparator::nullsFirst is a comparator that considers null to be less than non-null, and compares non-null objects with the supplied Comparator.
Comparator::nullsLast is a comparator that considers null to be greater than non-null, and compares non-null objects with the supplied Comparator.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am creating a Chess program on NetBeans using jButtons as squares, and my java knowledge is limited to what I have learnt at school.
So this line
int verticalValue = Integer.parseInt(newButton.substring(1,1));
returns a nullPointerException and I can't figure it out whatsoever. Here is the relevant code:
static void pawnMovement(JButton but){
String buttonName = but.getName();
String newButton = buttonName;
int verticalValue = Integer.parseInt(newButton.substring(1,1));
The names of all buttons are in the format letterNumber, so I don't see why this shouldn't work.
Thanks!
This code should produce a NumberFormatException as the string from substring(1, 1) will always be empty, unless newButton is null because it hasn't been set.
I would check in your debugger that is has been set. I would also ensure you are trying to parse at least 1 character.
When you do a new JButton("name") - it sets the variable JButton.text as name. Hence, but.getText() should work for you.
In your case, but.getName() returns NULL because you have NOT done but.setName() first. but.setName() is required for but.getName() to work.
Hence, buttonName & newButton are NULL.
Hence, when you do newButton.substring(1,1) - it causes NPE because newButton is NULL
This question already has answers here:
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
Closed 9 months ago.
I have encountered the following problem: I have a java class with a private member like so:
private Arcs[] arcs;
This is not initialised in the constructor because I don't know the length of my vector yet, but it is initialised in the read function, where I read the info from a file.
In this function I do the following:
arcs = new Arcs[n]; //n is a number read from file
Then there is a while cycle in which I read other stuff from the file and I have something like:
while(condition){
...
arcs[i].add(blah); //i is a valid number, smaller than n, and the add function is also correct
...
}
But here I have an error saying NullPointerException and I don't understand why. I would appreciate it, if someone would explain to me what's happening.
Are you actually ever storing an Arcs object in arcs[i]? If not, all elements of arcs[] will be initialized to null. (Hence the NPE)
Do something like this:
while(condition){
// ...
arcs[i] = new Arcs();
arcs[i].add(blah);
// ...
}
Reference:
Java Tutorial: Arrays