This is my very simple code, with data being an empty double array
private void findLast(){
double empty[] = new double[0];
if(data == empty){
throw new ArrayIndexOutOfBoundsException(" Array is empty");
}else{
System.out.println(data[data.length-1]);
}
}
When I run the code I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
My question is, shouldn't the "throw" and "if" stop the "else" from running? And how do I fix the code so it runs properly?
== tests for reference equality for reference types such as arrays.
empty == empty is true
empty == new double[0] is false.
If you need to find if an array is empty, use:
if (data.length == 0) {
In java, the == operator checks if the two variables reference the same object, not if the two objects that the variables reference have equivalent values. So, even if both empty and data are double arrays of size 0, data == empty will never be true because they don't reference the same object.
As a side note, I'm not really sure there's any good reason for you to be doing this and an array of size 0 doesn't have an element at length - 1. If empty has zero elements, what is the point of creating it? if it doesn't have zero elements and you want to know if there is nothing stored into it, then you should know that arrays always have something stored in them after being initialized.
if(data.length==empty.length)
{
throw new ArrayIndexOutOfBoundsException(" Array is empty");
}else{
System.out.println(data[data.length-1]);
}
Related
I have a rather simple question: How to check for an (int) array, whether the current entry array[i] was already assigned or not.
It is a dynamic programming task, where I store results for sub-tasks in an array. Thus the array is filled continuously.
I tried: if(a[i] != null) do stuff; but I got an error that "!=" is a bad operator in this case.
What would be the best(robust) solution to check this?
If a is an int array, you can't ask this:
if (a[i] != null)
Because an int value cannot be null. In an empty int array, the uninitialized positions will have 0 as value. Maybe this will work for your use case?
if (a[i] != 0)
If that doesn't solve the problem, then consider explicitly initializing the array with a different value (for example: -1), at the beginning of your program, and testing against it in the condition.
(a[i] != null) is an error for the int type. This is because int is a primitive type and cannot be null. As explained in another answer and some comments, you can fill the array with a set value such as -1 or Integer.MIN_VALUE which would flag an unused element.
If you need a value that can be null and passed as an object, perhaps an array of Integer will do.
It is initialized almost the same:
Integer[] a = new Integer[N]; // N is a constant indicating the length of the array
This creates an array that can hold Integer objects, all of which are initialized to null. You can put an Integer into the array with:
a[i] = new Integer(x);
This will work fine in your if statement:
if (a[i] != null) {...do something...}
will work fine.
This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
Closed 4 years ago.
I got different simulation results when I programmed in these two ways:
if (S == null) {
return new LinkedList<>();
}
and
int len = S.length();
if(len == 0) return new LinkedList<>();
The first code gave me [""], which passed the testing. While the second one gave me [], got failed.
And I also noticed that there is another way: S.isEmpty()
Would anyone please explain? Many thanks!
String == null checks if the object is null (nothing, not even an empty string) and String#length() == 0 (actually, you should use String#isEmpty() instead) checks if the string object has 0 chars. Also, you can't access any methods if the object is null, it will throw a NullPointerException (or NPE for short).
difference between (string == null) and (string.length() == 0)?
Very different.
When you check (string == null), it checks whether the string reference is pointing to any existing object. If it is not referencing to any object, it will return true.
string.length() == 0 just checks your existing String object's content and see if its length is 0. If no object exist in the current variable when you invoke .length(), you get a NullPointerException.
S is a reference variable (you should write it in lower case).
S (or rather s) references an object that provides the method length().
You can only access the object referenced by s, if s is a really a reference to an object. If s is null (s==null), s does not reference an object and therefore, you can not call the method length(). If you try, you will get a NullPointerException.
When s references an object, you can call the length method on that object. In this case, it is a string object. A string object may exist without any characters (empty string, or "").
String s; // just a reference, initial value is null
s = ""; // s now references an empty string and is no longer null
new String(""); // create a new object with an empty string
In Java, you never really work with objects. You only work with references to objects, though in most cases, it appears as if you work with the object directly.
Keep in mind that the reference variable and the object are really to different things.
If the string you are passing into the second one is null, an exception should occur, since .length() will throw an exception when called on a null string.
if a String instance is null, myInstance.length() == 0 would throw a NullPointerException, because you call an instance member of a not instantiated instance and crash your application.
So, if you're not sure your String instance is instantiated, always do a null-check, or better yet, with Java 8 or later, use Optional to avoid null's.
S == null mean that there if you try to print something for instance, nothing wiil happen (or maybe a nullPointerEcxeption) because null mean that there is nothing inside this variable.
String.lenght(S) == 0 mean that your string equals to ''
for instance :
String S1 = '';
String S2 = null;
try{
System.out.println(S1.length() == 0) {
System.out.println('S1 is not null');
}catch(nullPointerExeption e){
System.out.println('S1 is null');
}
try{
System.out.println(S2.length())//it will throw you a java.nullpointerexcption
System.out.println('S2 is not null');
}catch(nullPointerExeption e){
System.out.println('S2 is null');
}
The system will write
0
S1 is not null
S2 is null
//case1
String s;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
//error: variable s might not have been initialized
//case2
String s=null;
if(s==null)System.out.println("I am null");
System.out.println(s.length());
/* output
I am null
error: Null pointer exception
*/
//case 3
String s=new String();
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
String s="";
if(s==null)System.out.println("I am null");
System.out.println("length is "+s.length());
/* output
length is 0
*/
The javadoc of ArrayUtils.isNotEmpty() in Apache Commons Lang seems to be wrong. Or, at least, misleading. It says
Returns:
true if the array is not empty or not null
In my understanding, an empty array is not null. So, according to the above definition, isNotEmpty() should return true for an empty array, which is counterintuitive.
Wouldn't
Returns:
true if the array is not null and not empty
be more correct?
Wouldn't
Returns: true if the array is not null and not empty
be more correct?
Yes you are right. The doc is a bit misleading. In fact, if you see the source code, it does exactly that:
public static boolean isNotEmpty(Object[] array) {
return (array != null && array.length != 0);
}
In my understanding, an empty array is not null.
Not correct. Counterexample:
int a[];
a is an empty array (as it doesn't contain anything), and it's also null since it wasn't initialized.
In this case, isNotEmpty will return false, since it is empty.
So I've created my own class with 5 private fields: Each is an array with a pre-set length. It's my way of creating a table, where each array is a column, and they have pre-set lengths because not every cell will contain an element (So, not using anything dynamic).
Anyway, my question is: Can I check to see if a specific cell of a specific array contains "null"? Using .equals(null) gives a nullpointerexception :(
When you call .equals(...) you call a method of the object. If it is null, it has no method. Therefore null check like this:
if (myArray[position] == null) {
....
}
don't do .equals(null) but == null:
if( the_array[i] == null ) {
//...
}
Think about build a table by a bidimensional array. Example:
TheClass my_array[][] = new TheClass[10][5];
you should use
if (cell[i] == null){
}
since you are testing for reference equality. And in the case where cell[i] is actually null, null doesnt have an equals method.
Mixed up for loops and null construct
for(Integer ints : intNum) {
if(intNum != null) {
//valid
}
}
I'm more curious as to why your making 5 arrays? Have you heard of multidimensional arrays? Maybe that's what you really need in this case.
an array like this fx:
int[][] arrayName = new int[3][3];
Would represent an array of 3 rows and 3 columns in each.
Maybe you alrdy knew that, but it just seems weird to me to make five different arrays if you just want a table-like structure.
I'm looking for Java's equivalent of PHP's isset();
int board[][]=new int[8][8];
...
if(isset(board[y][x]))
// Do something with board[y][x]
Does such a function exist in Java?
Edit: Sorry, what I meant is that I want to check if board[100][100] exists or not. if(board[100][100]) would result in an array out of bounds error.
In Java, int arrays are initialized to a value of zero, so you won't be able to tell if it's been not set, or if it's set to a value of 0.
If you want to check if it's set, you should use an array of Integer. If the value isn't set, it will be null.
Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }
I think a basic null check would work.
String[] myArray = {"Item1", "Item2"};
for(int x =0; x < myArray.length; x++){
if(myArray[0] != null)
{
...do something
}
}
You can create a method that checks that first the x, y is in the bounds of the array and if it is that the value is not null. I don't believe there is a built in method for array, but there are helper functions similar like .contains() for ArrayLists.
Probably better to not use int, you could use Integer if you really have to have it as an int, but generally speaking a complex object is going to be better (like a ChessPiece or something). That way you can check to see if the value == null (null means it has not been set).
if (board[x][y] != null) {
// it's not null, but that doesn't mean it's "set" either. You may want to do further checking to ensure the object or primitive data here is valid
}
Java doesn't have an equiv. to isset because knowing if something is truly set goes beyond just stuffing a value into a location.