In this post we will discuss about one of the basic java interview question and question is that Can We store a double value in a long type variable without casting?
We cannot store a double value into a long type variable without casting because the range of double is greater than long and that’s why we need to type cast. It’s not difficult to answer this question but many developers get it wrong due to confusion on which one is bigger between double and long in Java.
Let’s understand above concept using an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.kkjavatutorials.client; /** * @author KK JavaTutorials *Can We store a double value in a long type variable without casting? */ public class StoreDoubleInLongTest { public static void main(String[] args) { double d1 = 200.0; /*As range of double is more than long so Explicit casting is needed here else there will be compilation error*/ //long l1 = d1; long l2 =(long)d1; System.out.println(l2); } } |
Sample Output
200
You may also like:
Encapsulation in Java
Abstraction in Java
Understating of Polymorphism in Java
Method Overloading or Static Polymorphism in Java
Method Overriding or Dynamic Polymorphism in Java
Understating of Inheritance in Java
Difference Between Encapsulation and Abstraction in Java
Association Aggregation And Composition in Java
That’s all about Can We store a double value in a long type variable without casting?
If you have any feedback or suggestion please feel free to drop in blow comment box.