Popular Google Pages:
◕ A platform for writers Details..
◕ Story writing competition. Details..
This article is regarding Explicit Casting for floating point type in Java.
Last updated on: 22nd March 2017.
◕ Explicit Casting for floating point type in Java.
- Let have an example statement first.
averageTemp = 2.5 + ( 15/2 );
If we run this, what will be the result?
The correct result is 10, but we will get the wrong result as 9.5.
This is because, the part 15/2 is an integer expression and will produces an integer result i.e. 7 not 7.5.
Hence the overall result will be 9.5.
averageTemp = 2.5 + double(15/2);
averageTemp = 2.5 + ( double )15/2;
If we run this, then we will get the correct result 10.
Because, here we converted the part 15/2 from integer to floating point by adding the word double.
- In the 1st solution we make the whole expression 15/2 as floating point.
- In the 2nd solution we make the int 15 as floating point.
As a result when the expression 15/2 executed it produces the result as floating point.
Converting this type of thing like the 1st solution and 2nd solution is called the Explicit Casting.
Please remember: It is not good to use Explicit Casting in a program. Hence try to avoid this.
Explicit Casting for integer
Related Java articles:
■ What is Java? Where we can apply Java?
■ Why Java is a Machine Independent Program? What is Machine Independent Program?
■ Root Directory of Java
■ How to Compile and run a Java Program?
■ What is .class file in Java?
■ What is variable in a program?
■ What is identifier in Java?
■ Integer data types in Java?
■ What is Primitive Types in Java?
■ How to declare constant variables in Java?
■ Why should we declare the initial value of a variable in Java?
■ Use of Underscores to write an integer in Java
Top of the page