[{"data":1,"prerenderedAt":146},["ShallowReactive",2],{"qa-\u002Fjava\u002Ffundamentals\u002Farrays":3},{"page":4,"siblings":130,"blog":143},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"questionsCount":121,"related":122,"seo":123,"seoDescription":124,"stem":125,"subtopic":6,"topic":126,"topicSlug":127,"updated":128,"__hash__":129},"qa\u002Fjava\u002Ffundamentals\u002Farrays.md","Arrays",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"easy","md","Java","java",{},true,3,"\u002Fjava\u002Ffundamentals\u002Farrays",[23,27,31,35,39,43,47,52,56,60,64,69,73,77,81,85,89,93,97,101,105,109,113,117],{"id":24,"difficulty":14,"q":25,"a":26},"declare-initialize","What are the ways to declare and initialize an array in Java?","An array is declared with `type[]` and created with `new`, an **array\ninitializer** `{ ... }`, or both. The brackets can sit on the type or the\nvariable, but `type[]` is the convention.\n\n```java\nint[] a = new int[3];          \u002F\u002F size only — defaults {0,0,0}\nint[] b = new int[]{1, 2, 3};  \u002F\u002F size + values\nint[] c = {1, 2, 3};           \u002F\u002F shorthand initializer (declaration only)\nint d[] = {1, 2, 3};           \u002F\u002F legal but discouraged (C-style)\n```\n\nThe bare `{ ... }` shorthand works **only at declaration** — you can't write\n`c = {4,5,6};` later; you'd need `c = new int[]{4,5,6};`. Either form fixes the\nlength at creation.\n",{"id":28,"difficulty":14,"q":29,"a":30},"array-is-object","Is an array a primitive or an object in Java?","An array is always an **object** on the heap, even an array of primitives. The\nvariable holds a **reference** to it, the array has a runtime class\n(`int[].class`), and it inherits from `Object` — so you can call\n`clone()`, read `.length`, and store it in an `Object` variable.\n\n```java\nint[] a = {1, 2, 3};\nObject o = a;                  \u002F\u002F arrays are Objects\nSystem.out.println(a.getClass().getName()); \u002F\u002F \"[I\" — int array\nint[] copy = a.clone();        \u002F\u002F inherited (overridden) clone\n```\n\nBecause it's an object, an array variable can be `null`, and elements of a\nprimitive array are stored **inline** (contiguously) while elements of an object\narray are **references**.\n",{"id":32,"difficulty":14,"q":33,"a":34},"default-values","What are the default values of array elements?","Allocating an array with `new` **zero-initializes** every element — you never get\ngarbage. The default depends on the element type:\n\n| Element type | Default |\n| ------------ | ------- |\n| numeric (`int`, `double`, …) | `0` \u002F `0.0` |\n| `boolean` | `false` |\n| `char` | `'\u0000'` (null char) |\n| reference (`String`, objects) | `null` |\n\n```java\nint[] nums = new int[3];        \u002F\u002F {0, 0, 0}\nboolean[] flags = new boolean[2]; \u002F\u002F {false, false}\nString[] names = new String[2]; \u002F\u002F {null, null}\n```\n\nThis differs from **local variables**, which get no default and must be assigned\nbefore use. Array slots, like fields, are always initialized.\n",{"id":36,"difficulty":14,"q":37,"a":38},"length-fixed","Can you change the size of an array after creation?","No. An array's **length is fixed at creation** and can never change. To \"grow\"\none you allocate a **new, larger array** and copy the elements over (which is\nexactly what `ArrayList` does internally).\n\n```java\nint[] a = {1, 2, 3};\n\u002F\u002F a = a + one element  -> not possible\nint[] bigger = Arrays.copyOf(a, a.length + 1); \u002F\u002F new array, last slot = 0\nbigger[3] = 4;          \u002F\u002F {1, 2, 3, 4}\n```\n\nIf you need a resizable, append-friendly structure, reach for `ArrayList`\ninstead of hand-rolling array growth.\n",{"id":40,"difficulty":14,"q":41,"a":42},"length-field","What is the difference between length, length() and size()?","Three different things that beginners confuse:\n\n- **`array.length`** — a **field** (no parentheses) giving an array's size.\n- **`string.length()`** — a **method** giving a `String`'s character count.\n- **`collection.size()`** — a **method** on `List`\u002F`Set`\u002F`Map` giving its element count.\n\n```java\nint[] a = {1, 2, 3};\nString s = \"hello\";\nList\u003CInteger> list = List.of(1, 2);\n\na.length     \u002F\u002F 3  — field, no ()\ns.length()   \u002F\u002F 5  — method\nlist.size()  \u002F\u002F 2  — method\n```\n\nWriting `a.length()` or `s.length` is a compile error — memorize which is which.\n",{"id":44,"difficulty":14,"q":45,"a":46},"index-out-of-bounds","What happens when you access an index outside an array's bounds?","Java performs **bounds checking** on every access. A valid index is `0` to\n`length - 1`; anything else throws **`ArrayIndexOutOfBoundsException`** at\nruntime (it's unchecked, so it isn't caught at compile time).\n\n```java\nint[] a = {10, 20, 30};\na[0];    \u002F\u002F 10 — first element\na[2];    \u002F\u002F 30 — last (length - 1)\na[3];    \u002F\u002F ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3\na[-1];   \u002F\u002F also AIOOBE — no negative indexing in Java\n```\n\nUnlike some languages, Java has **no negative indexing**; `a[-1]` is an error,\nnot \"last element\". Bounds checks are what make Java memory-safe here.\n",{"id":48,"difficulty":49,"q":50,"a":51},"negative-size","medium","What happens if you create an array with a negative size?","The size is evaluated at runtime, and a **negative** length throws\n**`NegativeArraySizeException`**. A size of `0` is perfectly legal — it gives a\nvalid, empty array.\n\n```java\nint[] ok    = new int[0];   \u002F\u002F legal — empty array, length 0\nint n = -1;\nint[] bad   = new int[n];   \u002F\u002F NegativeArraySizeException at runtime\n```\n\nThis catches interviewees who assume any compile-passing `new int[expr]` is\nsafe — a computed negative size blows up only when the line executes.\n",{"id":53,"difficulty":49,"q":54,"a":55},"multidimensional","How do multidimensional arrays work in Java?","Java has no true 2D arrays — `int[][]` is an **array of arrays**. The outer array\nholds references to inner arrays, each a separate heap object.\n\n```java\nint[][] grid = new int[2][3];  \u002F\u002F 2 rows, each an int[3]\ngrid[0][1] = 5;\ngrid.length      \u002F\u002F 2 — number of rows\ngrid[0].length   \u002F\u002F 3 — columns in row 0\n\nfor (int[] row : grid)         \u002F\u002F each row is itself an int[]\n  for (int v : row) { \u002F* ... *\u002F }\n```\n\nBecause the inner arrays are independent objects, accessing `grid[i][j]` is two\npointer hops. You can also declare more dimensions (`int[][][]`) the same way.\n",{"id":57,"difficulty":49,"q":58,"a":59},"jagged-arrays","What is a jagged (ragged) array?","A **jagged** array is a multidimensional array whose inner rows have **different\nlengths**. Since each row is a separate array object, this is fully legal — you\njust allocate the rows yourself.\n\n```java\nint[][] jagged = new int[3][];   \u002F\u002F 3 rows, none allocated yet\njagged[0] = new int[]{1};        \u002F\u002F length 1\njagged[1] = new int[]{2, 3};     \u002F\u002F length 2\njagged[2] = new int[]{4, 5, 6};  \u002F\u002F length 3\n\nfor (int[] row : jagged)\n  System.out.println(row.length); \u002F\u002F 1, 2, 3\n```\n\nAlways iterate with `row.length` rather than a fixed column count, since rows\ncan differ — and an unallocated row stays `null` until you assign it.\n",{"id":61,"difficulty":49,"q":62,"a":63},"array-of-objects","How does an array of objects differ from an array of primitives?","A primitive array stores the **values inline**; an object array stores\n**references**, and creating it does **not** create the objects — every slot\nstarts as `null`.\n\n```java\nint[] nums = new int[2];        \u002F\u002F {0, 0} — values ready to use\nString[] names = new String[2]; \u002F\u002F {null, null} — no String objects yet\n\nnames[0].length();              \u002F\u002F NullPointerException — slot is null!\nnames[0] = \"Ada\";               \u002F\u002F must populate first\nnames[0].length();              \u002F\u002F now 3\n```\n\nThe classic bug: iterating an object array and calling methods before filling it,\nwhich throws `NullPointerException`. Primitive arrays never have this problem.\n",{"id":65,"difficulty":66,"q":67,"a":68},"array-covariance","hard","What is array covariance in Java?","Java arrays are **covariant**: if `Sub` extends `Super`, then `Sub[]` is a\nsubtype of `Super[]`. So you can assign a `String[]` to an `Object[]` variable.\nThis is convenient but **not type-safe** at compile time.\n\n```java\nObject[] arr = new String[3];   \u002F\u002F legal — covariance\narr[0] = \"ok\";                  \u002F\u002F fine, it's really a String[]\narr[1] = 42;                    \u002F\u002F compiles, but throws at runtime\n```\n\nContrast with **generics**, which are *invariant* — `List\u003CString>` is **not** a\n`List\u003CObject>`. Generics chose compile-time safety; arrays chose flexibility,\npushing the check to runtime (see `ArrayStoreException`).\n",{"id":70,"difficulty":66,"q":71,"a":72},"array-store-exception","When does ArrayStoreException occur?","Because arrays are covariant, the JVM must check at **runtime** that every value\nyou store is compatible with the array's **actual** element type. Storing an\nincompatible type throws **`ArrayStoreException`**.\n\n```java\nObject[] arr = new String[2];   \u002F\u002F actual type is String[]\narr[0] = \"hi\";                  \u002F\u002F OK\narr[0] = Integer.valueOf(42);   \u002F\u002F ArrayStoreException at runtime\n```\n\nThis runtime store check is the price of covariance, and it's why generics were\ndesigned to be invariant — the compiler can guarantee type safety for\n`List\u003CString>`, so no equivalent check is needed.\n",{"id":74,"difficulty":49,"q":75,"a":76},"arrays-sort","How do you sort an array, including with a Comparator?","`Arrays.sort` sorts **in place**. Primitive arrays use a tuned dual-pivot\nquicksort; object arrays use a stable merge sort and can take a `Comparator`.\n\n```java\nint[] nums = {3, 1, 2};\nArrays.sort(nums);                  \u002F\u002F {1, 2, 3} — natural order\n\nString[] words = {\"banana\", \"apple\"};\nArrays.sort(words);                 \u002F\u002F natural (lexicographic)\nArrays.sort(words, Comparator.reverseOrder()); \u002F\u002F {\"banana\", \"apple\"}\nArrays.sort(words, Comparator.comparingInt(String::length)); \u002F\u002F by length\n\nArrays.sort(nums, 0, 2);            \u002F\u002F sort only a sub-range [0,2)\n```\n\nNote primitive arrays **can't** take a `Comparator` (no objects to compare) — box\nto `Integer[]` if you need custom ordering of numbers.\n",{"id":78,"difficulty":49,"q":79,"a":80},"parallel-sort","What is Arrays.parallelSort and when would you use it?","`Arrays.parallelSort` (Java 8+) sorts large arrays using a **parallel\nmerge-sort** across the common ForkJoinPool, then merges the pieces. Same result\nas `Arrays.sort`, faster on big arrays and multiple cores.\n\n```java\nint[] big = new int[10_000_000];\n\u002F\u002F ... fill big ...\nArrays.parallelSort(big);    \u002F\u002F multi-threaded sort\n```\n\nIt only pays off above a size threshold (roughly a few thousand elements);\nbelow that it falls back to a sequential sort, so for small arrays plain\n`Arrays.sort` is simpler and just as fast.\n",{"id":82,"difficulty":49,"q":83,"a":84},"binary-search","How does Arrays.binarySearch work and what is the catch?","`Arrays.binarySearch` does an O(log n) search but **requires the array to be\nsorted first** — on unsorted input the result is undefined. If found it returns\nthe index; if not, it returns a **negative** value: `-(insertionPoint) - 1`.\n\n```java\nint[] a = {10, 20, 30, 40};\nArrays.binarySearch(a, 30);   \u002F\u002F 2  — found at index 2\nArrays.binarySearch(a, 25);   \u002F\u002F -3 — would insert at index 2: -(2)-1\n```\n\nDecode a miss with `int insertAt = -result - 1;`. Forgetting to sort first is the\nmost common bug — `binarySearch` silently returns garbage on unsorted data.\n",{"id":86,"difficulty":14,"q":87,"a":88},"fill-equals-tostring","What do Arrays.fill, Arrays.equals and Arrays.toString do?","Three everyday `Arrays` helpers:\n\n- **`fill`** — sets every element (or a range) to one value.\n- **`equals`** — element-by-element value comparison (`==` on arrays only checks references).\n- **`toString`** — a readable `\"[1, 2, 3]\"` (an array's own `toString` prints `[I@1b6d3586`).\n\n```java\nint[] a = new int[3];\nArrays.fill(a, 7);              \u002F\u002F {7, 7, 7}\n\nint[] b = {7, 7, 7};\na == b              \u002F\u002F false — different objects\nArrays.equals(a, b) \u002F\u002F true  — same contents\n\nSystem.out.println(a);                 \u002F\u002F [I@... (unhelpful)\nSystem.out.println(Arrays.toString(a)); \u002F\u002F [7, 7, 7]\n```\n\nAlways use `Arrays.equals`\u002F`Arrays.toString` — the inherited `Object` versions\ncompare references and print the type+hash.\n",{"id":90,"difficulty":49,"q":91,"a":92},"deep-equals-tostring","What is the difference between equals\u002FdeepEquals and toString\u002FdeepToString?","The plain `Arrays.equals` and `Arrays.toString` are **shallow** — for a 2D array\nthey compare\u002Fprint the inner arrays by reference, which is wrong. The\n**`deep`** variants recurse into nested arrays.\n\n```java\nint[][] a = {{1, 2}, {3, 4}};\nint[][] b = {{1, 2}, {3, 4}};\n\nArrays.equals(a, b)      \u002F\u002F false — compares inner int[] references\nArrays.deepEquals(a, b)  \u002F\u002F true  — recurses into rows\n\nArrays.toString(a)       \u002F\u002F [[I@..., [I@...]\nArrays.deepToString(a)   \u002F\u002F [[1, 2], [3, 4]]\n```\n\nRule: use `deepEquals`\u002F`deepToString` for **multidimensional or nested** arrays,\nthe shallow ones for flat arrays.\n",{"id":94,"difficulty":49,"q":95,"a":96},"copyof-copyofrange","How do Arrays.copyOf and Arrays.copyOfRange work?","Both return a **new** array. `copyOf` copies from the start to a given length\n(truncating or **zero-padding** if longer); `copyOfRange` copies a `[from, to)`\nslice.\n\n```java\nint[] a = {1, 2, 3};\nArrays.copyOf(a, 2);          \u002F\u002F {1, 2}        — truncated\nArrays.copyOf(a, 5);          \u002F\u002F {1, 2, 3, 0, 0} — padded with defaults\nArrays.copyOfRange(a, 1, 3);  \u002F\u002F {2, 3}        — indices 1..2 (to is exclusive)\n```\n\n`copyOf(a, a.length + n)` is the standard idiom for \"grow this array\". Both are\n**shallow** copies for object arrays (they copy references, not the objects).\n",{"id":98,"difficulty":49,"q":99,"a":100},"system-arraycopy","What is System.arraycopy and how is it different from copyOf?","`System.arraycopy` is a **native, low-level** bulk copy into an **existing**\ndestination array: `arraycopy(src, srcPos, dest, destPos, length)`. It's the\nfastest copy and what `copyOf`\u002F`ArrayList` use under the hood — but you must\nallocate the destination yourself.\n\n```java\nint[] src = {1, 2, 3, 4, 5};\nint[] dest = new int[5];\nSystem.arraycopy(src, 1, dest, 0, 3); \u002F\u002F dest = {2, 3, 4, 0, 0}\n```\n\nUse `System.arraycopy` when copying into an array you already have (or inserting\na range); use `Arrays.copyOf` when you just want a fresh copy and let it do the\nallocation.\n",{"id":102,"difficulty":66,"q":103,"a":104},"clone-shallow","Is array clone() a deep or shallow copy?","`clone()` makes a **shallow** copy: a new array of the same length with the same\nelements. For a primitive array that's effectively a deep copy. For an object (or\n2D) array, the **references are copied** — both arrays point at the same objects.\n\n```java\nint[] a = {1, 2, 3};\nint[] b = a.clone();\nb[0] = 99;            \u002F\u002F a unchanged — independent (primitives)\n\nint[][] grid = {{1, 2}, {3, 4}};\nint[][] copy = grid.clone();\ncopy[0][0] = 99;      \u002F\u002F grid[0][0] is ALSO 99 — shared inner array!\n```\n\nTo truly deep-copy a 2D array, clone each row yourself:\n`for (int i = 0; i \u003C grid.length; i++) copy[i] = grid[i].clone();`.\n",{"id":106,"difficulty":66,"q":107,"a":108},"aslist-gotcha","What is the gotcha with Arrays.asList?","`Arrays.asList` returns a **fixed-size** `List` **backed by the array** — it's a\n*view*, not a normal `ArrayList`. You can read and `set`, but `add`\u002F`remove`\nthrow `UnsupportedOperationException`, and changes write through to the array.\n\n```java\nInteger[] arr = {1, 2, 3};\nList\u003CInteger> list = Arrays.asList(arr);\nlist.set(0, 99);     \u002F\u002F OK — also changes arr[0] to 99\nlist.add(4);         \u002F\u002F UnsupportedOperationException — fixed size\n\n\u002F\u002F also: passing an int[] gives a List\u003Cint[]> of size 1, not List\u003CInteger>!\nList\u003CInteger> wrong = Arrays.asList(1, 2, 3); \u002F\u002F OK with varargs of Integer\n\n\u002F\u002F for a real mutable list:\nList\u003CInteger> real = new ArrayList\u003C>(Arrays.asList(arr));\n```\n\nTwo traps: it's **not resizable**, and `Arrays.asList(intArray)` boxes the\n*array itself* (a one-element `List\u003Cint[]>`) — use an `Integer[]` or a stream.\n",{"id":110,"difficulty":49,"q":111,"a":112},"array-to-stream","How do you convert between an array, a List and a Stream?","The standard bridges:\n\n```java\nint[] prims = {1, 2, 3};\nIntStream is = Arrays.stream(prims);     \u002F\u002F primitive array -> IntStream\nint[] back  = is.map(x -> x * 2).toArray();\n\nString[] arr = {\"a\", \"b\"};\nList\u003CString> list = new ArrayList\u003C>(Arrays.asList(arr)); \u002F\u002F array -> List\nString[] arr2 = list.toArray(new String[0]);            \u002F\u002F List -> array\n\nStream\u003CString> s = Arrays.stream(arr);   \u002F\u002F object array -> Stream\nString[] arr3 = s.toArray(String[]::new);\n```\n\nNote `Arrays.stream(int[])` gives an `IntStream` (no boxing), whereas\n`Stream.of(int[])` would give a `Stream\u003Cint[]>` of one element — prefer\n`Arrays.stream` for primitive arrays.\n",{"id":114,"difficulty":49,"q":115,"a":116},"varargs-arrays","How are varargs related to arrays?","A varargs parameter (`Type... args`) **is an array** — the compiler packages the\npassed arguments into a `Type[]`. Inside the method `args` is a normal array with\n`.length` and indexing.\n\n```java\nstatic int sum(int... nums) {     \u002F\u002F nums is really an int[]\n  int total = 0;\n  for (int n : nums) total += n;  \u002F\u002F iterate like any array\n  return total;\n}\nsum(1, 2, 3);          \u002F\u002F compiler builds new int[]{1, 2, 3}\nsum(new int[]{1, 2});  \u002F\u002F can also pass an array directly\nsum();                 \u002F\u002F empty array, length 0 (not null)\n```\n\nBecause it's just an array, varargs must be the **last** parameter, and passing\nan existing array works directly. An empty call yields a zero-length array, not\n`null`.\n",{"id":118,"difficulty":49,"q":119,"a":120},"array-vs-arraylist","What is the difference between an array and an ArrayList?","| Aspect | Array | `ArrayList` |\n| ------ | ----- | ----------- |\n| Size | **fixed** at creation | **dynamic** (grows\u002Fshrinks) |\n| Element type | primitives **or** objects | objects only (boxes primitives) |\n| Access | `a[i]`, field `.length` | `get(i)`\u002F`set`, method `.size()` |\n| Type safety | covariant (runtime check) | generic, invariant (compile-time) |\n| Performance | no boxing, less overhead | boxing + resize cost |\n\n```java\nint[] arr = new int[3];          \u002F\u002F fixed, primitive, fast\nList\u003CInteger> list = new ArrayList\u003C>(); \u002F\u002F resizable, boxes ints\nlist.add(1); list.add(2);        \u002F\u002F grows automatically\n```\n\nChoose an **array** for fixed-size, primitive-heavy, performance-critical code;\nchoose **`ArrayList`** when the size varies or you want the rich `List` API.\n`ArrayList` is itself backed by a resizing array.\n",24,null,{"description":11},"Java arrays interview questions — declaration and initialization, default values, multidimensional and jagged arrays, array covariance, Arrays utility methods, copying, and array vs ArrayList.","java\u002Ffundamentals\u002Farrays","Fundamentals","fundamentals","2026-06-20","0j6qqsSf8ktXBDepdiNsvEtmK97n9_F-BthkA5x8Low",[131,135,138,139],{"subtopic":132,"path":133,"order":134},"Data Types & Variables","\u002Fjava\u002Ffundamentals\u002Fdata-types-variables",1,{"subtopic":136,"path":137,"order":12},"Strings","\u002Fjava\u002Ffundamentals\u002Fstrings",{"subtopic":6,"path":21,"order":20},{"subtopic":140,"path":141,"order":142},"Keywords & Modifiers","\u002Fjava\u002Ffundamentals\u002Fkeywords-modifiers",4,{"path":144,"title":145},"\u002Fblog\u002Fjava-arrays-declaration-utilities","Java Arrays — Declaration, the Arrays Utility Class & Gotchas",1782244115242]