For some reason I am getting a precision error when I try to compile my code. The precision error comes in the return of my second method where I am trying to calculate the circumference. What am I doing incorrectly?
public class Methods2
{
public static final double PI = 3.14;
public static double calcCirc(double x)
{
return PI*x;
}
public static int calcCirc(int x)
{
return (2*(double) x)*PI;
}
public static void main(String[]args)
{
System.out.println(calcCirc(10.2));
System.out.println(calcCirc(4));
}
}
You are attempting to return a double value in a method declared to return an int. Java won't let you implicitly narrow your value like that.
If you're okay with the loss of precision, then explicitly cast the value to int -- Java will let you do that.
return (int) ((2*(double) x)*PI);
However, I would change the method to return double instead, not to lose precision:
public static double calcCirc(int x)
... as you already did with your other calcCirc method.
Both versions of calcCirc() ought to return doubles.
Also, side note--consider using different method names since they accept inputs that differ not only in type but also in semantics.
E.g. calcCircFromRadius(double radius), calcCircFromDiameter(double diameter). There's not really a reason to take an int as an input type here since Java will automatically cast ints to doubles for you.
try
public static int calcCirc(int x){
return (int)((2*x)*PI);
}
Related
We already know that the return type of Math.lang() function in java is double.
class Lossy {
public static void main(String args[]) {
int sum;
sum=Math.pow(2,3);
System.out.println (sum);
}
}
Now this statement results in possible lossy conversion error because the variable is of type int and Math.pow() return a double value i.e. 8.0 which is fair enough.
Now look at the code below with some changes.
class Lossy {
public static void main(String args[]) {
int sum=2;
sum+=Math.pow(2,3);
System.out.println (sum);
}
}
Now if we compile this code we don't get an error of possible conversion error, which we should get because we are storing a double value in an integer variable. Moreover, when we are printing the value it shows an integer value. Why?
In the first code, you are assigning a double value to a integer variable. since double value needs 8 bytes whereas integer needs only 4 bytes of memory. We cant store a 8 bytes value into a 4 bytes variable. That's why it shows possible loss of conversion error.
class Lossy
{
public static void main(String args[])
{
int sum;
sum=Math.pow(2,3); //Assigning double value to a int variable. its an Error
System.out.println (sum);
}
}
In the second example you are not simply or directly assigning a value to a integer variable. but you used an add and assign operator(+=), which functions as follows:
sum+=Math.pow(2,3) is equal to sum = sum + Math.pow(2,3);
When you do like the above one, JVM performs Automatic Type Conversion(double to int) or Parsing for the function Math.pow() and it converts the return value of the function to int while compilation. So it works fine. I hope you understand. Thanks!
public class HelloWorld
{
public void m1(int i)
{
System.out.println("int-arg");
}
public void m1(byte j)
{
System.out.println("byte-arg");
}
public static void main(String []args)
{
HelloWorld n=new HelloWorld();
n.m1(12);
}
}
O/P: int-arg
Question: 12 is int type and byte type too. so in this case int is the exact match everytime. so what value should I provide if I want to call m1(byte) method?
Thanks.
You can either declare it with type or cast it
byte b = 12;
n.m1(b);
or cast
n.m1((byte)b);
As others have said, you will need to cast it.
In Java, plain numbers (ex: 12) are int by default, if the number has decimals (ex: 12.0), it will default to float double type (thank you #Sushil for the correction). There are suffixed to force some types, but not for all types (ex: 12L is long, 12.0f is float).
You'll need to cast prior to passing the value.
n.m1((byte)12);
This is my Java program code. I overloaded the add function for the data types int and float, but the call add(2.3, 2.4) throws an error, instead of calling add(float, float).
public class Main {
public static void main(String[] args) {
// This calls add(int, int) as expected
System.out.println(add(2,4));
// This call throws an error
System.out.println(add(2.3,3.4));
}
public static int add(int a, int b){
return (a + b);
}
public static float add(float a, float b){
return (a + b);
}
}
You defined the overloaded methods correctly!
What you got wrong is the way you call the methods. You are calling add(2.3,3.4). 2.3 and 3.4 are all doubles. That's why they can't be directly put into a method that accepts floats.
"What? Why are they doubles?" you might ask.
By default, all number literals without a . or e are considered to be ints. And all number literals that has either or both a . or e are considered to be doubles.
To create a float literal, add f to the end of the numbers. i.e. these are all floats:
1f
1000f
1.1f
-9f
1e99f
So you should call your method like this
add(2.3f,3.4f)
There are add methods for int and float, while literal 2.3 has type double. There two ways to fix this:
Use float literals, i.e. 2.3f and 3.4f (notice the f suffix).
Define add method for doubles.
Since int is less precise than double I thought I needed to cast it when parsing it into a method. Yet the following code runs fine. Why?
public class MyClass {
public static void main(String[] args) {
System.out.println(met(3/2));
}
static String met(int i){
return "This is what I get " + i;
}
}
When you do 3/2 that won't give you a double result. Integer division happens and result gets truncated to an integer. Hence there is no need of cast. In order to get double result, either needs to be cast to double so that get a compiler error to get it casted to double.
Try doing met(3d / 2), then you run into the compiler error which you are expecting.
I have written a java code for scientific calculator and also written jUnit test for it.Below is the method for calculating cubeRoot.
public <T> Double cubeRoot(T number){
Double result= Math.cbrt((Double)number);
return Math.abs(result);
}
Method returns proper result integer and double types,but when i invoke method for decimal,argument i pass is double type.Following are the JUint Test for above method.
public void testCalculateCubeRootWhenNegative(){
Integer number=-64;
assertEquals(-4.0,sci.cubeRoot(number));
}
public void testCalculateCubeRootOfdecimal(){
Double number=0.40;
assertEquals(0.736,sci.cubeRoot(number));
}
And this the interface i am using
public interface iScientific extends iMaths {
<T>Double squareRoot(T number);
<T>Double cubeRoot(T number);
Unable to find solution for getting error "java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double"
You are trying do to something like this:
Integer i = Integer.valueOf(0);
Double d = (Double) i;
This does not work because i is not an instance of Double.
I suggest to change your cubeRoot method to accept a Number (the base class of both Integer and Double):
public Double cubeRoot(Number number) {
Double result = Math.cbrt(number.doubleValue());
return Math.abs(result);
}
Again i have do some more code change to make the code error free as initially error persist.Check the correction i have made and do suggest for more refactoring of code.
public Double cubeRoot(Number number){
DecimalFormat df=new DecimalFormat("#.####");
double result= Math.cbrt(number.doubleValue());
return Double.valueOf(df.format(result));
}
And the following test passed.
public void testCalculateCubeRootWhenNegative(){
Integer number=-64;
assertEquals(-4.0,sci.cubeRoot(number));
}
public void testCalculateCubeRootOfdecimal(){
Double number=0.40;
assertEquals(0.7368,sci.cubeRoot(number));
}