How do I make an array parameter in java? - java

I tried to make a parameter for an array for a method, but it always comes up with an error.
public void methodExample1() {
int array1[] = new int[4]
}
public void methodExample(Array array1[]) {
System.out.println(array1[0]);
}
But it always says there's an error in my parameter. Is there any way to do this?

Try this:
public void methodExample(int[] array1)
Explanation: The type is the same that you used for declaring a value that will be passed as parameter (for the moment I'm ignoring covariant arrays), for instance if you do this:
int[] array1 = new int[4];
... Then, at the time of passing it as a parameter we'll write it like this:
methodExample(array1)
Also notice that the size of the array must not be passed as parameter, and that by convention the [] part goes right after the type of the array's elements (in fact, int[] is the type of the array), and not after the array's name.

If I understand your question, then you could use Array, and something like
public static void methodExample(Object array1) {
int len = Array.getLength(array1);
for (int i = 0; i < len; i++) {
System.out.printf("array1[%d] = %d%n", i, Array.get(array1, i));
}
}
public static void main(String[] args) {
methodExample(new int[] { 1, 2, 3 });
}
Output is
array1[0] = 1
array1[1] = 2
array1[2] = 3

I assume that you are trying to pass array as a parameter to a method , to initialize it and then call another method to print it?
In java you have to create an object and "allocate" memory space for it by calling to new ...
so you can do like that :
public static void main(String[] args) {
int [] m_array; // creating a array reference
m_array = new int[5]; // allocate "memory" for each of of them or you can consider it as creating a primitive of int in each cell of the array
method(m_array); // passing by value to the method a reference for the array inside the method
}
public void method(int [] arr) // here you are passing a reference by value for the allocated array
{
System.out.println(arr[0]);
}

Related

Trick the private keyword in Java

I am aware that the idea of the keyword private is to enable encapsulation. However, I got confused when I realized that I can modify an Array after retrieving it with a getter, which surprised me. The same didn't work for the plain integer, although I thought java treats all variables as objects.
The example:
public class PrivContainer {
private int[] myIntArray;
private int myInt;
PrivContainer(){
myIntArray=new int[1];
myIntArray[0]=3;
myInt=22;
}
public int[] getIntArray(){
return myIntArray;
}
public int getInt(){
return myInt;
}
public void printInt(){
System.out.println(myIntArray[0]);
System.out.println(myInt);
}
}
public class Main {
public static void main(String[] args){
PrivContainer pc=new PrivContainer();
int[] r=pc.getIntArray();
int q=pc.getInt();
r[0]=5;
q=33;
pc.printInt();
}
}
The Output of printInt() is 5,22
This means that main method could change the entries of the private array but not of the private int.
Could someone explain this phenomena to me?
An array is a mutable Object. Therefore, if you have a reference to that array, you can modify its contents. You can't do the same with primitive members of a class (such as int) and with references to immutable class instances (such as String and Integer).
Your assignment :
q=33;
Would be similar to :
r = new int [5];
Both of those assignments cause the variables to contain new values, but they don't affect the state of the PrivContainer instance from which the original values of those variables were assigned.
Nothing seems strange here. What happen basically as follow.
public class Main {
public static void main(String[] args){
PrivContainer pc=new PrivContainer(); <-- create new `PrivContiner` object which also initialised the private variables
int[] r=pc.getIntArray(); <-- you get the "object" integer array here and assign r to refer to that object
int q=pc.getInt(); <-- you get the "primitive" integer here and assign q to refer the myInt variable here.
r[0]=5; <-- you assign the first value of the array 5. Note that the object reference is still the same here
q=33; <-- you assign the variable q to 33. Note that, this mean, the variable q refer to another primitive here (which is 33)
pc.printInt(); <-- print the content of the object here.
}
}
When you invoke the printInt function. the output will be 5 and 22 as the new integer (33) is assigned to q and its scope is only within the main function.
While you return an array from a getter you return the reference of that object. Since you have the reference you can change its elements. If you want to avoid this behavior you will have to return the clone of your array in that case you wont be able to change the elements of your array
public class Main {
public static void main(String... args) {
Arr arr = new Arr();
int[] y = arr.getX();
y[1] = 5;
System.out.println(arr.getX()[1]);
}
}
class Arr {
private int[] x = {1, 2, 3};
public int[] getX() {
return x.clone();
}
}
Try this code and remove the clone method, like this
class Arr {
private int[] x = {1, 2, 3};
public int[] getX() {
return x;
}
}
Now execute the main method, you will observe that changing value of y will change the value of array x as well.

arrays passing to methods in Java - What is passed here? Value or Reference?

When I passing an object reference (arrays are objects) to a method, the value is passed, right?
In the following code the initial value is: 333. After method passing, the value is changed. Why? Is in this case the reference passed instead the value?
Are arrays "special cases"?
public static void main(String[] args) {
int[] myArray = { 333 };
valueOrRef(myArray); // Value or Reference?
System.out.println(myArray[0]); // 777 (changed)
}
public static void valueOrRef(int[] myArgument) {
myArgument[0] = 777;
}
Another approach: (the logic "pass by value"):
public static void main(String[] args) {
int[] myArray = { 333 };
valueOrRef(myArray[0]); // Value or Reference?
System.out.println(myArray[0]); // 333 (after method still unchanged)
}
public static void valueOrRef(int myArray2) {
myArray2 *= 2;
}
The value is always passed, but keep in mind that for arrays the value is in fact a reference to an array and not the array itself.
The first valueOrRef method changes the content of the array pointed at by myArgument which is why you see the effect on the array after calling the method.

Accessing arrays with methods

Hi guys i'm just starting to learn Java, and I wondering how can I access an array that was declared in a method from another method?
The design look like this:
public class Arrays{
int arraysize = 2;
public void initializeArray(){
float array[] = new float[arraySize]; // Declare array
}
public void accessArray(){
// I want to access the array from this method.
}
}
Read about scope of variables in java. This is link I could find on quick Google search. http://www.java-made-easy.com/variable-scope.html
You can declare the array at class level then it is accessible in all methods.
public class Arrays {
int arraysize = 2;
private float[] array = null;
public void initializeArray() {
array = new float[arraySize]; // Declare array
}
public void accessArray() {
// access array here.
}
}
Or You can pass the variables in method.
public class Arrays {
int arraysize = 2;
public void initializeArray() {
float[] array = new float[arraySize]; // Declare array
accessArray(array);
}
public void accessArray(float[] array) {
// access array here.
}
}
Given the amount of information, I have from question, approach 1 seems better than 2.
You need to move your declaration to make it a member, otherwise it will go out of scope once the initializeArray call ends. Then you can access the array from both methods. Try this:
public class Arrays{
float[] array;
int arraysize = 2;
public void initializeArray(){
array = new float[arraySize]; // Declare array
}
public void accessArray(){
array[0] = 1.0f;
}
}
This is done thusly
public class myClass{
int arraysize = 2;
float[] myArray; // Declare array
public myClass(){
myArray = new float[arraySize]; // initialize array
}
public float[] accessArray(){
return myArray;
}
}
The array declaration must not be done inside the class methods.
Variable declaration done inside a method limits it's scope of a variable to the method. (i.e you can't use it anywhere else).
The array is then instantiated in a constructor.
A constructor is a special function that is run when a class is instantiated.
Constructor are used to instantiated a class's variables
Constructors have the same name as their class and must not specify a return type (so no public int or public void just public)
Next you need to change the return type of the accessArray method. A return type of void states that the method isn't going to return anything. Change it to float[]
Then your accessArray method need only return the array variable.
EDIT: The
"return myArray;"
line of code gives a reference to the array to what ever called the function (Not a copy of the array, the actual array, a quick of Java is that it always does this except when returning primitive data types where it returns a copy)
If you want accessArray() to set floats in the array instead of returning the array it should be implmented like this.
public void accessArray(int index, float value){
myArray[index] = value;
}
There a two options:
You declare that array as instance variable
public class Arrays {
private int arraySize = 2;
private float array[];// Declare array
public void initializeArray() {
array = new float[arraySize];
}
public void accessArray() {
// I want to access the array from this method.
float first = array[0];
}
}
You pass the array as parameter to the method (resp. the initializeArray method should return an array)
public class Arrays {
public static void main(String[] args) {
int arraySize = 2;
float[] array = initializeArray(arraySize);
accessArray(array);
}
public static float[] initializeArray(int size) {
return new float[size];
}
public static void accessArray(float[] floats) {
// I want to access the array from this method.
float first = floats[0];
}
}

