Does Java postfix increment operator (i++) create a new object [duplicate] - java

This question already has answers here:
Is ++x more efficient than x++ in Java?
(3 answers)
Closed 6 years ago.
I'm reading C++ 101 Rules Guidelines and Best Practices, and at item 28, they state that post increment operator should be avoided if we don't need the old value of the variable, as this operator creates a copy of it, hence a tiny performance loss.
I was wondering if Java did this operation the same way, in which case prefix operator should also be prefered for for-loop statements (the ones that might not be suited to a for-each or a lambda forEach() statement)
Java specs tell (§15.14.2):
The value of the postfix increment expression is the value of the variable
before
the new value is stored
So, is there some new object created at any time during the operation ? As we're returning something different than the variable that's been incremented.

Yes, there is. This method might explain it:
int iplusplus(int i){ //this is just an example. in real java, this would be a copy of i
int old = i; //this is the copy that might be unneeded
i = i+1; //this is the actual increment
return old;
}
old is the copied value. If you just want to increment i, ++i is shorter:
int plusplusi(int i){
return i+1;
}
As mentioned, this method is not the same, as the parameter i would be a copy and you would not change the variable's value in the calling code.

Related

Is Array declaration linear time operation or constant time operation? [duplicate]

This question already has answers here:
Java: what's the big-O time of declaring an array of size n?
(4 answers)
Closed 3 years ago.
boolean[] arr = new boolean[n];
What is the time complexity of above initialization? Is it O(1) ir O(n)? I think it is O(1) because the program simply asks JVM for a block of memory of size n. How does JVM(hotspot) actually allocate memory in this case?
I have looked up following links so far, however the answer is not clear to me:
Thread-1
Thread-2
I think that in general it is O(n), since the declared array need to be zeroes with default values, in your case with false.
But a VM can also prove that this array is not read immediately, that is someone first writes all the elements to it and only after that, reads them. In such a condition the complexity would be O(1), because you are not really doing anything (no default values are placed inside the array itself) - thus constant.
This, for example, is what happens in java-11 with Collection::toArray sort of, via :
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
So when you have something like:
List.of(1, 2, 3, 4)
.toArray(x -> new Integer[x]);
The implementation will actually do new Integer[0] and use that coupled with some System.arrayCopy, instead of the inferred new Integer[4]. This is done because the VM can prove that zeroing is not needed, thus skip it entirely.

What is the meaning of ":"? [duplicate]

This question already has answers here:
How does the Java 'for each' loop work?
(29 answers)
Closed 5 years ago.
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like
for(String x : model)
Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?
It means the loop will iterate through each object of the list
String x declares a String named x
model is the list of String you want to iterate through
: is the operator making the compiler doing this operation.
You can read the for like this : For each String in model, use x as variable and do the following operations.
you can then use x to do the operations you want on each elements of the list
In this context, : literally means in.
This is the syntax of the enhanced for loop. It marely means that you're iterating over all the elements in model, where in each iteration the String x is assigned with the current element so you can use in the loop's body.
Similar to mathematical notation that represents elements in a set.
Read left to right; For all string's x that are elements in model, do .

Why did the first for loop fail in Java? [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 7 years ago.
I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.
for(int num:a)
num=1;
But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~
for(int num=0;num<a.length;num++)
a[num]=1;
for(int n:a)
System.out.println(n);
Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.
These loops are different. Both in functionality and operations.
The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.
The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.
To put this in other terms:
The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.
The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.
Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.
Or...you could use Java 8's Stream API and come up with something like this:
IntStream.iterate(1, (x) -> 1).limit(100).toArray()

Does java cache array length calculation in loops [duplicate]

This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Closed 7 years ago.
Lets say that i have an array which i would like to iterate over:
int[] someArray = {1,2,3,4}
for (int i = 0; i < someArray.length; i++) {
// do stuff
}
Will this length of aray be caclulated with each iteration or it will be optimized to calculate it only once ?
Should i iterate arrays by calculating the length in advance and pass that to a loop ?
for (int i = 0, length = someArray.length; i < length ; i++) {
// do stuff
}
From JLS 7
10.7 Array Members
The members of an array type are all of the following:
• The public final field length, which contains the number of components of
the array. length may be positive or zero.
Coming back to your question,java doesn't recount the number of elements in array on array.length. It returns the value of public final int length, calculated during array creation.
As always for performance: write the simplest code you can, and test it to see whether it performs well enough.
If you only need the element (and not the index) I would encourage you to use the enhanced-for loop:
for (int value : array) {
...
}
As per JLS 14.14.2 that's basically equivalent to your first piece of code, but the code only talks about what you're actually interested in.
But if you do need the index, and assuming you don't change array anywhere, I believe the JIT compiler will optimize the native code to only fetch the length once. Obtaining the length is an O(1) operation, as it's basically just a field within the array, but obviously it does involve hitting memory, so it's better for the eventual code to only do this once... but that doesn't mean that your code has to do this. Note that I wouldn't expect the Java compiler (javac) to perform this optimization - I'd expect the JIT to.
In fact, I believe a good JIT will actually see code such as:
for (int i = 0; i < array.length; i++) {
int value = array[i];
...
}
and be able to optimize away the array bounds checks - it can recognize that if it accesses the same array object all the time, that can't possibly fail with an array bounds error, so it can avoid the check. It may be able to do the same thing for more "clever" code that fetches the length beforehand, but JIT optimizations often deliberately target very common code patterns (in order to get the biggest "bang for buck") and the above way of iterating over an array is very common.
As length is the member of Array So it is already been set when you create an Array , On Each iteration you are only accessing that property nothing else .
So either you access it like
int myArrayLength=arr.length;
for(int i=0;i<myArrayLength;i++)
or like :
for(int i=0;i<arr.length;i++)
There will be no measurable performance change .

What's the function of increments and decrements operators in any programming language?

I'm having a hard time understanding increments and decrements operators. In general, I see the "++ and --" post condition and preconditions in many variables inside or outside the loop. I know that it adds one or subtract one from the variable. But what's the purpose ?
like for intance.
int house =1;
/// block of code. Usually if statements, loops, other type of code you name it.
house++
For(int i =0; i<5;i++)
I thinking its like a way to control a block of items. Let me know
Thank you.
As you said, the increment operators increases a value by one, and the decrement operator decreases a value by one.
The postfix operator will return the variable's value and then change the variable.
int a = 5;
System.out.println(a++); // Outputs 5, before incrementing the variable.
System.out.println(a); // Outputs 6
The prefix operator will return the variable's new value after changing the variable.
int a = 5;
System.out.println(--a); // Outputs 4, after decrementing the variable.
System.out.println(a); // Outputs 4
This action of changing the variable before or after evaluation is the same for both the decrement and increment operators.
The way that this ordering of evaluation and mutation of the variable works is via the JVM's stack, and in which order values are pushed and variables are changed.
The purpose is exactly what you write: to increment or decrement an integer type (typically) variable.
It's common syntactic sugaring that provides a concise idiom that represents a commonplace task.
The idea of doing the same set of operations over and over again in a loop is very common in computer programming, and incrementing or decrementing counters, pointers or whatever is often useful in such a scenario.

Categories

Resources