How to fill an array in a class JAVA - java

So I am having issues with a program i am trying to create. I cannot put in data into the array int[] serviceCode without the error
Exception in thread "main" java.lang.NullPointerException
at Job_18028094.<init>(Job_18028094.java:24)
at BMAS_Main_18028094.main(BMAS_Main_18028094.java:76)
Here is the relevant section of my code.
From my Main:
String[] tempRecords = fileScan.nextLine().split(",");
jobList[loopCount] = new Job_18028094(tempRecords);
From my class 'Job':
private int[] serviceCode;
public Job_18028094(String[] tempRecords) {
serviceCode[0] = Integer.parseInt(tempRecords[6]);
}
To clear things up, there is data held in tempRecords[6] as String (but is all numbers) and have been using Integer#parseInt prior to convert them. I researched what the error means and have turned up with it meaning that the variable is a 'null' value, but I am unsure as to how to change this or just over write it with the data in tempRecords.
Thank you in advance for any help :)

The NullPointerException is thrown , because the ServiceCode array is not initialized. Arrays are static objects and need to be initialized prior any use. Also, you should provide the size of this array before using it ! try to pass a "size" parameter to Job_18028094 constructor. This will solve the problem.

You have to initialize this array before use it.
private int[] serviceCode; // else serviceCode is null
You can use
private int[] serviceCode=new int[5];
If you are not sure about the length of the array. Use List
List<Integer> list=new ArrayList<>();

When you simply declare an array using the statement private int[] serviceCode;, you are telling to the compiler that a variable named serviceCode will hold an array of integers. At this point of time, compile is not informed about how many integers that the array will be holding. So the actual memory allocation to hold the integers will not happen by this time.
To start putting integers into an array, the corresponding memory allocation should have happened already. Compiler will take care of doing this memory allocation only when you initialize the array using the following statement.
int[] serviceCode = new int[5]
After the above initialization, memory allocation will be completed for the array to hold 5 integers and the array will be filled with the default values for the integers (which is '0'). Now you can start putting different values into the array.
In your case, since you have not initialized the array, memory allocation did not happen which caused the NullPointerException to be thrown when you tried accessing the array.

Related

Checking if an array has been assigned a size yet

Is there any way to check if an array has already been set to a length in Java?
In my case, I have a recursive method, and in the first iteration of the method, I want the array to have the length of a variable n. However, after the first recursion of the method, I don't want the array to be reassigned a new size.
Additionally, I don't know what the size should be until the first iteration of the method.
Thanks!
The array variable would be null until you assign an instance to it. Once an instance is assigned, it will have a fixed length. Therefore, a simple null check would suffice.
The Array Reference Variable Would be NULL until you assign to it.
You cannot create an Array Object without a lenght; if you want that, maybe you should create a ArrayList, and you can add objects to it without care about the size.
If you just want to see the lenght of your Array; after CREATE, do this:
public static void main (String[] args){
String[] x = new String[2]; // you cannot create here without a lenght, you MUST set
System.out.println(x.length);
}
OUTPUT: 2

An Array of ArrayLists (Null Pointer Exception)

i'm currently trying to add items to an generic "array" of arraylists but for some reason i keep getting a null pointer exception. The Structure is initialised and both my array index reference and the reference to the object i'm passing in are both visible within the body of code right before the exception occurs. I'm almost sure its down to the way i either declared the data structure or my way im trying to add it in. Any advice would be appreciated. Thanks in advance
ArrayList<Site>[] group = (ArrayList<Site>[])new ArrayList[entranceSites.size()];
group[i].add(sIndex(path));
sIndex is a function I'm using to convert integers to graph sites and the object is not null when I'm passing it in so i'm sure its not the problem. I is initialised and also visible to the program.
new ArrayList[entranceSites.size()];
does not actually initialize the array elements with any constructor. The array will be filled with enteranceSites.size() null elements.
You will need to iterate through the array and actually construct ArrayList objects.
Here's how you can set each element of the array to a new ArrayList using Java 8:
Arrays.setAll(group, n -> new ArrayList<Site>());
(The second argument is a function of n, the array index, but n isn't actually used. You still need to include it.)
You have allocated an array of ArrayLists, but you have not allocated any actual ArrayLists inside that array. The array initially contains all null references. So your invocation to add is on a null reference and thus causes the exception. If you say:
group[i] = new ArrayList<Site>();
Before you call add it will work.
Note that it is generally a bad idea to mix primitive arrays and Java collections, and if you are new to Java, then you should probably stick to collections since they are going to be easier to work with.
You should also be aware that the cast you are making (ArrayList<Site>[]) is unchecked and will almost certainly generate a warning assuming you have warnings enabled, which you should be enabling warnings as a beginner. This is another reason why it is not a good idea to mix generics with primitive arrays.
By the looks of your code fragment, my guess is that you failed to initialize the ArrayList<Site> element being added to the array; thus, failing when calling the List.add() method. The array itself is properly initialized, but you are trying to add a Site to an ArrayList that has not been initialized properly.
For this to work, you must create your ArrayList<Site> object. Once your lists are properly instantiated, you can add them to the array. You can add Site objects when creating the list or after you add them to the array. It does not matter when because the space in memory will be already allocated. Suppose a company has sites in many states, for argument sake, New York. All of the sites in that geographical location will be added to the NY list of sites:
ArrayList<Site> nySites = new ArrayList<Site>();
Site site1 = new Site();
group[0] = nySites;
group[0].add(site1); // Now you can call the add() method

initialize java array vs other initialization?

I know that when I initialize a char array:
I have to
char[] b= new char[5];
or
char[] b= new char[5]({1,2,3,4,5});
why not like
ArrayList<Charset> list = new ArrayList<Charset>();
initialize array :
char[] b = new char[5](); ?
Why they are different? Is it one of java philosophical nature or some reasons behind it ?
If you've ever used C, then the answer is fairly simple. In C, the way you create arrays is by allocating a static length of memory on the stack that is large enough to contain the number of elements, and point to the first element with a pointer - or dynamic length of memory on the heap, and point to the first element with a pointer.
int a[5]; //stack, static allocation
int* a = (int*)malloc(sizeof(int)*5)); //heap, dynamic allocation
And in C++, the second version was changed to this, obviously because it's more obvious what is happening:
int* a = new int[5];
And they took this type of array creation over to Java.
int[] a = new int[5];
Arrays don't really work like typical objects, hence why even creating them and manipulating them with reflection uses a different Array class in order to manipulate the object. (see http://docs.oracle.com/javase/tutorial/reflect/special/arrayInstance.html )
ArrayLists are different, because they're just everyday classes like most things in java, so you initialize them with an actual constructor call:
List<T> = new ArrayList<T>();
Basically, arrays and classes just work in different ways.
That's is simply design of Java. ArrayList and Arrays are two different things. No need to be same declaration.
I guess the guys who created Java wanted to keep a syntax close to the C syntax. In Java, arrays are minimalist low-level objects, so their case is a bit particular.
ArrayList is a container, it's similar as Vector in C++, it can add and remove elements, but array can't change its size
Arrays and ArrayList are used for different purposes. If you need a fixed size collection of objects then go for array but if you need dynamically growing collection of objects then go for arraylist. In some way compiler need to know about what is your need, hence the syntax is different.

