0
Enhanced For Loop apart from Array Literal
Can we use For Each Loop for a Normal Array Which is Not an Array Literal?
9 ответов
+ 3
Osman Shams ,
answer to your first reply in this thread :
You can't modify actual array elements using a for-each loop.
as of your example:
int [] arr=new int[4];
if you try to change them in foreach as:
for(var elem:arr)
elem=5;
It'll NOT change elements of existing array. The iteration variable `elem` is just a copy of array element. any modification to this variable won't be reflected in original array.
so as you asked, you can't get input for every element of array using for-each however following code will do required work as it operates on actual array elements :
for(int i=0;i<arr.length;i++)
arr[i]=sc.nextInt();
+ 2
Ipang ,It's not possible with for each but the second version will do work (as mentioned in previous answer)
In case you are asking in context with functions, Java is strictly pass by value. When object reference is passed it's copied by value as it still points to same object you can modify object in called function.
in case of primitives , again, it'll work on it's copy. arguments won't be affected.
Also I'm new to Java just started learning in this very month (December 2019). This is just what I have learned so far , If there are some errors I'll be glad for corrections 🙂👍
+ 2
🇮🇳Omkar🕉
Thanks for the headsup bro! 👍
So I guess this is a by design policy in Java, got it!
+ 1
int [] arr = {1,2,3,4,5};
for(int a : arr)
System.out.println(a);
+ 1
I think I didn't understand the question well. Are you asking about using the for each loop for TAKING user input?
+ 1
Yes you can.
0
Bro For A user Defined Array whose Elements are not known for something like this
int [ ] arr = new int[4];
(And the user will be promoted to fill the array, can we use For Each Loop in that Case?)
0
No for Traversing through an Array which is not Array Literal