Question

I am pretty confused about array initialization.finds it quite complex task.

public int[] make2(int[] a, int[] b) {
  int[] make2=new int[2];
  if(a.length==2 )
  {
  make2={a[0],a[1]};
  }

  return make2;
}

Is it wrong? can anyone explain the ways to initialize a array without taking a loop.

Update for this

Here is the updated code. But can you please let me know the version which will help me to avoid creating a extra array which is of no use.When i do not use it and directly returns the make 2 at end,the compiler complains that make2 cannot be resolved

public int[] make2(int[] a, int[] b) {
 int[] large=new int[3];
  if(a.length>=2 )
  {
 int[] make2={a[0],a[1]};
 return make2;
  }
  else if(a.length==1)
  {
 int[] make2={a[0],b[0]};
 return make2;
  }
  else if(a.length==0)
  {
 int[] make2={b[0],b[1]};
 return make2;
  }
return large;
}
Was it helpful?

Solution

You can simply:

int make2[] = new int[]{a[0], a[1]};

OTHER TIPS

int[] make2 = new int[] { a[0], a[1] };

you can do like below:

int[] a = {1,2,3, 4,5,6,7};

or

    int[] a = {1,2};
    int[] b={2,3};
    int[] aa={a[0], b[1]};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top