Home   |   About   |   Terms   |   Contact    
Read & Learn
 

What is Casting and Explicit Cast in Java?

Java

☯ All Java Articles     ☯ All Articles


A new product.






Popular Google Pages:




This article is regarding What is Casting and Explicit Cast in Java?
Last updated on: .



◕ What is Casting and Explicit Cast in Java?

Let have an example of a complete program first:

public class balls{
public static void main(String[] args){
int numBalls=0;
int redBalls=3;
int blueBalls=2;
numBalls = redBalls+blueBalls;
System.out.println("Total number of balls is: "+ numBalls); // This displays the result on screen.
}
}


If we run this program then we will get the result as:
Total number of balls is: 5



Now we will change the variable type from int to short on the above program.
The program will look like this:

public class balls{
public static void main(String[] args){
small numBalls=0;
small redBalls=3;
small blueBalls=2;
numBalls = redBalls+blueBalls;
System.out.println("Total number of balls is: "+ numBalls);
}
}


If we want to run this program we will find that the program is not running.
Here everything is OK. But why the program is not running?

The answer is, the compiler is unable to compile the statement:
numBalls = redBalls+blueBalls;

The reason is:
We have declare the type of variable as short which is 16 bit long.
But in Java all binary integer operations work only with type int or with type long.
Type int is 32 bit long.
Type long is minimum 64 bit long.
Hence the expression
redBalls + blueBalls produces a 32-bit result.
And the compiler is unable to store the 32 bit result to the numBalls as it is only 16 bits long.
As a result the program is not running.


Solution:
To make the program OK we have to change only one line as:
numBalls = (short)(redBalls + blueBalls);

Please note:
We should always avoid explicit casting in our programs unless they are absolutely essential.



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





Popular Google Pages:





Top of the page

Amazon & Flipkart Special Products

   


Top of the page