Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.
Related
I am new to java and I am working with arrays and for each loop.I am facing a problem with iterator initialization.
Code works fine when iterator variable initialization is done within for each block while code throws error when iterator initialization is done outside the loop
For example:
This code works:
class Array {
public static void main(String args[]) {
int[] array = {1,2,3,4,5,6,7,8,9,10};
for (int iterator : array) {
System.out.println(iterator);
}
}
}
This code does not work
class Array {
public static void main(String args[]) {
int[] array = {1,2,3,4,5,6,7,8,9,10};
int iterator;
for (iterator : array) {
System.out.println(iterator);
}
}
}
Someone please give me some insight about the topic and also if someone can explain about the memory mapping of for each loop it will be usefull. Thanks in advance
It's just how the enhanced for loop is defined. The variable that receives each value must be declared in the loop header.
The reason is that a separate variable is created for each loop iteration. In the linked spec section, see the example of what the enhanced for loop would look like if it were a simple for loop:
// Your enhanced `for` loop rendered as a normal `for` loop per the spec:
int[] array = {1,2,3,4,5,6,7,8,9,10};
{
int[] a = array;
for (int index = 0; index < a.length; index++) {
int iterator = a[index];
System.out.println(iterator);
}
}
Notice how iterator (not a great name for that variable) is recreated on each iteration. (It's conceptually similar for the other form of enhanced for dealing with an Iterable instead of an array.)
One advantage of it being a separate variable every time is that we can use final with it, which is useful particularly if we want to use its value in a lambda.
That also addresses your question about memory: As with any block, new stack space is allocated and used for the locals within the block. We have three levels of that in the above: The freestanding block wrapping the entire thing containing the notional a variable; the for statement itself containing index; and the body block containing iterator.
It's worth noting that the enhanced for could have been defined such that it let you optionally declare the value variable outside the loop, it just wasn't. It could have been defined such that if the variable were pre-declared, inside the loop iteration it would just do an assignment, not create a new variable and do an assignment. But it would have made it more complicated, and it already had the complication of needing to handle both arrays and Iterables. Apparently the cost of the complication wasn't considered worth the flexibility.
You are braking the syntax of enhanced loop. A compilable for each loop syntax is
EnhancedForStatement:
for ( {VariableModifier} **UnannType** VariableDeclaratorId : Expression ) Statement
https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2
Loop must know in it's type in it's own scope, since you breaking that, the error.
The following code sorts through a dictionary of words in lexicographical order. The problem is that I cannot access the sorted array outside of the for loop. Well I think this is the problem. I have declared the array words in another method and returned it to a private variable within the same class. But after I sort the array and try to print it out, it just prints out the original array. I also want to mention that this sorting method does work as I have tested it in another class where everything was in the main method. So again I believe my problem has to do with returning the new sorted array. I also need to write a few lines of code within the method after the array is sorted and when I tried to return the array, using "return words;" I was unable to write this code.
public void insertionSort() {
int in, out;
for (out=1; out<nElems; out++){
String temp = words[out]; // remove marked item
in = out; // start shifting at out
while (in>0 && words[in-1].compareTo(temp)>0){ // until temp is lexicographically after after the word it is being compared to
words[in] = words[in-1]; // shifts word to next position in lexicographical order
--in;
}
words[in] = temp;
}
for(int i=0; i <words.length; i++)
System.out.println(words[i]);
I have declared the array words in another method
It sounds like you have declared two arrays: one inside the other method and an entirely separate one at class level that is being sorted. Make sure both methods are using the same array.
If you want them both to use the array declared at class level, don't declare a separate array in the other method. E.g., if you have String[] words = new String[10]; in the other method, change it to words = new String[10];. If you really need the nElems variable (i.e., if the sort method can't simply use words.length), make sure that variable is also not being redeclared and is being set to the correct value.
Alternatively, instead of depending on putting the data to be sorted in a particular array, your sort method would be more generally useful if it accepted any array to be sorted as a parameter:
public static void insertionSort(String[] words, int nElems) {
/* ... rest of method as before ... */
}
I've made that method static too, since it no longer depends on any instance fields.
Well, as I understand what you are saying, you are using a private variable at class level and that variable receives the words[] array items from a method... in that case:
Make sure the private variable at class level is an array named words.
Make the private variable (now named words) the same type as the words array received from the other method.
Because you are calling words from insertionSort() you need to acces the private variable values, you can't get the words[] array values from the other method, because that array is local to that method, so you must return it's values to some array varibale (the private variable that you must name words), so it's that variable that you must access.
I'm doing an assignment for my intro to programming class and it's a bubble sort. The code may be flawed, but I'm not looking for someone to solve that problem. What my problem is, is that I'm trying to print it. I've been given the condition that the method had to be defined by a void method by the line "public static void sort(int[] array)". So, if I tried import Arrays, and used System.out.println(Arrays.toString(sort(array))); in my main method, it wouldn't work because I get a compiler error saying that void does not apply. If I tried to put it into a loop at the main method, it tells me that there are incompatible types. What is found is a void, what is required is an int[], but the original condition of the assignment is to use a void method. So, with that being said, should I change the method from void to int[] for testing purposes and submit the assignment as a void, or is there a way to print the output of this code with the void and I'm just missing it?
public static void sort(int[] array)
{
int[] y = new int[array.length];
for(int i = 0; i<=array.length-1; i++)
{
for(int j = i+1; i<=array.length-1; j++)
{
if(array[i] < array[j]){
y[i] = array[j];
}
if(array[i] >= array[j]){
y[i] = array[i];
}
}
for(int k = 0; k<y.length; k++){
System.out.println(y[k]);
}
}
} //end of sort method
The problem is that you create an new local array inside your sort method which you obviously cannot return because of the restriction of you assignment.
int[] y = new int[array.length];
Your method will not be valid, since the array passed will remain unchanged. You need to do the sorting in place, i.e. without creating a new array. So that if you pass it from your main method, it gets sorted and you can print it there.
Bubble sort should use a swap method, so you just need one temporary variable.
In order to print the array, in your main method you'll need
//code that initializes the array or whatever
sort(myArray);
System.out.println(Arrays.toString(myArray)); //print the array modified by the previous method call
Also note what #A4L said about your local array. Work with the array you pass as parameter to your method, don't create a new one.
Arrays.sort() modifies the array you pass in. So if you iterate over the array object and print the elements AFTER your call to Arrays.sort(), it will print for you.
Since you have a void sort method, you want it to sort the array as a side effect. That is, modify the values in the int[] array reference you passed as a method parameter. Then you can print it from main.
I've got a problem.
I'm trying to compare a String and a int but can't seem to get working.
What am I doing wrong?
Getting this from Eclipse:
The type of the expression must be an array type but it resolved to List
int numberOfMoves;
List<String> highscoreLinkedList = new LinkedList<String>();
if (moves < Integer.parseInt(highscoreLinkedList[2])){
highscoreLinkedList[2] = Integer.toString(moves);
highscoreLinkedList[1] = name;
}
This is for a highscore textfile for a game I'm making. The String at index 2 is a number of moves and the int moves is also a number of moves.
You cannot access a list element using highscoreLinkedList[2] - that syntax is reserved for arrays. To access a list you have to use the get() method, i.e. highscoreLinkedList.get(2)
You are trying to treat list as an array, but the only way to access elements of the is through calling get() method. Your code does not compile.
Lists don't work the same way as arrays in Java. To access a certain element, you have to use the get() method, and to get the element, you need to use set(), like so:
// you have highscoreLinkedList[2], it should be:
highscoreLinkedList.get(2);
// you have highscoreLinkedList[2] = ..., it should be:
highscoreLinkedList.set(2, Integer.toString(moves));
You can see all of the methods for LinkedList here.
This question already has answers here:
Changing array in method changes array outside [duplicate]
(2 answers)
Closed 3 years ago.
public class Test {
public static void main(String[] args) {
int[] arr = new int[5];
arr[0] = 1;
method(arr);
System.out.println(arr[0]);
}
private static void method(int[] array)
{
array[0] = 2;
}
}
After invoking method, arr[0] becomes 2. Why is that!?
You can call set methods on objects passed to a method. Java is pass by value, which means that you can't replace an object in a method, though you can call set methods on an object.
If Java were pass by reference, this would pass:
public class Test {
public static void main(String[] args) {
Test test = new Test();
int j = 0;
test.setToOne(j);
assert j == 1;
}
public void setToOne(int i) {
i = 1;
}
}
Java is Pass-by-Value, Dammit! http://javadude.com/articles/passbyvalue.htm
This is because Java uses Call by Object-Sharing* (for non-primitive types) when passing arguments to method.
When you pass an object -- including arrays -- you pass the object itself. A copy is not created.
If you mutate the object in one place, such as in the called method, you mutate the object everywhere! (Because an object is itself :-)
Here is the code above, annotated:
public static void main(String[] args)
{
int[] arr = new int[5]; // create an array object. let's call it JIM.
// arr evaluates to the object JIM, so sets JIM[0] = 1
arr[0] = 1;
System.out.println(arr[0]); // 1
method(arr); // fixed typo :-)
// arr still evalutes to JIM
// so this will print 2, as we "mutated" JIM in method called above
System.out.println(arr[0]); // 2
}
private static void method(int[] array)
{
// array evaluates to the object JIM, so sets JIM[0] = 2
// it is the same JIM object
array[0] = 2;
}
Happy coding.
*Primitive values always have call-by-value semantics -- that is, a copy is effectively created. Since all primitive values are immutable this does not create a conflict.
Also, as Brian Roach points out, the JVM only implements call-by-value internally: the call-by-object-sharing semantics discussed above are implemented by passing the value of the reference for a given object. As noted in the linked wikipedia article, the specific terms used to describe this behavior differ by programming community.
Additional:
Pass by value or Pass by reference in Java? -- see aioobes answer and how it relates with Brian Roachs comments. And aioobe again: Does array changes in method?
Make copy of array Java -- note this only creates a "shallow" copy.
Because that's exactly what you're telling it to do. Java passes first by value, then by reference. You're passing in the array, but any modifications you make to that array will be reflected on any other accesses to that array.
A quick example for thought:
If within method you did array = null, no change would be visible from main - as you would be changing the local value of array without modifying anything on the reference.
Because when you are passing argument like int/double/char etc. they are the primitive data types and they are call by value - meaning their values are copied to a local variable in this method (that has the same name as the names in your argument) and changes made to them are only changes made to these local var -> does not affect your primitive type variables outside the method
however an array or any object data type is called by reference -> the argument pass their address(reference) to method. that way, you still have a local variable named by them which has the reference. You can change it to reference another array or anything. but when it is referencing an array, you can use it to set the value of the array. what it does is accessing the address it is referencing and change the content of the referenced place
method(arr[0]);
I think that's supposed to be
method(arr);
But anyway the value passed as argument to the method is the reference to the array and the local variable arr in the method is referencing the same array. So, within the method you are making changes to the same array.
Java is pass by value. What confuses people is that the 'value' of a variable that refers to an object allocated on the heap is a reference, so when you pass that, you pass the reference 'by value' and therefore it refers to the same object on the heap. Which means it doesn't matter from where you modify the referent; you're modifying the same thing.