Java varargs with 2-dimensional arrays

Question is left here because people answered it, my problem was that the version of the API I was using was out of sync with the docs I had....You can in fact do this.
Is there any way to use a 2-d array in Java as an argument for an argument that expects a vararg of arrays?
The function I am trying to call is
public Long sadd(final byte[] key, final byte[]... members) {
and I have a 2-d array of bytes(byte [][] data=blah)
however if I try to call
sadd(key,data);
I get the following compiler error:
(actual argument byte[][] cannot be converted to byte[] by method invocation conversion)
Is there any way to use a 2-d array as a vararg of an array type?
The following works for me. Perhaps you're not doing what you think you're doing?
#Test
public void test_varargs() {
byte[] x = new byte[] { 1, 2, 3};
byte[] y = new byte[] { 0, 1, 2};
assertEquals(9L, sum(x,y));
byte[][] z = new byte[][] { x,y };
assertEquals(9L, sum(z));
}
public long sum(final byte[]... members) {
long sum = 0;
for (byte[] member : members) {
for (byte x : member) {
sum += x;
}
}
return sum;
}
Can you provide more of your code because this compiles for me.
byte[][] data = new byte[1][];
byte[] key = new byte[1];
long sadd = sadd(key, data);
class A {
void show(int[] ax,int[]...arr) {
for (int is : ax) {
System.out.println(is);
}
for (int[] a : arr) {
for (int i : a) {
System.out.println(i);
}
}
}
}
public class abc{
public static void main(String[] args) {
A a = new A();
int[] arr1= new int[]{10,20};
int[][] arr2 = new int[][] { { 10, 20 }, { 20, 20 }, { 30, 20 } };
a.show(arr1,arr2);
}
}
Here I have used 2-d array as var args parameter and a 1-d array as fixed parameter. Refer this code if this can help you! :)
It's not possible since the compiler has no way to infer the two dimensions. When using one-dimensional array you can determine the length of the array as the number of auxiliary arguments (those that are not mandatory).
e.g: Let's say you method definition includes n mandatory parameters and, at runtime, you supply m more arguments. Those m arguments are going to make up the array of auxiliary arguments. The length is m. In case of a two-dimensional array, the compiler has to come up with two dimensions for the array such that: dimension1 * dimension2 = m.

