Java - NullPointerException in Array [duplicate] - java

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

Related

Why does the output for while (arar==arr){ arr[0]=2; } display this ([I#60e53b93)? [duplicate]

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);
}

String Array Assignment in Java [duplicate]

This question already has answers here:
Arrays constants can only be used in initializers error
(5 answers)
Closed 4 years ago.
Code:
String Foo[];
Foo={"foo","Foo"};
Error at Line 2: Illegal Start of expression
The code works if I say:
String Foo[]={"foo","Foo"};
Why does this happen, and how should I do the required without generating an error? This also happens with other data types.
Would appreciate if you could explain in layman terms.
{"foo","Foo"} is an array initializer and it isn't a complete array creation expression:
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
Java Specification
Use new String[] {"foo","Foo"} instead.
You have to initialize the string array:
String foo[] = new String[]{"foo, "Foo"}; Or
String foo[] = {"foo, "Foo"};
Modern IDEs give error for not initializing the array objects. You can refer more details here:
http://grails.asia/java-string-array-declaration

.substring() throws a nullPointerException [duplicate]

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

.equals() method not working with multi dimensional arrays [duplicate]

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.

Is there a method in Java that lets you find the index of an element in an int array? [duplicate]

This question already has answers here:
Where is Java's Array indexOf?
(13 answers)
Closed 9 years ago.
I need to assess the last int in an array where a certain conditional is met. My program can work out what that int is, but it needs to also know where it's position was in the array. I searched on stack-exchange and someone posted this:
Arrays.asList(array).indexOf(indexPos);
As a possible solution, but I am not sure if I am doing it right, because I get the error
cannot find symbol. I also allowed:
int test = Arrays.asList(array).indexOf(indexPos);
And then tried to print test, but I could not even get to that point. Thanks.
You may need to import java.util.Arrays to get the symbol.
There is no guaranteed way of finding the position of an element in an array except for looping over the array - that is basically what your asList snippets are doing.
This will work as long as your arrays don't have duplicate values. If you need to handle duplicate values, you may need to rethink you data structs.
Someone posted a similar question that someone else asked. It seems that this has worked for me.
The Code is:
java.util.Arrays.asList(seq).indexOf(indexPos);
and the Question:Where is Java's Array indexOf?
Yes you have the method defined in List interface. So you need to use asList() function followed by indexOf() function.
If the array is not sorted you can use java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search function(improves performance) java.util.Arrays.binarySearch(theArray, o)
As for the error make sure you have imported java.util.Arrays. Also that you have defined Array seq and int indexPos which makes your code int test = Arrays.asList(seq).indexOf(indexPos);.

Categories