Menu
Topics Index
...
`

While loop


If you need explanation Read this topic

If you need Answer Take test on this topic

While loop
What will be the output of the following program?
public class Result {
    public static void main(String args[]) {
        int num = Integer.parseInt("10");
        double result = 0.0;
        while (num > 0) {
            result = result + 1 / num;
            num--;
        }
        String output = "" + result;
        System.out.println("Output = " + output.substring(0, 5));
    }
}

A. Output = 2.928
B. Output = 2.9289
C. Output = 2.92896
D. Some other output
E. Compilation Error or Runtime Error
Topic: Converting Numbers to and from Strings In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans:E  the values are added to the result in (int) the for loop like 0.0+0.0+......+1.0(lastvalue..because 1/1)=1.0 so answer is 1.0 it will give .but here we are accessing it using substring function 0 to 5 values..so the integer not support that much range so it will give output as...runtime error... so         anwer is :E...

Posted by Sapparapu Pradeep Kumar    2014-02-25 07:01:28


Integer division results in an integer. Here we always get 0 with (1 / num) except when num = 1, in which case, the result is 1. This is added to "result" (0.0) and we get 1.0. Then we are trying to obtain a sub string of "output" from 0 to 4. But, endIndex (i.e., 5) is larger than the length of output. So, we get a runtime error indicating that endIndex is outside the range.

Posted by Shaileshwar Sharma    2014-02-25 14:03:51


Congratulations Sapparapu Pradeep Kumar. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-02-26 04:43:29


© meritcampus 2019

All Rights Reserved.

Open In App