The following code shows an empty infinite loop and code written after the loop prints "Hello, World".
In this example, the println statement to print the statement synchronously and thus theoretically, after the infinite loop nothing should be printed, but still when on running the code, it prints "Hello, World".
So, why is the code written after an infinite loop executing?
public class Main{
public static void main(String[] args){
for(int i=0; i>=0; i++){}
System.out.println("Hello, World"); // This is printed on the console
}
}
I tried searching goole and stackoverflow for it, but could not find an answer for the problem.
Thank you.
When i becomes greater than max value(2147483648 - that can be represented in 32 bits), it overflows to its min value.
It runs exaclty Integer.MAX_VALUE times, because Integer.MAX_VALUE + 1 is Integer.MIN_VALUE, a negative number.
You can visualize your code like this :
class Main {
public static void main(String[] args) {
int i = 0;
for(i=0; i>=0; i++){}
System.out.println("Hello, World : "+ i);
}
}
This loop is not an infinite loop. It goes until the i reaches Integer.MAX_VALUE. Then i becomes Integer.MIN_VALUE which is a negative value. Run the code below and check the output.
int x = Integer.MAX_VALUE;
x++;
System.out.println(x);
If you want the loop to be infinite use,
for ( ; ; ){
}
Either the compiler smartened up and knew that nothing was done in that loop (which shouldn't matter, because even the for conditions can edit stuff)
or i looped 2 million something times and overflowed into negative numbers, making it less than 0.
Related
Hi can anyone help me with this?
First block of codes gives the output as intended.
But second one goes for infinite loop.
What is the reason?
Thank you.
1.
import java.util.Scanner;
class Numbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a starting number: ")
int start = scan.nextInt();
for(int a = start;a<=(start+10);a++)
{
System.out.println(a);
}
}
}
2.
import java.util.Scanner;
class Numbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a starting number: ")
for(int start = scan.nextInt();start<=(start+10);start++)
{
System.out.println(start);
}
}
}
In the first block, start is a constant variable which has fixed value and the condition is between a and start (a keeps increasing a++ and start won't change its value).
While in second block, the condition is between start and start+10, but start keeps increasing with start++ in the loop function, which makes the loop is infinite (start keeps changing its value so start<=(start+10) is always true).
This for(int start = scan.nextInt();start<=(start+10);start++) compares the changing variable to a changing value, which keeps the same distance ahead.
I.e. the value of start will always be lower than start+10, what you get is at first an endless loop. It can only terminate when values get so high that they cannot be represented anymore an strange things occur. At that point start+10 might appear to be lower than 0 for example and hence seem also lower than start which not yet is past that weird border.
In your second snippet of code
for(int start = scan.nextInt();start<=(start+10);start++)
{
System.out.println(start);
}
You're comparing start to itself plus 10. Regardless what operation you're going to perform, nothing can't be equals to itself plus 10. start will always be lower than itself plus 10 and therefore producing an infinite loop. It's a semantic error. You should use a different variable to keep track of the loop, as you did in your first snippet, and a second one for the confrontation (start in your case).
Doing a very simple program to test out recursion. The program prints something until the number is not greater than 0.
public class TestIt {
public static void print(int f){
while(f>0){
System.out.println("Not today");
f--;
print(f);
}
}
}
the code above is called from the main program like this.
public static void main(String[] args) {
TestIt.print(2);
}
Maybe I'm finally losing my mind, but the amount of times the program prints is exceeding what I expected. If I send 3 to the method then the program prints 7 times. Any ideas as to why?
Because you did wrong
while(f>0){
System.out.println("Not today");
f--;
print(f);
}
you are calling the method print f in the loop times
and as it is recursive it will be called f-1 times recursivelly
so it will b f fatorial times
remove the while loop and will work as you want
This is because everytime the call comes off the stack, f is still what it was originally, and then it continues with the while loop. So for 2:
while(f>0){
System.out.println("Not today");
f--;
print(f);
}
First run, subtracts from 2, results in one. (Print count = 1) Resursive call:
Subtracts again, 0, recursive call: (Print count 2)
While loop is never entered. returns:
0, while loop is not executed, reuturns:
While loop is run again, recursive call: (print count = 3)
Passes zero, while loop not entered, return
While loop terminated, exit method
For 2 it prints three times, but this grows for every number passed in. To fix this do:
if(f>0){
System.out.println("Not today");
f--;
print(f);
}
Remember recursion usually is to avoid loops, so if you find yourself using both, this is usually a red flag
I have a program like this:
public class OCAJP {
public static void main(String[] args) {
int i=0;
for(;i<2;i=i+5) {
if(i<5) {
continue;
}
System.out.print(i);
}
System.out.print(i);
}
}
This gives me an output to be 5 rather than giving me 05.
The continue statement used in if block must not be executing the if block but it shows its functionality to continue the for loop.
It doesn't print on the first round because of the continue statement since
i
is still less than 5.
Yes, the block inside the if must be executed because 0 < 5.
The increment is executed after the first loop, EVEN if the increment is a line before. Unfortunately it is confusing, sorry
You already said everything about how it works. continue statement is connected to for loop and you can use it to control the loop. It's meaning is "leave this iteration of loop, go back to loop definition and proceed with next iteration". Hence the first print, for i=0, doesn't execute.
I started learning Java and I can't solve this:
I want to code program which will be counting from 10 to 0 using "do while" and show numbers from 9 to 1.
I did this:
public class exWhile {
public static void main(String[] args) {
int a = 10;
do {
--a;
System.out.println(a);
} while (a==1);
}
}
Why this wont working?
The loop exits almost immediately after the first iteration since the exit condition has been met. Use
...
} while (a != 1);
Your loop is saying "while a equals 1" do stuff. Since a isn't initialized to 1, it's only going through the do-while loop once.
What you want to do is
while(a != 0)
or you can also do
while (a > 0)
to print 10 thru 0.
What your code is saying is to continue looping through prints while the value of a is one. You stay a at ten, so this is not true, and the loop exits.
You want to do something like this
While(a!=0){
System.out.println(a);
a--}
I'm new to this site and also very new to Java and I'm trying to understand the do while loops
Question: What is the output and why?
public class DoWhile {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("i is : " + i);
i++;
} while(i < 1);
}
}
I get that the output is "i is : 1" but I'm trying to understand why. It stops once it hits while because i isn't less that 1, right?
Just trying to get my head around it so any help will be appreciated.
Yes. Correct.
do { } while (condition);
This will perform the code at least once, regardless of the condition. After the first execution it will check the condition, which will evaluate to false (1 is not smaller than 1) and thus it will stop.
Yes, the output is 1 because in a do-while loop the statements within the do block are always executed at least once.
After the do block is executed the i value becomes 2 and the while block is not executed.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
Yes, the output is
i is : 1
The do-while loop will always execute at least once, because the condition isn't evaluated before the loop is entered; it's only evaluated at the end of each iteration. This is in contrast to the while loop, whose condition is checked before the first iteration as well as after each iteration.
i is 1 at the start, then print occurs, then i is incremented to 2. Then the condition is evaluated -- it's false, so the loop terminates.
The output is just 1 becuase the do causes the loop to execute at least once, but the condition in the while doesn't aloow the loop to reiterate, because i is never less than 1
It is no more 1
public class DoWhile {
public static void main(String[] args) {
int i = 1; // i is 1
do {
System.out.println("i is : " + i); //still i is 1
i++; // this makes i = 2;
} while(i < 1);
}
}
if you notice the comments it is no more 1 after the first iteration