Null pointer exception in array initialized to null [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
This is the following code. I have to make the array null for a purpose, then when I initialize the array components to 1, it shows null pointer exception. How to handle this?
public static void main(String[] args) {
double[] a;
a=null;
if(a==null)
for(int i=0;i<12;i++)
a[i]=1;
}

You need to create an array object and assign it to the array variable before trying to use the variable. Otherwise you are creating the very definition of a NullPointerException/NPE: trying to use (dereference) a reference variable that refers to null.
// constant to avoid "magic" numbers
private static final int MAX_A = 12;
// elsewhere in code
if (a == null) {
a = new double[MAX_A]; // you need this!
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}

a[i]=1 // That's the problem.
You are trying to assign a value, without actually allocating memory (aka, not initializing). Indirectly you are trying to invoke a operation on NULL object which obviously results in Null Pointer Exception.
So
if(a == null){
a = new double[12];
//other for loop logic
}
will solve the problem. 12 is the size of the array (The number of double value it can hold/store).

You have to create the array before initialization -
double[] a;
a=null;
if(a==null){
a = new double[12];
for (int i = 0; i < a.length; i++) {
a[i] = 1.0;
}
}
Since double array a is null when you are trying to access the array element like this -
a[i]=0;
It produces NullPointerException.

At the first place why don't you make it NULL while declaring the variable double[] a = null;
The reason why you are getting NullPointer is because you are trying to access it when it is NULL a[i]=1;. This is as good as String name = null; name.toString(); You are doing some operation on an NULL value so getting NullPointer.
Just initialize it and then try to access it and you will not get NullPointer. This is like you should first allocate some memory and then try to access the memory location, when no memory is allocated, you will get NullPointer which tells you that there is no memory allocated yet. Hope this helps.

Related

How to get around array.equals(otherArray) evaluating to null? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}

Void function returns changed array, but not a changed integer? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
{
int[] n = new int[4];
n[0]=1;
n[1]=3;
n[2]=4;
n[3]=5;
for(int i=0; i<4; i++)
{
System.out.print(n[i]+ " ");
}
menjava(n);
System.out.println();
for(int i =0;i<4;i++)
{
System.out.print(n[i]+ " ");
}
}
public static void menjava(int[] a)
{
a[0]=1*10;
a[1]=3*10;
a[2]=4*10;
a[3]=5*10;
}
}
http://imgur.com/0CNqY9A //the result in console
{
int n = 1;
System.out.println(n);
menjava(n);
System.out.println(n);
}
public static void menjava(int st)
{
st = 4;
}
}
http://imgur.com/dAqzuez //the result in console
So why did the Array get returned, but the integer stayed the same (whcih in my mind should). I can't find anything on why the array get's returned in an void function.
The reference to the array is not returned nor changed.
The array referenced has been changed.
int[] n = new int[4];
In this code n is a reference to an array and this reference is copied when you pass it to a method. This reference is not changed.
Your issue here is that Java is a pass by value language. This means in your situation you are providing your method menjava with what might as well be a temporary array that contains the same values as your original array n. So when this array is passed to menjava it does the calculations, but to this temporary array that your main method doesn't know about.
The easiest fix here is to have your menjava method return the array it worked on and set your array to that value in the calling function something like this:
public static int[] menjava(int[] a){
//changes to array a
return a;
}
and then in your calling function:
{
//your other code
n = menjava(n);
//the rest of your code
}

Check if array is NULL at a Specific Index returns NullPointerException

I am trying to add an object of type Car to an Array of cars, I do not have a specific index within the array that I want the car to go into, I just want to add the car to the first empty and available index that doesn't have a car object already in there. Here is my code:
protected static final int MaxCars = 5;
protected Car[] cars = new Car[MaxCars];
public void addCar(Car c)
{
for(int i = 0; i < MaxCars; i++)
{
if (cars[i] == null)
{
cars[i] = c;
break;
}
}
incrementNumInTeam();
}
On the if statement inside the for loop I am getting the a NullPointerException .. how can I overcome this?
Your variable cars is likely null at the time the if block is called. Your error is present but likely elsewhere in your code. Check to be sure that you're not shadowing the cars variable and that the variable being initialized is the same one being read.

Java - Why am I getting this NullPointerException?

I don't understand why this is giving me a null pointer exception when I try to add a value to the a1[i] array.
public class Array {
String text;
int total = 0, count = 0;
Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);
public void setData() {
int i=0;
System.out.println(a1.length);
do {
System.out.println("Enter some data: ");
text = scan.next();
if (text.equals("end"))break;
a1[i].text = text; //I get a null pointer exception here. Not sure why.
i++;
} while (true);
}
Everything initialized in the a1 array is null. You'd have to put a new instance of Array() in there before doing anything with the member methods.
What this translates to: Every time you want to do something with a1[i], you'd have to have a new instance of Array in there first.
Example:
for(int i = 0; i < n; i++) {
a1[i] = new Array();
}
Because there isn't an object stored at a1[i]. What you're essentially saying at that line is:
null.text = text
which will break every time
You are getting a null-pointer exception, because you have allocated the space for 100 array elements, but you still need to initialize them:
So before accessing a1[i].text you need to initialize it by calling a1[i] = new Array()
Also I am quite sure, that you actually wanted to create some other kind of object, not Array. Array the class you are currently writing, as I understand, so you probably want to have multiple Strings, e.g. String[].
I recommend to you to use a LinkedList instead.
Array[] a1 = new Array[100]; //here you just create an array of references to objects which are set to null
a1[i].text = text; //before this line you should assign to a1[i] a reference to Array object for example a1[i] = new Array();

How can I initialize an array with an enhanced for-loop?

I was optimizing an application and wanted to change my for loops to enhanced loops:
From:
for (int m = 1;m < MAX_BEREN;m++)
{
Wasberen[m] = new Wasbeer();
Wasberen[m].YYY = r.nextInt(SchermY - 28);
}
to:
for (Wasbeer a : Wasberen)
{
if (a!=null)
{
a = new Wasbeer();
a.YYY = r.nextInt(SchermY - 28);
}
}
I get a NullPointerException, because it probably doesnt know how much 'beren' can be in
the array, but I'm not sure how to manage the same as the loop above (MAX_BEREN = 11).
If the array reference ('Wasberen' in this case) in an enhanced for statement is null, then a NullPointerException will result when the statement is executed.
For initializing arrays, you should stick to the syntax you had before.
You can't use the enhanced for-loop in Java to fill an array. (I'm assuming your Wasberen array was already created before - if not, this will get you a NullPointerException in both variants.)
Your code (simplified)
for (Wasbeer a : Wasberen)
{
a = ...;
}
is equivalent to
for (int i = 0; i < Wasberen.length; i++)
{
Wasbeer a = Wasberen[i];
a = ...;
}
This assignment will change the local variable a, but will have no effect on the contents of the array.

Categories

Resources