
- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to make a method take variable lentgth argument as an input using Java
Problem Description
How to make a method take variable lentgth argument as an input?
Solution
This example creates sumvarargs() method which takes variable no of int numbers as an argument and returns the sum of these arguments as an output.
public class Main { static int sumvarargs(int... intArrays) { int sum, i; sum = 0; for(i = 0; i< intArrays.length; i++) { sum += intArrays[i]; } return(sum); } public static void main(String args[]) { int sum = 0; sum = sumvarargs(new int[]{10,12,33}); System.out.println("The sum of the numbers is: " + sum); } }
Result
The above code sample will produce the following result.
The sum of the numbers is: 55
The following is an another sample example of Varargs
public class HelloWorld { static void display(String... values) { System.out.println("display method invoked "); for(String s:values) { System.out.println(s); } } public static void main(String args[]) { display(); display("Tutorialspoint"); display("my","name","is","Sairamkrishna Mammahe"); } }
The above code sample will produce the following result.
display method invoked display method invoked Tutorialspoint display method invoked my name is Sairamkrishna Mammahe
java_methods.htm
Advertisements