
- 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 use variable arguments as an input when dealing with method overloading in Java
Problem Description
How to use variable arguments as an input when dealing with method overloading?
Solution
This example displays how to overload methods which have variable arguments as an input.
public class Main { static void vaTest(int ... no) { System.out.print( "vaTest(int ...): " + "Number of args: " + no.length +" Contents: "); for(int n : no)System.out.print(n + " "); System.out.println(); } static void vaTest(boolean ... bl) { System.out.print( "vaTest(boolean ...) " + "Number of args: " + bl.length + " Contents: "); for(boolean b : bl)System.out.print(b + " "); System.out.println(); } static void vaTest(String msg, int ... no) { System.out.print( "vaTest(String, int ...): " + msg +"no. of arguments: "+ no.length +" Contents: "); for(int n : no) System.out.print(n + " "); System.out.println(); } public static void main(String args[]) { vaTest(1, 2, 3); vaTest("Testing: ", 10, 20); vaTest(true, false, false); } }
Result
The above code sample will produce the following result.
vaTest(int ...): Number of args: 3 Contents: 1 2 3 vaTest(String, int ...): Testing: no. of arguments: 2 Contents: 10 20 vaTest(boolean ...) Number of args: 3 Contents: true false false
The following is an another sample example of varargs with method overloading.
public class Vararg { static void vararg(Integer... x) { System.out.println("Integer..."); } static void vararg(String... x) { System.out.println("String..."); } public static void main(String [] args) { int s = 0; vararg(s,s); } }
The above code sample will produce the following result.
Integer...
java_methods.htm
Advertisements