Write a Java Program to Pass ArrayList as the function argument

Java Program to Pass ArrayList as the function argument

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Pass ArrayList as the function argument
Java Program to Pass ArrayList as the function argument

Write a Java Program to Pass ArrayList as the function argument

PROGRAM: Java Program to Pass ArrayList as the function argument

/*Java Program to Pass ArrayList as the function argument*/

1: Pass ArrayList as Function Parameter

import java.util.ArrayList;

class Main {

public static void display(ArrayList<String> languages) {

System.out.print(“ArrayList: “);
for(String language : languages) {
System.out.print(language + “, “);
}
}
public static void main(String[] args) {

// create an arraylist
ArrayList<String> languages = new ArrayList<>();
languages.add(“Java”);
languages.add(“Python”);
languages.add(“JavaScript”);

// passing arraylist as function parameter
display(languages);
}
}

2: Pass ArrayList as Function Parameter by converting into Array

import java.util.ArrayList;

class Main {

public static void percentage(Integer[] marks) {
int totalMarks = 300;
int obtainedMarks = 0;
for(int mark : marks) {
obtainedMarks += mark;
}

// compute average
double percent = (obtainedMarks * 100) / totalMarks;
System.out.println(“Percentage: ” + percent);
}
public static void main(String[] args) {

// create an arraylist
ArrayList<Integer> marks = new ArrayList<>();
marks.add(67);
marks.add(87);
marks.add(56);
System.out.println(“Marks: ” + marks);

// passing arraylist as function parameter
percentage(marks.toArray(new Integer[marks.size()]));
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *