Java array interview questions
Following Java program calculate the sum of the array by passing the array to the user define method (Not pre-define method of java library).
Java pass array to method
// Java program to pass the array to the method import java.util.Scanner; public class PassArrayToTheMethod { public static void add(int[] a){ int sum=0; for(int l=0;l<a.length;l++) sum=sum+a[l]; System.out.println("Sum: "+sum); } public static void input(int[] b){ Scanner uk=new Scanner(System.in); System.out.println("Enter 5 numbers"); for(int l=0;l<b.length;l++){ b[l]= uk.nextInt(); } } public static void main(String[] args) { int z[]=new int[5]; PassArrayToTheMethod.input(z); PassArrayToTheMethod.add(z ); } }
Output
Enter 5 numbers 1 1 1 1 1 Sum: 5