SCJP Certification

Sun Certified Java Programmer Certification exam essentials

November 30th, 2009

What is a narrowing conversion?

Java Facts, by Daisy Williams.

A narrowing conversion is an explicit type conversion or casting. It is used when the destination data type is narrower than the source data type, an explicit type conversion is required. The general form of this explicit conversion is given below:

(target-type) value

Here, target-type is the desired data type and value is the value to be converted.

For example:

int num1, int num2;
short num3;
num3= (short)(num1+num2);

In the example above, the sum of two 32-bit integer data type variables num1 and num2 is assigned to another variable num3, which is of integer type short (16-bit). Therefore, an explicit conversion takes place before assigning the value to num3. Otherwise, if this explicit type conversion is not performed, and the sum of variables num1 and num2 is directly assigned to variable num3, a compile-time error will be generated.

Share

Back Top

Responses to “What is a narrowing conversion?”

Comments (0) Trackbacks (0) Leave a comment Trackback url
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

*