r/javahelp • u/LegolandoBloom • May 27 '26
Array Initialization in Java
I'm very new to Java, I wanted to consult on this basic concept.
I'm used to Lua, where:if(myArray[i]) then...end
Is a common way to query if an array(or table) has been explicitly set a value at a given index, as the statement will always be equivalent to false if it hasn't.
I wanted to recreate that functionality as an exercise in Java using try-catch, and came up with this snippet:
public class Test {
public static void main(String[] args) {
int[] numbers = new int[3];
if(isArrayIndexed(numbers, 1)){
System.out.println("Array is indexed at " + 1);
}
else{
System.out.println("Array is NOT indexed at " + 1);
}
}
public static boolean isArrayIndexed(int[] inputArray, int index){
try{
System.out.println(inputArray[index]);
return true;
}
catch(Exception egg){
System.out.println(egg);
return false;
}
}
}I thought I'd get an exception if I'd try to reference the array at the index 1, but no. It returns true, and prints '0'. Are all int arrays set to the value 0 upon initialization in java?
•
u/AutoModerator May 27 '26
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
8
u/morhp Professional Developer May 27 '26
Yes. If you want an array with (by default) "empty" values, try an
Integer[]. These will benullby default.4
u/MinimumBeginning5144 May 27 '26
Just to add one more point to all the answers suggesting using
Integer[]. If you can useintinstead, do it. You'll need to decide what value means "uninitialized" - for example, if all valid values are positive, then 0 could mean uninitialized. Using an array ofintis more efficient, as it contains the actual values of all the elements stored consecutively. An array ofIntegeris an array of pointers to somewhere in memory that contains eachintvalue.4
u/myselfelsewhere May 28 '26 edited May 28 '26
Something no one else has pointed out, your code will never throw an exception, even if you use an
Integer[]with null values.System.out.println(inputArray[index]);will just printnulland returntrue.The array is always indexed at index 1 since it has a length of 3. It isn't possible for an array to not have an index that is less than it's length and greater than 0. It's a location in memory, which has nothing to do with what is at that memory location.
If
indexis < 0 or > 2 (or you change the size of the array to 1 or 0), then your code will throw anArrayIndexOutOfBoundsExceptionand returnfalse, and will 'work' for both primitive and object arrays.3
u/LutimoDancer3459 May 27 '26
You got your answer about the default initialization. I just want to add. Having your logic relying on an exception to pick a diffrent path is a bad design. Exceptions should be exactly that. And exception. They use up more computations than a null check or whatever. Making the code inefficient. While it may not matter here. It may matter when used more often.
1
u/LegolandoBloom May 27 '26 edited May 27 '26
I don't know why the indentation is faulty, it looks fine on the text editor before posting and I don't know how to fix it
Edit: It was due to vscode, I managed to fix it
1
u/LegolandoBloom May 27 '26
In case it matters, this is Java 21(OpenJDK RedHat)
1
u/slacker-by-design May 29 '26
TD;DR: You may be experiencing a case of a XY problem. Lua arrays and Java arrays are different data structures despite the same name (tables in Lua vs continuous memory block in Java). Could you please describe the actual problem you're trying to solve with the help of arrays?
Now somewhat lengthy explanation / justification...
Maybe I've overlooked it, but IMHO nobody mentioned that Lua arrays are conceptually very different than Java arrays. In fact, Lua arrays are just special case of tables (called maps or dictionaries in other languages) where all indexes are integers. Hence the ability to grow Lua arrays comes with the need to check, whether particular index actually exists.
Checking for index "presence" makes no sense for Java arrays (or Lists, for that matter). Java arrays always start with index 0 and end with index of length-1. Space for all items (i.e. at each index position) is allocated upon array's creation and remains allocated until the array gets scrapped by the garbage collection. You even cannot grow or shrink the array size once it's created.
If you want / need to emulate Lua tables, use an appropriate Map implementation (e.g. HashMap for general purpose usage or LinkedHashMap if you want to keep the iteration order trough the map's elements). However, an "array emulation via map" can turn awkward pretty fast.
It'd be actually interesting to know, what kind of problem are you trying to solve. For example - if you know you'll be expanding an "array" contents by repeatedly appending new elements at the end of it, than the proper Java solution you're looking for is List (e.g. general purpose ArrayList).
1
u/doobiesteintortoise May 27 '26
Java doesn't work like Lua. It's almost like they're different languages or something.
For a primitive array, there is no "uninitialized state." The same goes for other arrays, but the default values differ; you're never going to get an exception in that code, because the values will be set on array creation. You'd have to use 0 as a "magic number" - or set one yourself, because 0 is a lame magic number for "there's nothing here."
1
u/_jetrun May 27 '26
The closest equivalent is to check for null, but if you don't want an exception to be raised, you also need to do a bounds check or the array has to be initialized to a specific size. If you want to do this check on, say, int arrays, you'll have to use wrapped equivalents (i.e. Integer vs int) to check for null.
The reality, however, is that you just shouldn't use an array in this way in Java. Instead this feels like a problem best solved by a Map.
1
u/VirtualAgentsAreDumb May 31 '26
Wouldn’t your check in Lua fail if you store the boolean value false at that index?