I get a NullPointerException at a line on which just a simple null check takes place.The line is the following:
if(routingTable[commonBitGroups][nextNumberOfOther-1]==null)
I verify that the array is not null just before this line.
commonBitGroups and nextNumberOfOther are both simple int types.
I should add that this line is part of an app that uses rmi and part of a class which extends UnicastRemoteObject and implements a RemoteInterface.I specify that because I am under the impression that a NullPointerException can occur when you deal with synchronization even if nothing is realy null (maybe when something is locked) ,and I deal with synchronization in this app.The method that contains the line though is not synchronized and nowhere in my code I try to use the array as a monitor (I only have some synchronized methods ,no smaller synchronized blocks so I nowhere choose a specific monitor explicitly).
If the following line throws an NPE:
if (routingTable[commonBitGroups][nextNumberOfOther - 1] == null)
then either routingTable is null or routingTable[commonBitGroups] is null.
You say that the array is initialized as follows:
routingTable = new NodeId [32][15];
Arrays.fill(routingTable, null);
"Well there's your problem!"
The first line gives you an array of 32 NodeId[]'s, with the elements initialized to non-null values ... arrays of size 15. (So far so good ...)
The second line sets routingTable[i] to null for all i .... Ooops!!
Delete the second line.
As #Gabe says, it's probably that routingTable[commonBitGroups] is null. Java does not have real multidimensional arrays: a 2-d array is an array of arrays (and a 3-d array is an array of arrays of arrays).
Incidentally you don't have to initialize references in an array to null in Java, that is their default value. In this case it's also your problem. You're setting the second level of array values to null. What you meant was
for (int i = 0; i < 32; i++) {
Arrays.fill(routingTable[i], null);
}
But as above, this is unnecessary. So just remove your call to Arrays.fill.
Related
I'm learning Java with the help of a book and don't understand the following example/statement:
For args[0].equals("Schrödinger") you need to make sure the args[0] is not null, whereas "Schrödinger".equals(args[0]) doesn't need this kind of check because "Schrödinger" can't be null.
Code:
if("Schrödinger".equals(args[0])) {
System.out.println("Hallo");
}
However I do get an error if there is no parameter in args, which also seems logical as you need to grab the value at args[0] at some point for the comparison, even if the string "Schrödinger" isn't null. I'm confused, is the example from the book wrong or am I not understanding something?
The code provided in the book only handles args[0] being null, not args having a length of 0. Assuming your program is supposed to pass some command-line arguments to it, and you do not pass any argument while executing it, the length of the following array, args will remain 0.
public static void main(String[] args)
As a result, an attempt to access an element from the first position, which is specified with the index, 0 will result in ArrayIndexOutOfBoundsException. Since the index of an array starts with 0, the maximum index can go up to the size of the array minus 1.
You can avoid the problem you have faced by checking the size of the array first before accessing an element within the maximum index e.g.
if(args.length >= 1 && "Schrödinger".equals(args[0])) {
//...
}
Similarly, if you want to access an element up the index, 1, you should check if the size is 2 or more e.g.
if(args.length >= 2 && "Schrödinger".equals(args[1])) {
//...
}
By the way, a condition like "Schrödinger".equals(args[0]) is known as Yoda conditions.
Your assumption is correct. For the main method If the array is not provided then you can not access the first element of the array. It will throw an ArrayIndexOutOfBoundsException since there are no elements.
Running any method for a null object is not allowed, and you will get an exception. You have to check if args[0] is null (or of length 0) before you do anything with it.
For args[0].equals("Schrödinger") you need to make sure the args[0] is not null.
True, since you're calling .equals("Schrödinger") on the object, which is expected to be at index 0 in the args array.
whereas "Schrödinger".equals(args[0]) doesn't need this kind of check because "Schrödinger" can't be null.
True, as "Schrödinger" is a String literal, which by definition is an Object, so you explicitly have it, and there's no even hypothetical chance it'll be null.
However I do get an error if there is no parameter in args, which also seems logical as you need to grab the value at args[0] at some point for the comparison, even if the string "Schrödinger" isn't null.
True, but to be precise here, error doesn't happen at the comparison stage, because of you can't compare something to nothing, rather, your error happens here, because you're not passing anything, hence the args array is empty, and args[0] will throw the ArrayIndexOutOfBoundsException exception.
I hope I made each and every step clear for you.
For User defined args array
Case 1: args[0].equals("Schrödinger")
When args[0] is null(no value is passed), you cannot call equals method on
null hence NullPointerException is thrown
Case 2: "Schrödinger".equals(args[0])
In this case despite args[0] being null equals is called on string literal and
no exception is thrown + the condition evaluates to false. Hence this approach
is the recommended one or use Optionals.
For args of public static void main
In case of args array of public static void main it will throw ArrayIndexOutOfBoundException. If JVM finds no command line arguments its initializes the args as String[] args = new String[0] i.e of length 0. Hence while accessing it throws exception
javac allows below syntax,
int[][][] i = new int[4][0][2];
which has zero length index that prevents access beyond.
1) There is no way to access third dimension. zero length dimension as last dimension(int[][][] i = new int[4][2][0];) looks fine.
2) It is not possible to write an initialiser for a multi-dimensional array with a zero length dimension unless that dimension is the last( for instance int[2][3][0]).
Why java allows such syntax?
Note: this question has nothing to do with int[0]
Because nothing in the multianewarray bytecode instruction prevents you from doing so.
There is really no better answer than that... The fact is that for any X, even if X is a primitive, then X[] is a class, X[][] is a class and so on; and you are free to choose the "dimensions" of the array.
Note how declaring a X[n][] and a X[n][m] array differ: in the first you'll declare a anewarray of X[] whereas in the second you'll declare a multianewarray of X.
Of course, in X[m][n][p], there is no possibility to ever have a "third dimension" (p) if n is 0, but... Well, the programmer knows what he's doing, right?
Just another bizarreness of arrays in the JVM... Think nothing of it except that "it can happen" ;)
I agree with #m0skit0 - I think this is a duplicate questions. However I will give a brief answer anyways.
Basically its an alternative for null. Consider simply, you have a method that returns an array, but it has no value to return. You could return null, but then you have to check for null in your code. On the other hand, you could return a 0 length array. Code such as the follows would automatically be skipped.
for(int p = 0; p < array.length; p++) {
So you can do perfectly acceptable stuff like:
public static final int[][][] EMPTYARRAY = new int[0][0][0];
note also things a much worse than you suppose because this is also legal:
public static final int[] SCREWEDARRAY = new int[-1];
which causes a runtime error:
java.lang.ExceptionInInitializerError
Caused by: java.lang.NegativeArraySizeException
First of all, it's not just in "the middle". You can easily define a one dimensional array just as easily:
int[] a = new int[0];
Second, an array with zero length is a bit like an empty collection. It's a legal data structure which might be returned by a method, but which happens to be empty.
This question already has answers here:
Why does Java allow arrays of size 0?
(9 answers)
Closed 9 years ago.
char[] arrNew = new char[0];
System.out.println(arrNew.length); // length = 0
arrNew[0]='c'; // ArrayIndexOutOfBoundsException .
In the above code as you can clearly see there is no point in having an array of size 0. As far as I can see there is no practical usage of 0 size array. Can someone explain why the compiler allows creation of 0 length array. And also how is a 0 length array different from an array initialized to null? (i.e, is memory allocated to it as if it were a normal array?). I am sorry if this question seems stupid.
We can return an empty array instead of null from a method, this is called Null object design pattern. Consider the following code
Person[] res = find(name);
for(String e : res) {
System.out.println(e);
}
if find() does not find anyone it returns an empty array. If find returned null then code would need to treat it as a special case.
We should keep in mind that empty array is immutable so it is logical to use a singleton instead of creating it each time
private static final Person[] NULL = new Person[0];
Person[] find(String name) {
...
if (notFound) {
return NULL;
}
...
It's best not to return null from a method that returns an array type. Always returning an array, even if the array has zero length, greatly improves the generality of algorithms. If you anticipate that your methods will return zero-length arrays frequently, you might be concerned about the performance implications of allocating many such arrays. To solve that problem, simply allocate a single array, and always return the same one, for example:
private static final int ZERO_LENGTH_ARRAY[] = new int[0];
This array is immutable (it can't be changed), and can be shared throughout the application.
So in Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available.
Compiler allows because that code its within the rules of the language.
And no, they are both not the same. If it were the same, you would get a NullPointerException rather than ArrayIndexOutOfBoundsException.
It can be of use, if you have a function returning reference to array, and if you have nothing to return then you might consider its better to return 0 length array than a null. If null were returned you would have to check this function for both null value, and if range is correct, if you return 0 length array - then you might only check the if range is correct - ie. in for loop.
Zero-length arrays are rarely "required," but are more often used simply to show that there is no data being passed to a method.
in java the memory allocation can be dynamic in nature. The java array enables the user to store values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure which can not be altered when required. It just occupies the memory.
This question already has answers here:
length and length() in Java
(8 answers)
Closed 6 years ago.
I've noticed that when doing the length of an array you write something like:
arrayone.length;
However, for such things as array lists or a string, you write a bracket on the end, such as the following for the length of the String:
stringone.length();
What is the key reason for this and how do you know when to put the brackets or now?
.length;
directly accesses a field member.
.length();
invokes a method (i.e. an accessor) to access a field member.
in the case of String, this is to be expected since it's immutable.
Arrays are handled differently than Strings or ArrayLists or anything else that can be counted in Java. An Array is pretty much a native type and it's length can never be changed after it is initialized, so there's no need for encapsulation. The length variable can be directly exposed with no side effects.
The reason why String uses a method instead of a variable is because it internally uses a char[] that it doesn't want to expose publicly (for immutability/encapsulation), so it wraps the length variable in a length() method. It's the same reason ArrayList has a size() method instead of a length variable.
The only time you'll use the variable instead of the method is with arrays. Everything else will be methods. That is, you'll use the brackets for everything except arrays.
The only true way to know when to use which one is experience. Though an IDE with autocompletion will usually help you out when you don't remember.
For the most part (not always) array.length, System.out, and System.err are the most common 3 you'll run into that are actually member access instead of method calls.
int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();
myArray.length //gives the length of the array
myString.length() //gives the length of the string
myList.size() //gives the length of the list
Its very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally a method length() was used to avoid duplication of the same information. Ultimately this is just an inconsistently that evolved that would definitely be fixed if the language were ever redesigned from the ground up. :D
The main difference is that in the A) first case its Array Type for example int[], Object[], double[], ect.. that has a public field called lenght and the B) second case is a Object String that has a function called length(), the function could of been called getLength() or something else. The array type public field length is probably a hangover from C++ way of doing things.
Array Types have the following:
The public final field length, which contains the number of
components of the array (length may be positive or zero)
The public method clone, which overrides the method of the same name
in class Object and throws no checked exceptions
All the members inherited from class Object; the only method of
Object that is not inherited is its clone method
Take a look at this, Array Types.
.length() is a method of a String class and which returns the number of characters in the string.
.length will give the number of elements stored in an array.
public class length
{
public static void main(String args[])
{
String x="test";
int a[]={1,2,3,4};
System.out.println(x.length());
System.out.println(a.length);
}
}
// output
4
4
length is a pseudo-data member reference, and only works for (small-a) arrays (ignoring classes that you may define that implement the member).
Everything else is an object of a class, and all JDK classes that have this concept define either length() or size() instance methods. (I do wish they'd been consistent and picked one or the other, but that's water over the bridge.)
Array.length is a property of that Array, similar to a variable reference.
ArrayList.size() is an actual method call to the array list object.
I have an array at actionTable.get(state).
When I go to add an onject to the array, namely the Reduce, the properties of the reduce don't seem to go with it.
The array is of type Action[] where Action is the superclass of Reduce, could this be the reason?
Adding the reduce to the array:
actionTable.get(state)[t] = new Reduce(st.items.get(item).prod);
Checking to see if the field head is defined before adding it:
System.out.println(Prod.prods.get(st.items.get(item).prod).head);
Checking to see if the newly added reduce has the correct head field:
System.out.println(actionTable.get(state)[t].prod.head);
A NullPointerException occurs on the last print statement. The .prod part is defined but the .prod.head is null, even though the original prod object had a defined head.
This is the constructor for Reduce:
Reduce(int pr) {
p = pr;
length = Prod.prods.get(pr).length;
prod = Prod.prods.get(pr);
}
All of the RHS of the assignments in the constructor are defined. So, I don't understand why the head field, within the prod object that the new Reduce has access to is not defined when you access it through the actionTable.
Trust inheritance and all. Most likely with arrays is, that different array instances are involved (if you enlarge/copy array references). Some more System.out.println's will help there.
The first thing you always should do is this: got to your break points view in your IDE, check "stop on Exception thrown" and perhaps give the name NullPointerException.
Then run your code in the debugger and it will stop exactly at the point where the NullPointerException is thrown.