Ways to print Array in Java
Below are different ways to print string, int or any array in java.
Way 1: Using for loop
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.*; public class Main { public static void main(String[] args) { String[] str1={"welcome","to","webencyclop"}; for(int i=0;i<str1.length;i++) { System.out.println(str1[i]); } } } |
Output:
1 2 3 |
welcome to webencyclop |
If you want to print output in one line check this post
To print int array.
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.*; public class Main { public static void main(String[] args) { int[] arr={1,2,3,4,5,6}; for(int i=0;i<arr.length;i++) { System.out.print(arr[i] + " "); } } } |
Output:
1 |
1 2 3 4 5 6 |
Way 2: Using for Arrays.toString() method
1 2 3 4 5 6 7 8 9 |
import java.util.*; public class Main { public static void main(String[] args) { String[] str1={"welcome","to","webencyclop"}; System.out.println(Arrays.toString(str1)); } } |
Output:
1 |
[welcome, to, webencyclop] |