Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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

...