Why are these printing different outputs? - java

I just want to understand the difference between for(int i =1;i<4;i++)
and for(int i =1;i++<4;)
The first one prints 123
The second one prints 234
for(int i =1;i<4;i++)
System.out.print(i);
for (int i =1;i++<4;)
System.out.print(i);
I do not understand why are the results different, I expect 123 from both of them.

This loop:
for (int i =1;i++<4;)
increments i before System.out.print(i), which means the first printed value of i will be 2.

In the standard for loop, i is incremented after the loop iteration. From the Java Tutorials:
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
In the second example, it is incremented in the expression where it is evaluated, but because the post increment operator is used, the value evaluated is the old value. This means that by the time it is printed, it has already been incremented.

To explain I've refactored the statements only by using curly braces...
for(int i =1;i<4;i++) {
System.out.print(i);
}
System.out.println();
for (int i =1;i++<4;) {
System.out.print(i);
}
System.out.println();
Inside the first 'for' statement - the third clause with "i++" doesn't happen until the contents of the loop is executed.
Next consider the second 'for' statement, the comparison clause (the 2nd clause). that will be completely evaluated before the contents of the loop is started. So going into the first iteration, "i++" gets evaluated as "1" for the purpose of the comparison, but immediately gets incremented after the boolean clause is evaluated.
So when it hits the print statement it's already equal to 2. (and so on)
I hope that helps!

Related

Why the following program printing "Hello" three time and not two?

I am learning java nowadays, and while going through loops in java, I am stuck here, I am unable to understand why the following program is printing "Hello" three times. can you please explain?
public class Helloworld {
public static void main(String[] args) {
for (int i =1; i<=2; i++ ) {
for (int j =1; j<=i ; j++) {
System.out.println("Hello");
}
}
}
}
for loop iterations:
i=1
j=1 — prints "Hello"
j=2 — breaks out of inner loop, `j <= i` is false.
i=2
j=1 — prints "Hello"
j=2 — prints "Hello"
j=3 — breaks out of inner loop, `j <= i` is false.
This is what happens when the above code is run.
To understand why, change
System.out.println("Hello");
to
System.out.println("Hello: i = " + i + ", j = " + j);
compile and run it again, and look carefully at the values of i and j printed out.
Basically, in the second iteration of the outer loop, the inner loop runs twice.
If you cannot compile and run the program, there is another way to understand the behavior. Hand execute it.
Get a pencil an piece of paper, draw a table with a column for each variable. Each time a variable is assigned to / modified (e.g. i = 0 or i++) add a new row to the table with the current values of all of the variables. When you have a test (e.g. i<=2) read the variable's value from the latest row in the table.
After some practice you will be able to do this in your head. After more practice you will be able to read the code (like you read English text, or mathematical notation) and reason about what the code does.
Or use a debugger :-)
Sometimes when learning loops, writing small loops on paper can help.
Here you habe a nested loop using variables i and j.
First, the inner loop, j=1, and 1 is less than or equal to 1(i), so it prints. Then j++.
j is now 2, which is not less than or equal to 1, ending inner loop cycle. Now back to outer loop, i++,
i is now 2.
Inside the inner loop- j=1, less than or equal to 2, so second print. Now j++. Condition still true, as j(as 2) is still less than or equal to 2, so third print.
Hope this debugging method helps you.
You have two loops. The outer i loop runs twice, but inner j loop depends on the value of i with the j<=i part. So for the first i loop, j runs once, and the second i loop j runs twice, so three times all up.
This has to do with the nested looping. There's (2) loops to pay attention to here. For each iteration of the outer loop (i), the inner loop (j) may run multiple times. If you change the output to output the iterators, it will give you some visibility into this property.
System.out.println("i:"+i+" j:"+j);
OUTPUT: $javac HelloWorld.java
i: 1 j:1
i: 2 j:1
i: 2 j:2
If you want to get a more detailed view on nested looping, here's a good video series I'd recommend: Nested Looping (The Coding Train)
Hope this helps!

Is there a better way to access the last element in a for loop in Java

[edited the post to be more clear]
The code below is supposed to represent a number of trial runs, and within each trial assume a is the number of cases that need to be checked.
while(testCaseAmt > 0) {
for(int i = 0; i < a; i++) {
if(some condition)
//code when i is not the last element
//then I would like to break/return here.
if(i = a - 1)
//code when i is the last element
//then if the above if statement never runs during the a amt of trials
//i will print out something else
}
testCaseAmt--;
}
My question is if there is another way to access specifically the last element within a for loop to give it specific instructions. I want to loop through a set trials and if they meet the first condition, I stop the loop immediately and return. However, if the condition isn't found I still need to print out not found.
Cheers.
To me this seems related to "off-by-one errors" or "fencepost errors", see here.
If the code you're executing when i is not the last element isn't too complex, it could be better to just end the for loop one iteration earlier and write the specific code for the last element outside the for loop.
Adding an if statement inside a for loop where you know it will only be true at the very last iteration could be seen as bad-style.
You can define a boolean conditionMet = false before the for-loop and iterate until i < a-1.
If some condition applies, execute your code, then set conditionMet = true and break out of the for-loop.
After the for-loop, check if !conditionMet and in this case, execute the code for the last element.

Variable assignment inside for loop [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
This is a very simple for loop:
for(int i=0;i<=100;i++)
{
System.out.println(i);
}
I know how it mostly works, but I don't understand how the i++ works at the end: its supposed to add 1, if I'm correct, but when it prints out the i, it prints out 0 and then 1.
Why doesn't it just start out with 1 because of the i++? Why does it still just print out the original value instead of the i++ value?
A for loop works as follows:
Initialization is done (int i=0 in your case; only executed once)
Condition is checked (i<=100 here), if condition is false leave the loop
Code within the braces is executed (System.out.println(i); in your case)
Update statement is executed (i++)
Goto 2.
It's similar to this while loop :
{
int i = 0;
while (i <= 100) {
System.out.println(i);
i++;
}
}
i is incremented only at the end of each iteration.
Because the increment is evaluated after the first execution of the loop body. This is by design, and remember that programmers generally treat 0 as the first number. For example, with arrays and String(s) the first element is 0.
The Java Tutorial on The for Statement says,
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Here it is how it works
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.
There are three parts to the for loop header:
for (initialization; condition; increment / decrement) {
//statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it's true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.
Credits : For
If you use ++ operator as prefix like: ++var; then, the value of operand is increased by 1 then, only it is returned but, if you use ++ as postfix like: var++; then, the value of operand is returned first then, only it is increased by 1.
For example,
class Example
{
public static void main(String[] args)
{
int var = 1;
System.out.println(var++);
System.out.println("\n" + ++var);
}
}
the following program prints
1
3
In the prefix form, the increment or decrement takes place before the value is used in expression evaluation, so the value of the expression is different from the value of the operand. In the postfix form, the increment or decrement takes place after the value is used in expression evaluation, so the value of the expression is the same as the value of the operand.
Think of the i++ as the statement that says "Use then increment"
The value of i will first be used in the loop and then incremented by 1.
So the loop is executed once, then the declaration and incremental statements checked.

for loop with only terminating expression vs while loop

Whilst browsing the Apache ActiveMQ source code, i came across a funny looking for loop..
for (;beforeEndIndex < size;) {
synchronizations.get(beforeEndIndex++).beforeEnd();
}
Whats the benifit of this over using a standard while loop?
E.G.
while(beforeEndIndex < size){
beforeEndIndex++;
}
Both do exactly the same thing.
The major difference between a for loop and a while loop is that the for loop limits the scope of the iteration counter to within the for block where as a while loop requires you to declare the iteration counter at least one block higher. In this case, as the for loop declares no iteration counter variable, there is no difference.

Can a termination variable in a condition of for loop be changed inside the loop?(Java)

in Java, when using a for loop, you need to write a termination condition of course. This is my for loop:
for(int i=1; i<=infix.length()-2; i++){
if(infix.charAt(i)==' '){
infix=infix.substring(0,i)+infix.substring(i+1);
}
(infix is a string i got as a parameter). As you can see, I'm using substring inside the loop, which shortens the length of infix, which means that the termination condition of the loop is changed after every single iteration.
My question is this: Is the value "infix.length-2" saved at the beginning of the for and doesn't change later on? Or it changes every time, and if so, what happens with i? When will the for stop? Is there a chance for an index out of bounds or something like that?
Thank you very much in advance! :D
The string length gets calculated every loop, and your for could throw an IndexOutOfBoundsException if your string becomes too short.
IMHO yours is a very bad practice, for loops are intended to make a determined number of loops and should never be stopped, also their stop condition should never be changed inside the loop, you should use a while if you don't know how many iterations you want to do. But this is my personal opinion :)
Yes, you can change the upper limit. No, it's not cached at the beginning of the loop. Yes, anything you do wrong might cause errors -- but this is neither especially dangerous or uncommon. On the contrary, it's quite common.
you can put multiple end criteria in a for loop, just for a sample syntax
for(int i = 0; i < 2 || i< 5; i++)
System.out.println(i);
As a short hint: Your for-loop is equivalent to the following while-loop
{
int i=1;
while(i<=infix.length()-2) {
if(infix.charAt(i)==' '){
infix=infix.substring(0,i)+infix.substring(i+1);
}
i++
}
}
That means the condition of a the for-loop is evaluated in the same way as the condition of a while-loop. There is nothing special about it.
My question is this: Is the value "infix.length-2" saved at the beginning of the for and doesn't change later on? Or it changes every time, and if so, what happens with i?
It changes with every iteration of the for loop. i gets incremented, with each iteration.
When will the for stop? Is there a chance for an index out of bounds or something like that?
The for loop will stop when the termination condition is true.
i<=infix.length()-2.
i initialized to 1 will result in a loop that terminates if the length
If you modify the termination condition variables with incorrect logic, then you have a chance of running into an infinite loop.

Categories

Resources