Can I initialize an array with all -1 in Java? What is the shortest code for that?
- User
Can I initialize an array with all -1 in Java? What is the shortest code for that?
Assistant
Yes, you can initialize an array with all elements set to
-1in Java. The shortest and most concise way to do this is by usingArrays.fill()from thejava.util.Arraysclass. Here’s the shortest code:import java.util.Arrays; public class Main { public static void main(String[] args) { int[] array = new int[10]; Arrays.fill(array, -1); } }If you want to avoid importing
java.util.Arrays, you can manually initialize the array in a loop, but it will be slightly longer:public class Main { public static void main(String[] args) { int[] array = new int[10]; for (int i = 0; i < array.length; i++) { array[i] = -1; } } }However, using
Arrays.fill()is the most concise and idiomatic way to achieve this.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.