-5

I have writen a code like below-

public class ArrayExample {

    public static void main(String[] args) {

        int[] myArray = { 20, 50, 40, 8 };
        for (int i = 0; i < myArray.length; i++) {
            System.out.println(myArray[i]);
        }
    }
}

output is: 20 50 40 8

Now i want to change the value of myArray.Now I want to set myArray = {100,1,200,80};

I have searched and tried but unable to do this.Please Java Experts need your help.

user3732316
  • 63
  • 1
  • 7
  • Did you search google with your doubt-simply `int[] myArray = { 100, 1,200,80 };` would have solved your purpose as achieved previously!!! – Am_I_Helpful Jun 18 '14 at 04:27
  • 2
    You know the elements, you have a `for` loop running and you know about accessing arrays using indexes. What else is difficult here? – Rahul Jun 18 '14 at 04:27

2 Answers2

3

Simply declare it with new values.

 int[] myArray = {100,1,200,80};
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
NotSoOldNick
  • 555
  • 4
  • 11
  • @NotSoOldNick-There is no need of `new int[]`! – Am_I_Helpful Jun 18 '14 at 04:29
  • 3
    @shekharsuman The new int[] is indeed necessary. `Array constants can only be used in initializers` – Bryan Jun 18 '14 at 04:33
  • @Bryan-That's what I am saying.See,his answer as per the amended code,it's fine as he has initialized the array afresh. So,no new need of `new int[]`! – Am_I_Helpful Jun 18 '14 at 04:34
  • 1
    @shekharsuman read the question again, he's saying that he 'now want to change the value of the array', Bryan is right – ethanfar Jun 18 '14 at 04:36
  • @Bryan-I didn't read the question properly. – Am_I_Helpful Jun 18 '14 at 04:45
  • @eitanfar-Thanks for pointing out about the hurriedness! – Am_I_Helpful Jun 18 '14 at 04:45
  • @shekharsuman I also misunderstood your intention. Either way works. Just a difference between initializing and re-initializing. – Bryan Jun 18 '14 at 04:47
  • So in other words, my initial answer before being edited was fine: you can either re-initialise the same variable using `myArray = new int[]{100,1,200,80};` or declare a new one using `int myNewArray = {100,1,200,80};`, or even use the solution provided by @Fahriyal Afif, which is equally correct. – NotSoOldNick Jun 18 '14 at 04:59
0
myArray[0] = 100;
myArray[1] = 1;
myArray[2] = 200;
myArray[3] = 80;
Fahriyal Afif
  • 560
  • 3
  • 11