DelphiFAQ Home Search:

java.lang.NullPointerException when using arrays?

 

comments27 comments. Current rating: 4 stars (7 votes). Leave comments and/ or rate it.

Question:

Why do I keep getting a "java.lang.NullPointerException" when using arrays?

Answer:

Two possible explanations:
  1. You've indexed past the array bounds
  2. You haven't initialized the array correctly

   // example of an incorrectly initialized array:

       public class Test {
          public static void main(String args[]) {
             String sa[] = new String[5];
             sa[0].charAt(0);
          }
       }

    // example of a correctly initialized array:

       public class Test {
          public static void main(String args[]) {
             String sa[] = new String[5];

             for(int i = 0; i < 5; i++) {
                sa[i] = new String();
             }
 
             sa[0].charAt(0);
          }
       }

Content-type: text/html

Comments:

You are on page 2 of 2, other pages: 1 [2]
2009-06-29, 22:25:57
anonymous from China  
what is a good solution! Thanks a lot!
2009-08-08, 05:38:31
anonymous from India  



Keywords:
2009-10-05, 12:54:11
anonymous from United Kingdom  
well this should be correct, but i get a java.lang.NullPointerException error at the first line at the for loop... i really don't see anything wrong

public boolean CheckForSpaceAdd(Space [] X, Vehicle Y) {
for (int i=0;i<X.length; i++){
               
        if (X[i].SpaceAv.equals('free')){
            X[i].LicPlate = Y.licPlate;
            X[i].SpaceAv='full';
            Y.ParkedAt=X[i].GetType();
           
        }
else{
            return false;
        }
           
           
        }
            return false;
       
                                   
   
    }


any thoughts?
2009-10-29, 16:05:17
f4everenergy from Singapore  
Hi ppl. I've tried to remove the 'java.lang.NullPointerException' error for hours but to no avail. Would anyone please point out what causes the problem in my code? Here it goes...


This is for MyShop.java:

import java.util.*;

public class MyShop {
private String shopName = 'ITGrocers'; //name of the shop
int capacity = 2; //maximum number of items that the shop can sell
Item[] listOfItems; //list of items in the shop
int numItems = 0; //number of items in the shop

public String getShopName() {
return shopName;
}

public void setShopName(String name) {
shopName = name;
}

public int addItem(String itemName, double itemPrice) {
boolean itemInShop = false;
if (numItems != 0) {
for(int i = 0; i < numItems; i++) {
if (itemName.equalsIgnoreCase(listOfItems[i…
itemInShop = true;
}
}
if (itemInShop)
return 0;

if (numItems == capacity)
return 1;

else {
listOfItems[numItems].setItemName(itemNa…
listOfItems[numItems].setItemPrice(itemP…
numItems += 1;
return 2;
}
}

public boolean updateItemPrice(String itemName, double newItemPrice) {
boolean itemInShop = false;
for(int i = 0; i < numItems; i++) {
if (listOfItems[i].getItemName().equalsIgno… {
listOfItems[i].setItemName(itemName);
listOfItems[i].setItemPrice(newItemPrice…
itemInShop = true;
}
}
if (itemInShop)
return true;
else
return false;
}

public void display() {
System.out.println('Shop name: ' + shopName + '\nMaximum capacity: ' + capacity);
if (numItems == 0)
System.out.println('No item added yet!\n');
else {
System.out.println('Total: ' + numItems + ' item(s)');
for (int i = 0; i < numItems; i++)
System.out.println(listOfItems[i].toStri… + '\n');
}
}

public static void main (String[] args) {
MyShop obj = new MyShop();
Item[] listOfItems = new Item[obj.capacity];
for (int i = 0; i < obj.capacity; i++) {
listOfItems[i] = new Item();
}
boolean loopChoice = true;
int choice;
double itemPrice;
String itemName;
Scanner s = new Scanner(System.in);
while (loopChoice) {
loopChoice = false;
System.out.println('--------------------… to Shop Management Program--------------------');
System.out.println('1.Add Item\n2.Update Item Price\n3.Display all items\n4.Exit');
System.out.println('Enter choice:');
choice = s.nextInt();
s.nextLine();

switch (choice) {
case 1: {
System.out.print('Enter item name:');
itemName = s.nextLine();
System.out.print('Enter item price:');
itemPrice = s.nextDouble();
if (obj.addItem(itemName,itemPrice) == 0)
System.out.println('This item is already in the list.');
else if (obj.addItem(itemName,itemPrice) == 1)
System.out.println('Adding failed. The shop has already reached its maximum capacity.');
else
System.out.print('New item added successfully.');
loopChoice = true;
break;
}

case 2: {
System.out.println('Enter item name:');
itemName = s.nextLine();
System.out.println('Enter item new price:');
itemPrice = s.nextDouble();
if (obj.updateItemPrice(itemName,itemPrice)…
System.out.println('Item updated successfully.');
else
System.out.println('The item does not exist.');
loopChoice = true;
break;
}

case 3: {
obj.display();
loopChoice = true;
break;
}

case 4: {
System.out.print('Thank you for using the program. Goodbye!');
break;
}

default: {
System.out.println('Invalid choice!');
loopChoice = true;
}
}
}
}
}



This is for Item.java:

class Item {
private String itemName;
private double itemPrice;

public String getItemName() {
return itemName;
}
public void setItemName(String n) {
itemName = n;
}

public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double p) {
itemPrice = p;
}

public String toString() {
return itemName + '\t$' + itemPrice;
}
}



The error lies at line 36 and 94 which are as follows:
36: listOfItems[numItems].setItemName(itemNa…
94: if (obj.addItem(itemName,itemPrice) == 0)



Detailed explanations would be helpful. U may rewrite the prog cos i'm really a noob at this. hv to hand in dis program latest by 10am
2010-04-28, 11:50:31
anonymous from India  
Thank you
2011-12-13, 10:13:08
anonymous from Vietnam  
thanks a lot . really helpful with me!!!
2011-12-25, 10:56:41
anonymous  
rating
Exception in thread 'main' java.lang.NullPointerException
    at java.util.Arrays.mergeSort(Arrays.java:1157)
    at java.util.Arrays.sort(Arrays.java:1092)
    at begin.main(begin.java:44)
i get this only after i sort the array with; Arrays.sort(array3);

help thanks
2012-01-01, 03:30:29
anonymous  


public class student
{
    int no;
    int ma[];    

    student(){}
    student(int mar[])
    {    
        for(int r=0 ; r<6 ; r++)
        {
            ma[r]=mar[r];
        }
    disp();
    }

    void disp()
    {    
        for(int r=0 ; r<6 ; r++)
        {
            System.out.println(ma[r]);
        }
    }
    public static void main(String arg[])
    {
        int no=1;
        String name='Mitul';
        int ma[]={1,2,3,4,5};            
        student s1=new student(ma);
    }
}


when i run this java code it give me this error!!! !
Exception in thread 'main' java.lang.NullPointerException
at student.<init>(student.java:14)
at student.main(student.java:34)
2012-01-25, 14:32:15
anonymous from United States  
Thanks dude
2012-05-14, 15:06:44
anonymous from Kuwait  
2012-07-23, 22:41:26
anonymous from United States  
2012-12-05, 09:56:14
anonymous from Denmark  
Thank you dude, you just made my day !
(as a popular statistic, my time of search-for-the-answer online was 5 minutes, ... after 1 hour of code testing on the issue)
You are on page 2 of 2, other pages: 1 [2]

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: