0

Enhanced For Loop apart from Array Literal

Can we use For Each Loop for a Normal Array Which is Not an Array Literal?

28th Dec 2019, 2:24 AM
Osman Shams
Osman Shams - avatar
9 Respostas
+ 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();
28th Dec 2019, 6:52 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 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 🙂👍
28th Dec 2019, 7:33 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 2
🇮🇳Omkar🕉 Thanks for the headsup bro! 👍 So I guess this is a by design policy in Java, got it!
28th Dec 2019, 7:36 AM
Ipang
+ 1
int [] arr = {1,2,3,4,5}; for(int a : arr) System.out.println(a);
28th Dec 2019, 2:35 AM
Avinesh
Avinesh - avatar
+ 1
I think I didn't understand the question well. Are you asking about using the for each loop for TAKING user input?
28th Dec 2019, 2:45 AM
Avinesh
Avinesh - avatar
+ 1
Yes you can.
28th Dec 2019, 2:49 AM
Avinesh
Avinesh - avatar
+ 1
Avinesh , 🇮🇳Omkar🕉 I only know assignment is possible in C++ by passing the reference. But how we do this in Java guys TIA,
28th Dec 2019, 7:25 AM
Ipang
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?)
28th Dec 2019, 2:39 AM
Osman Shams
Osman Shams - avatar
0
No for Traversing through an Array which is not Array Literal
28th Dec 2019, 2:47 AM
Osman Shams
Osman Shams - avatar