difference between these 2 ways of initializing an simple array

In java, I can initialize an array with predefined content either by :
int[] myArr = new int[]{1,2,3};
Or by :
int[] myArr = {1,2,3};
Essentially, is there any difference between these two ways ? Are they completely identical in Java ? Which way is better and why?
In your case there is no difference.
There will be a difference when you are not assigning your array to variable and doing inline creation.
for example, conside there is method, which takes an array as argument.
private void someX(int[] param){
// do something
}
Your case:
someX(myArr); // using some declared array .I.e your case
Now see the difference while calling it in other cases.
someX(new int[] {1,2,3}); // yes, compiler satisfied.
someX({1,2,3}); //Error. Sorry boss, I don't know the type of array
is there any difference between these two ways ? Are they completely identical in Java ?
No there is no difference. Both of them will create an array of length 3 with the given values.
The 2nd one is just a shorthand of creating an array where you declare it. However, you can't use the 2nd way of creating an array, at any other place than the declaration, where the type of array is inferred from the declared type of array reference.
No, the first and second are the same. The second is just syntactic sugar. Your end result is the same.
int[] myArr = new int[]{1,2,3};
Here it means you are initializing the three variable which will create the length of array 3
int[] myArr = {1,2,3};
Here it means you are initializing the three variable which will by default create the length of array 3
Both ways generate exactly the same result. Both are arrays of length 3 with predefined values. The second one is just shorter. The second method of declaring an array is better if you think that you need less time to write that code.
In the case you need to use that array to directly pass it to a method you should use the first one:
//Correct
someMethod(new int[]{1,2,3});
//Incorrect
someMethod({1,2,3});
But if your goal is only to declare and initialize the array in a variable either ways are correct:
int[] myArr = new int[]{1,2,3}; //Correct
int[] myArr = {1,2,3}; //Also Correct

what is the concept behind memory initialization for Array?

String a[]=null;
if(a[0]!=null)
{
System.err.println("dd-1");
}
if(a!=null)
{
System.err.println("dd-2");
}
}
In first if condtion its throwing null pointer exception, but in second if condition its not throwing null pointer exception? can anyone please explain me the same? is there is any concept behind this on Heap memory allocation.
also i got to know the problem becauese of Missing memory allocation,String a[]=new String.[10]; please expalain the concept?
In the first if condition you are trying to access the first element in the array, even thought there is no allocation done for it.
In second condition you are just testing the reference.
(Think of it as C pointers, char *str = NULL does not allocated any thing except a pointer pointing to NULL)
String a[]=null;
No memory is allocated for the array only reference is created.
String a[] = new String[1]
Memory to hold one String object is created on the Heap and a points to the allocated string object.
if(a[0]!=null)
The first condition is trying to access the first element of the array (and check if it exists). That will not work if the array does not exist (i.e. is null).
if(a!=null)
The second condition is just checking if the array itself is null.
Memory for the array gets allocated (on the heap) when you create the array. At that time you also have to specify its size (and that will determine exactly how much memory gets allocated). The memory is also initialized with null, so you don't get garbage data for a fresh array.
Access to array elements is not just pointer arithmetic as in C, Java actually checks if the array exists and if the index is within its bounds.
Arrays are objects. You have to create new space for them. If you're trying to access a null reference, you'll get a NullPointerException every time.
If you use a[0], you are going to access a object (first object of the array). but a doesn't have any object yet. therefore first one throws a exception. But in second one, you are checking a reference. it is not an object. So a is equals to NULL.
In Java, arrays are not like C, they are objects living in the heap, they do have a special type and syntax to access their elements but they are objects, if you wish to access any subindex you'll need to do something like
String[] a = new String[10];
after that, each element will be initialized in null, 0 or false depending the type of the array.

Categories