Modify an array passed as a method-parameter

Suppose I have an int-array and I want to modify it. I know that I cannot assign a new array to array passed as parameter:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1
}
public static void method(int[] n)
{
n = new int[]{2};
}
while I can modify it:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 2
}
public static void method(int[] n)
{
n[0] = 2;
}
Then, I tried to assign an arbitrary array to the array passed as parameter using clone():
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]); // prints 1 ?!
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
n = temp.clone();
}
Now, I wonder why it prints 1 in last example while I'm just copying the array with clone() which it's just copying the value not the reference. Could you please explain that for me?
EDIT: Is there a way to copy an array to object without changing the reference? I mean to make last example printing 2.
Your examples 1 and 3 are virtually the same in context of the question - you are trying to assign a new value to n (which is a reference to an array passed by value).
The fact that you cloned temp array doesn't matter - all it did was create a copy of temp and then assign it to n.
In order to copy values into array passed into your method method you might want to look at:System.arraycopy
It all, of course, depends on the sizes of your n array and the one you create inside method method.
Assuming they both have the same length, for example, you would do it like that:
public static void main(String[] args)
{
int[] temp_array = {1};
method(temp_array);
System.out.println(temp_array[0]);
}
public static void method(int[] n)
{
int[] temp = new int[]{2};
System.arraycopy(temp, 0, n, 0, n.length);
// or System.arraycopy(temp, 0, n, 0, temp.length) -
// since we assumed that n and temp are of the same length
}
In your method
public static void method(int[] n)
n is another name for the array that way passed in. It points to the same place in memory as the original, which is an array of ints. If you change one of the values stored in that array, all names that point to it will see the change.
However, in the actual method
public static void method(int[] n) {
int[] temp = new int[]{2};
n = temp.clone();
}
You're creating a new array and then saying "the name 'n' now points at this, other array, not the one that was passed in". In effect, the name 'n' is no longer a name for the array that was passed in.
As you correctly note, you cannot assign to the array reference passed as a parameter. (Or more precisely, the assignment won't have any effect in the caller.)
This is about the best that you can do:
public static void method(int[] n) {
int[] temp = new int[]{2};
for (int i = 0; i < temp.length; i++) {
n[i] = temp[i];
}
// ... or the equivalent using System.arraycopy(...) or some such
}
Of course, this only works properly if the size of the input array is the same as the size of the array you are copying to it. (How you should deal with this will be application specific ...)
For the record Java passes the array reference by value. It doesn't pass the array contents by value. And clone won't help to solve this problem. (At least, not with the method signature as declared.)
In your method method, nothing that you assign to n will ever change the value of the object passed in and assigned to n. At the beginning of method, n points to an array. When you assign n to equal another array, you've simply re-pointed which array n points to, and haven't changed anything about temp_array from the main method.

Categories