Widening Primitive Conversion in Java
Last Updated :
18 Dec, 2021
Whenever we do use double quotes around a letter or string as we all know it is treated as a string but when we do use a single quote round letter alongside performing some computations then they are treated as integers values while printing for which we must have knowledge of ASCII table concept as in computer for every character being case sensitive there is a specific integer value assigned to it at the backend which pops out widening of primitive datatype conversion. Refer to this ASCII table and just peek out as you no longer need to remember the value corresponding to each just remember popular values as it is sequentially defined over some intervals such as “a”, “A” and so on.
Illustration:
Widening primitive conversion is applied to convert either or both operands as specified by the following rules. The result of adding Java chars, shorts, or bytes is an int datatype under the following conditions as listed:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int
Example 1:
Java
public class GFG {
public static void main(String[] args)
{
System.out.print( "Y"
+ "O" );
System.out.print( 'L' );
System.out.print( 'O' );
}
}
|
Output explanation:
This will now print “YOLO” instead of “YO7679”. It is because the widening primitive conversion happens only when an operator like ‘+’ is present which expects at least an integer on both sides. Now let us adhere forward proposing another case as follows:
Example 2:
Java
public class GFG {
public static void main(String[] args)
{
System.out.print( "Y"
+ "O" );
System.out.print( 'L' + 'O' );
}
}
|
Output explanation:
When we use double quotes, the text is treated as a string and “YO” is printed, but when we use single quotes, the characters ‘L’ and ‘O’ are converted to int. This is called widening primitive conversion. After conversion to integer, the numbers are added ( ‘L’ is 76 and ‘O’ is 79) and 155 is printed.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...