what is the concept behind memory initialization for Array? - java

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.

Related

How to fill an array in a class 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.

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

java loitering and garbage collection

I have this bit of code for the Stack's pop method and i'm trying to figure out how it avoids loitering while still returning the element that our index is currently pointing to:
public String pop()
{ // Remove item from top of stack.
String item = a[--N];
a[N] = null; // Avoid loitering (see text).
if (N > 0 && N == a.length/4) resize(a.length/2);
return item;
}
From what i can understand we are pointing the reference item of our String object to the indexed element(we start from the last element using it's current size N-1 hence the decrements) of our array a. Then if we are returning the reference why are we setting that indexed element that our reference is pointing to null before doing so? Doesnt that make the item point to nothing and return nothing?
An object can't be garbage collected as long as it is reachable. If you simply change your index with --N but do not nullify a[N], you will keep a reference to that object, preventing its garbage collection even if the client code does not reference that object any longer.
That is one of the only cases where you need to nullify a variable in Java.
You also seem to misunderstand what references are. a[N] contains a value that points to an object in memory. When your write String item = a[N], you copy that value to the variable item. Both variables (item and a[N]) now refer to the same object. When you then write a[N] = null, you remove that reference from the array but item still contains a value that points to the original object.
This copies the reference in the array. It doesn't reference the array member.
String item = a[--N];
Now you have two references to the same object, one in the local variable, and one in the array. This removes the copy in the array:
a[N] = null; // Avoid loitering (see text).
If it were not removed from the array, then an unnecessary reference would continue to exist, preventing garbage collection.

How objects are allocated in array?

I want to improve my knowledge about memory model of programming languages (particulary in Java), so I have one question.
Here is very simple code:
// Allocating memory in heap for SimpleObject's instance
// Creating reference to this object with name so1
SimpleObject so1 = new SimpleObject();
// Allocating memory in heap for array of 10 references to SimpleObject's objects
// Now I know, that array stores only references to the objects
// (Previously I thought that array stores objects)
// Then we create reference to this array with name soArray
SimpleObject[] soArray = new SimpleObject[10];
Now the question:
// What is going on here?
soArray[0] = so1;
// object so1 had been really moved to memory area of soArray?
// And so1 reference have been updated to new memory address?
// Or we just had assigned so1 object's reference to soArray[0] element?
// Or so1 object had been copied to the soArray[0]?
// Then original so1 object has been deleted and all links to it had been updated?
If you know, how it works in other languages, such as (C, C++, C# or other), please answer, I will be glad to know it.
Everybody know, that ArrayList can be faster than LinkedList, because elements of array could be stored in CPU cache, while if we working with LinkedList, CPU has to get next object from RAM each time.
So how could it work, if at first I had created object in heap and only then I had put object in array?
UPD: Thank you guys, now I understand how array is working, but what about caching array in CPU cache in that way?
Arrays store references to objects, not the objects themselves. You therefore swap the reference at position 0 when assigning soArray[0]. The objects themselved can be moved within the heap, but this is usually due to GC, not assignments.
If the objects themselves were stored directly in the array, you could not have instances of subclasses with more instance fields in your array. They would not fit into the allocated space and therefore only become instances of the base class. This is what actually happens in C++ when you assign class instances stored on the stack.
In Java, arrays store references to objects. In C++ parlance they store pointers to objects.
SimpleObject[] soArray = new SimpleObject[10]; //Java
SimpleObject* cppArray[10]; // C++ equivalent
soArray[0] = so1; puts a reference to so1 in soArray[0] in the same way that cppArray[0] = &so1 stores a pointer to so1. The original object remains unchanged, no additional memory is allocated or deallocated.
In C++ you can store the objects directly in an array.
SimpleObject soArray[10]; // An array that stores Simple Objects in place
SimpleObject so1; // A new object
soArray[0] = so1; // This *copies* so1 into soArray[0]
We assign the reference to the object pointed by so1 to the array element.
Here's an example in using Python Tutor (there's no equivalent tool for Java that I know, but the memory model is similar, except for the Class being an object, so ignore that):

Why array values in java is stored in heap?

Programing languages like C,C++ will not store array values in Heap rather it keeps the value in STACK. But in Java why there is a necessity to keep array values in heap?
In Java, arrays (just like all other objects) are passed around by reference: When you pass an array to a method, it will get a reference pointing to the same location in memory, no copy is being made. This means that the array needs to remain "alive" after the method that created it, and so cannot be stored in the stack frame for the method. It needs to managed by the garbage collector, just like all other objects.
There is some research going in to optimize JVM memory allocation using "escape analysis": If an object (such as an array) can be guaranteed to never leave the current scope, it becomes possible to in fact allocate it on the stack, which is more efficient.
A short answer is that an array in Java is a reference type, and reference types live on the heap. It's worth noting that in C#, one can switch to unsafe mode and initialise arrays with stackalloc which will create the array on the stack. It's therefore quite probable that the VM would allow you to make an array on the stack, and it's merely an implementation detail that means arrays all live on the heap.
int[]a={10,20,30};
this array stores on stack, but the following array stores in heap:
`int[]num=new int num[2];`//here we build the object of array , object always located in heap
always treat arrays like java object, so do not be confused by the fact that arrays don't store on ram when we have a declaration like the one above.

Categories