Web Development, SEO, Social Media, Software & Database Development
Java Passing Array To Method
Some simple code to show how to pass a basic array to a method and then manipulate elements within that method.
------------------------------------CODE-------------------------------------
public class PassArray
{
public static void main(String args[])
{
int array[] ={1,2,3,4,5};
System.out.println(" Effects of passing reference to entire array ");
////////////////////////////////////
/// output original array elements//
////////////////////////////////////
for (int value : array)
{
System.out.printf(" %d",value);
}
modifyArray(array);
System.out.println("\n\nThe Values of the modified array are :");
////////////////////////
//output modified arry//
////////////////////////
for (int value : array)
{
System.out.printf(" %d",value);
}
System.out.printf("\n\nThe Values of the modified array are :\n"+"
array[3] before mofifiedElement : %d\n",array[3]);
modifyElement(array[3]);
System.out.printf("\n\nThe Values of the modified array are :\n"+"
array[3] before mofifiedElement : %d\n",array[3]);
}
public static void modifyArray(int array2[])
{
for (int counter=0; counter<array2.length; counter++)
{
array2[counter] *=2; ///array2[counter] = array2[counter] * 2
}
}
public static void modifyElement(int element)
{
element *=2; ///element = element * 2
System.out.printf("Value of element in modifyElement : %d\n",element);
}
}
----------------------------OUTPUT----------------------------------------
Effects of passing reference to entire array
1 2 3 4 5
The Values of the modified array are :
2 4 6 8 10
The Values of the modified array are :
array[3] before mofifiedElement : 8
Value of element in modifyElement : 16
The Values of the modified array are :
array[3] before mofifiedElement : 8
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment