2(viii)
A student is trying to convert the string present in x to a numerical value, so that he can find the square root of the converted value. However the code has an error. Name the error (syntax / logical / runtime). Correct the code so that it compiles and runs correctly.
String x= "25"; int y=Double.parseDouble(x); double r=Math.sqrt(y); System.out.println(r);
Show SolutionHide Solution↓
Syntax error in the line:int y=Double.parseDouble(x);
Corrected code:
String x= "25"; double y=Double.parseDouble(x); //int changed to double double r=Math.sqrt(y); System.out.println(r);
Explanation:
The error is a syntax error because the method Double.parseDouble(x) returns a double, but the code is trying to assign it to an int variable without proper casting, which is not allowed in Java.