Thursday, February 9, 2012

Variable arguments in java


Variable Arguments is efficient if you need to have same method name and arguments may vary slightly based on the scenario.

For Ex: You may need to perform the same operation for 2 different places by passing 1 more argument and handle the condition in operation based on 1 argument. As per method overloading (Polymorphism) you need to have 2 methods with different arguments. You can use variable arguments to avoid having 2 methods just for 1 more argument.

The ellipsis (...) identifies a variable number of arguments, and is demonstrated in the following summation method.

Variable argument (varargs) is an array. Refer : https://today.java.net/pub/a/today/2004/04/19/varargs.html

Check the length and null checks and loop through the same to get the values from the variables.

Syntax

type ... variableName

Example Test code :
package com.gubs.test;

public class VariableArgumentsTest {

/**
* @param args
*/
public static void main(String[] args) {
VariableArgumentsTest variableArgumentsTest = new VariableArgumentsTest();
variableArgumentsTest.addValues("Add Operation : ", 10, 20);
variableArgumentsTest.addValues(
"Add Operation with variable arguments : ", 10, 20, 30, 40);

}

private void addValues(String msg, int a, int b, int... c) {
int total = a + b;
// c is an variable argument integer array if you pass int, its a array
// of type. You can pass any number of
// arguments.
if (c != null) {
for (int i = 0; i <= c.length; i++) {
total = c[i] + total;
}
}
System.out.println(msg + total);
}
}
Output :

Add Operation Result: 30
Add Operation Result with variable arguments : 100

In Java, what's the difference between public, default, protected, and private?

Modifier    | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public      |  y    |    y    |    y     |   y
————————————+———————+—————————+——————————+———————
protected   |  y    |    y    |    y     |   n
————————————+———————+—————————+——————————+———————
no modifier |  y    |    y    |    n     |   n
————————————+———————+—————————+——————————+———————
private     |  y    |    n    |    n     |   n

y: accessible
n: not accessible


1 comment :

Unknown said...


Our PHP Programmers team delivers Web solutions for businesses in e-commerce, healthcare, manufacturing, education, telecommunications, financial services and insurance.

// Below script tag for SyntaxHighLighter