How to declare and initialize and print array in Java

6 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("%2d", arr[i]);
        }
    }
}
 
 
 
 
 
/*
run:
  
 1 2 3 4 5 6
  
*/

 



answered Mar 21, 2023 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        
        System.out.printf(Arrays.toString(arr));
    }
}
 
 
 
 
 
/*
run:
  
[1, 2, 3, 4, 5, 6]
  
*/

 



answered Mar 21, 2023 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int[] arr = new int[7];
        
        System.out.println(Arrays.toString(arr));
        
        Arrays.fill(arr, 1, 4, -9);
        
        System.out.println(Arrays.toString(arr));
    }
}
 
 
 
 
 
/*
run:
  
[0, 0, 0, 0, 0, 0, 0]
[0, -9, -9, -9, 0, 0, 0]
  
*/

 



answered Mar 21, 2023 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int[] arr = new int[7];
        
        System.out.println(Arrays.toString(arr));
        
        Arrays.setAll(arr, i -> i);
        
        System.out.println(Arrays.toString(arr));
    }
}
 
 
 
 
 
/*
run:
  
[0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6]
  
*/

 



answered Mar 21, 2023 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        int[] arr = new int[7];
        
        System.out.println(Arrays.toString(arr));
        
        Arrays.fill(arr, -9);
        
        System.out.println(Arrays.toString(arr));
    }
}
 
 
 
 
 
/*
run:
  
[0, 0, 0, 0, 0, 0, 0]
[-9, -9, -9, -9, -9, -9, -9]
  
*/

 



answered Mar 21, 2023 by avibootz
0 votes
import java.util.Arrays;
import java.util.stream.IntStream;

public class MyClass {
    public static void main(String args[]) {
        int[] arr = IntStream.rangeClosed(1, 7).toArray();
        
        System.out.println(Arrays.toString(arr));
    }
}
 
 
 
 
 
/*
run:
  
[1, 2, 3, 4, 5, 6, 7]
  
*/

 



answered Mar 21, 2023 by avibootz

Related questions

...