Rakesh
Rakesh

Reputation: 31

Java problem-Whats the reason behind and what will be probable output

1.)

long milli=24*60*60*1000;
long micro=24*60*60*1000*1000;
long result=micro/milli;

The result should be 1000 but it's not.

Please can you tell me the output and explain it?

2)

int i=0;
for(a=0;a<=integer.MAX_VAL;a++)
{
    i++;
}

S.O.P(i);

Normally it went to infine loop why because there is max value it should come out of loop. At what conditions it will executed sucessfully and what will be excepted value. .....Anyone can tell me about VM... handing of nummbers in JAVA

Upvotes: 0

Views: 404

Answers (3)

GuruKulki
GuruKulki

Reputation: 26418

2)

public class test {
    public static void main(String[] ar){
        int i=0;
        for(int a=0; a< Integer.MAX_VALUE;a++) {
            i++;
        }
        System.out.println(i);
    }
}

output:

2147483647

Upvotes: 2

Johan Sj&#246;berg
Johan Sj&#246;berg

Reputation: 49177

You need to put an L in there for long-conversion

long micro=24*60*60*1000*1000L

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533432

This feels jeopardy, having to guess the question as well as the answer. ;)

I think the second question should read

int i=0;
for(a=0;a<=Integer.MAX_VALUE;a++)
    i++

This will go into an infinite loop because all possible values of a are <= MAX_VALUE.

You can re-write this loop as

int a=0;
do {
    i++
} while (a++ != Integer.MAX_VALUE);

i will be Integer.MIN_VALUE as it overflows.

Upvotes: 1

Related Questions