This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 6 years ago.
From what I understand, if I have a variable k = 5, and I do ++k, the new value of k = 6. If I do k++, the value remains 5 until k appears the second time in the program, which is when it is changed to 6. For e.g:
k = 5;
System.out.println(k++); //prints 5, but now that k has appeared the second time, its value is incremented to 6
System.out.println(k); //prints 6
However, in this code:
class test {
public static void main(String args[]){
for(int i =0; i<10; i++){
System.out.println(i);
}
int x = 0;
x++;
System.out.println(x);
}
}
Output:
0
1
2
3
4
5
6
7
8
9
1
In the loop, though the variable i appears for the 2nd time(in System.out.println(i)), its value remains at 0. But for x, when it appears for the second time( in System.out.println(x); ) its value is incremented.
Why? I'm confused about how post and pre-increment work.
For your code
for(int i =0; i<10; i++){
System.out.println(i);
}
firstly the variable i is initialized to 0, it then checks if it satisfies the condition i < 10 and print the variable and lastly increments the variable i.
This is how the for loop works.
In the second piece of code you have written, it increments the variable x and lastly prints the value of x.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have been trying to fill my
int[][][] sudoku = new int[5][9][9];
array with
String[][] tmp = new String[21][21];
tmp[][] holds numbers like
005700020009600020
490060010140050030
For example this code works perfect and it gives me the number I want
System.out.println(Integer.valueOf(tmp[4][10]));
But this code
//sudoku1
b=0; c=0;
for (int i = 0; i < 6; i++) {
for (int j = 9; j < 18; j++) {
sudoku[1][b][c] = Integer.valueOf(tmp[i][j]);
c++;
}
b++;
}
throws "Index 9 out of bounds for length 9" error
You have c defined outside both loops, and added 1 each execution in the inner loop. The inner loop gets executed 6*9 times, so c can reach even the value 54, but it throws exception when it reaches 9 when trying to use sudoku[1][b][c], as the array indexes for the third element of the multiarray sudoku go from 0 to 8.
This question already has answers here:
Java for loop won't run...?
(4 answers)
Closed 1 year ago.
Why doesn't double equal work in Java?
int end = 10;
int start =0;
for(int i=start;i==end;i++) {
System.out.println(i);
Whereas the following works?
int end = 10;
int start =0;
for(int i=start;i<=end;i++) {
System.out.println(i);
The loop with the equal-operator will never be entered, because i==end (i.e. 0==10) is false on the first iteration of the loop, whereas i<=end (i.e. 0<=10) is not.
The for loop:
for(i=start; i<=end; ++i) {
}
is equivalent to:
i=start;
while(i<=end) {
++i;
}
I think you might be misunderstood on how a for loop works. Then syntax of a for loop is
for(A;B;C)
where B is a boolean.
The loop will continue to work until B is false.
if you have i == end, then it does not execute because i is not equal to end in the first place
when you have i <= end which works until i is greater than end.
How is the following for loop different from original?
Why after initialization, it checks for the condition?
Why such behavior and what are other such tricky behaviors of for loop?
class FooBar
{
static public void main(String... args)
{
for (int x = 1; ++x < 10;)
{
System.out.println(x); // it starts printing from 2
}
}
}
Output:
2
3
4
5
6
7
8
9
++x increments the value of x. As a result, two things are happening:
The value being checked for the for-loop condition (i.e., the inequality), is already incremented, and
This incremented value is what gets printed within the loop.
If you want values from 1 to 9, use the standard loop:
for (int x = 1; x < 10; ++x) { ... }
The effects of prefix and postfix operators has been discussed and explained in detail elsewhere, this post, for example.
The increment of x is combined with the condition. Normally, the increment is performed in the third section of the for loop, which is a statement executed at the end of an iteration.
However, the condition is checked at the beginning of the loop. It's an expression, not a statement, but as you can see, that doesn't stop someone from inserting a side-effect -- the pre-increment of x.
Because x starts out as 1, the condition increments it to 2 before the first iteration.
This is not for-loop trickery, it's the way the prefix and postfix operator works that you're using on x.
++x - Increment x then evaluate its value
x++ - Evaluate the value of x and then increment it.
So, the loop with this definition:
for (int x = 1; ++x < 10;)
executes like this:
Initialize x to 1
Increment x by 1
Evaluate if x < 10. If yes, iterate loop. If no, end loop.
What you want is this:
for (int x = 1; x < 10; x++)
Initialize x to 1
Evaluate if x < 10. If yes, iterate loop. If no, end loop.
Increment x by 1
Each for-loop (except enhanced for loop) has the following structure -
for(initialization; conditionChecking; increment/decrement){
//body
}
Your for-loop also has this structure with the incremetn/decrement portion empty. But to continue the for loop you have to change index (here x) of for-loop. If it is done some how then you can leave the increment/decrement portion empty. If you write the for-loop like this then it also fine -
for(int x=0; x<10; ){
//do something
x++;
}
You also may leave one/more portion (even the body) of a for-loop empty, like this -
int x=0;
for(;x<10;x++); //empty body; do nothing; just increment x
A for loop is valid with one or more of it's some portion leaving empty.
In the your code the increment portion is empty. You have done your increment of index x by using ++x>10. So it is valid. There is no difference from the regular for loop, it's just a way of representing the for loop in different way.
The Original way of a for loop you may have in you mind:
for(initialization; condition; inc/dec/divide..)
And what you mentioned: for (initialization; Inc & check; nothing)
What does it mean? : for(some blaBla; any Bla; some, more, bla)
You may have any expression any where. The Original version is just a convention we follow. Go ahead an write a printing statement or a bitwise operator instead of some blaBla try it out!
Update:
Why :
for (int x = 1; x++ < 10;)
{
System.out.println(x);
}
Prints 2..10? For the answer first try to execute :
for (int x = 1; ++x < 10;)
{
System.out.println(x);
}
It prints from 2..9
You should understand how pre/post fix operators work. x++ in the loop increments the value but not immediately. It increments after x++ < 10;
Where as ++x < 10; first increments and then rest everything happens.
So, when the x value is 9, 9(++)< 10 -> 9 is less ? yeah, now 9++ occurs.It then increments x. but ++x increments 1st so ++9< 10 -> 10<10 NO.
You can write your code as:
x = 1;
while (++x < 10)
{
System.out.println(x);
}
You expect the following:
x = 1;
do
{
System.out.println(x);
}
while (++x < 10);
This is the difference.
The following does what you expect:
for (int x = 1; x < 10; x++)
{
System.out.println(x);
}
TL;DR of it all is that ++x is a pre increment operator. When you use ++x, x will be incremented before any other allied operation. That is why your code prints out 2 first instead of 1 and stops when ++x becomes 10
This question already has answers here:
post increment operator java
(3 answers)
Closed 8 years ago.
what would be the output of
1).
int j=0;
for (int i=0; i<100; i++) j=j++;
System.out.println(j);
I thought j=j++; will be equal to
int j2 = j;
j = j+1;
so I was expecting the out put would be 99. but when I compiled on eclipse output was 0.
2). and I could not understand what is the logic behind
((int)(char)(byte) -1)
When ran it on eclipse I got output as 65535.
j=j++;
is functionally equal to
int xxx = j;
j++;
j = xxx;
So the value of j stays the same. (Because the right side is evaluated first, including the increment, then the result is assigned to j)
As for ((int)(char)(byte) -1), a char is 16bit in size and unsigned, so the bit pattern of -1 results in 65535.
This is because the ++ works as follows:
a = 0;
a = a++; // a will get the assignment of the current value of a before the increment occurs so a = 0 in here
However, in the next case here:
a = 0;
a = ++a; // a will get the assignment of the incremented value of a so a = 1 in here
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Java is NEVER pass-by-reference, right?...right? [duplicate]
(6 answers)
Closed 8 years ago.
I have the following code:
public class Book {
private static int sample1(int i) {
return i++;
}
private static int sample2(int j) {
return ++j;
}
public static void main(String[] arguments){
int i = 0;
int j = 0;
System.out.println(sample1(i++)); //0
System.out.println(sample1(++i)); //1
System.out.println(sample2(j++));//1
System.out.println(sample2(++j));//2
System.out.println(i);//2
System.out.println(j);//2
}
}
My expected output is in comments. The actual output is below:
0
2
1
3
2
2
I'm getting confused with the function calls and incemental operator. Can someone kindly explain the actual result?
Since sample1 and sample2 are just modifying their own local variables i and j (not those of the calling method), it's clearer if we rewrite them without those modifications:
private static int sample1(int i) {
return i; // was 'i++', which evaluates to the old i
}
private static int sample2(int j) {
return j + 1; // was '++j', which evaluates to j after incrementing
}
At which point it's straightforward to just substitute them in place — sample1(...) becomes ..., and sample2(...) becomes ... + 1:
int i = 0;
int j = 0;
System.out.println(i++);
System.out.println(++i);
System.out.println((j++) + 1);
System.out.println((++j) + 1);
System.out.println(i);
System.out.println(j);
We can make this a bit clearer by separating the incrementations into their own commands. i++ evaluates to the original value of i, so it's like incrementing i after running the surrounding command; ++i, by contrast, is like incrementing i before running the surrounding command. So we get:
int i = 0;
int j = 0;
System.out.println(i);
i++;
++i;
System.out.println(i);
System.out.println(j + 1);
j++;
++j;
System.out.println(j + 1);
System.out.println(i);
System.out.println(j);
. . . at which point it should be straightforward to trace through and see what it will output.
Does that all make sense?
First of all you need to know the difference between x++ and ++X;
In case of x++ :
First the current value will be used and it will be incremented next.
That means you will get the present value of x for the operation and if you
use x next time will get the incremented value;
In case of ++x :
First the current value will be incremented and it will be used (the incremented value) next, that means you will get the incremented value
at this operation and for other after this operation.
Now lets split the code and discuss them separately
method: sample1() :
private static int sample1(int i) {
return i++;
}
This method will take a int and return it first and then try to increment but as after returning the variable i will go out of scope so it will never be
incremented at all. exp in: 10-> out 10
method: sample2() :
private static int sample2(int j) {
return ++j;
}
This method will take a int and increment it first and then return it. exp in: 10-> out 11
In both case only the variables will change locally, that means if you call from main method the variables of main method will remain unaffected by the change
(as the sample1() and sample2() are making copy of the variables)
Now for the code of the main method
System.out.println(sample1(i++)); // it's giving sample1() `i=0` then making `i=1`
// so sample1() will return 0 too;
System.out.println(sample1(++i)); // it's making `i=2` and then giving sample1() `i=2`
// so sample1() will return 2;
System.out.println(sample2(j++)); // it's giving sample2() `j=0` then making `j=1`
// so sample2() will return 1;
System.out.println(sample2(++j)); // it's making `j=2` giving sample2() `j=2` then
// so sample2() will return 3;
You're experiencing the fun of prefix and postfix operators.
The prefix operator, ++i increments the variable i by one before using it in the expression, where the postfix operator (i++) uses i in the expression before incrementing it.
This means that your method sample1 doesn't do anything; it evaluates the expression containing i, but because that expression is a return statement, the local variable i goes out of scope, and we can't modify it anymore.
sample2, by contrast, increments the local copy of j before returning it, which is why you print higher values of j than you expect.
Easy:
1) First call:
a) Provide i (==0) to sample1(), which returns 0 (then increments the argument i, and that gets discarded).
b) increments i because of i++. i is now 1.
c) Prints the function result: 0.
2) Second call:
a) Increments i because of ++i. i is now 2.
b) Provide i (==2) to sample1(), which returns 2 (then increments the argument i, and that gets discarded)
c) Prints the function result: 2.
3) Third call:
a) Provide j (==0) to sample2(), which increments the argument, and therefore returns 1.
b) increments j because of j++. j is now 1.
c) Prints the function result: 1.
4) Fourth call:
a) Increments j because of ++j. j is now 2.
b) Provide j (==2) to sample2(), which increments the argument, and therefore returns 3.
c) Prints the function result: 3.
5 & 6) Fifth and Sixth call:
a) Prints the value of j: 2.
The key to remember here is that i++ increments the variable after passing it as an argument, whereas ++i increments the variable before passing it as an argument.
Hope this helps
1st print
before call: i = 0
increment after call
sample1 is called with a value of 0
sample 1 returns 0, the increment is discarded
after call: i = 1
2nd print
before call: i = 1
increment before call
sample1 is called with a value of 2
sample1 returns 2, the increment is discarded
after call: i = 2
3rd print
before call: j = 0
increment after call
sample2 is called with a value of 0
sample2 the increments 0 to 1, returns it
1 is printed
increment j to 1
after call: j = 1
4th print
before call: j = 1
increment before call
increment j to 2
sample2 is called with a value of 2
sample2 the increments 2 to 3, returns it
3 is printed
after call: j = 2
5th print
prints i
2 is printed
6th print
prints j
2 is printed
Both of them increase the variable i by one like i = i + 1;
The difference is that :
++i increments the value first and then return it
i++ return the value first and then increments it
This behavior difference doesn’t matter in a for loop.
If you want to know the difference try this :
int x = 0;
int y = x++;
int x = 0;
int y = ++x;
Here x++ returns the value then increments it but ++x first increments the value then returns that value
Form your example,
private static int sample1(int i) {
return i++;
}
private static int sample2(int j) {
return ++j;
}
public static void main(String[] arguments)
{
int i = 0;
int j = 0;
System.out.println(sample1(i++)); //0
System.out.println(sample1(++i)); //1
System.out.println(sample2(j++));//1
System.out.println(sample2(++j));//2
System.out.println(j);//2
System.out.println(j);//2
}
i = 0; sample1(i++) -> it pass '0'->in sample1 return i++ so, 0(++)
Here it returns 0 but incremented to 1 , so println is = 0 but finally i takes 1
i = 1; sample1(++i) -> it pass '2'-> in sample1 return i++ so, 2(++)
Here it returns 2, so println is = 2
j = 0; sample2(j++) -> it pass '0'-> in sample2 return ++j so, (++)0
Here it returns 1, so println is = 1.
j = 1; sample2(++j) -> it pass ++1 => 2, in sample2 return ++j so, (++)2
Here it returns 3, so println is = 3. But increment is ended with in sample2, not in
main so j still holds 2.
j = 2
j = 2