Here is a small code snippet given. Try to Guess the output
At first glance, we expect “YOLO” to be printed.
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.
Now try to guess the output of following:
Explanation: This will now print “YOLO” instead of “YO7679”. It is because the widening primitive conversion happens only when a operator like ‘+’ is present which expects at least integer on both side.
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:
- 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
This article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Method Overloading with Autoboxing and Widening in Java
- Primitive Wrapper Classes are Immutable in Java
- Is an array a primitive type or an object in Java?
- Comparison of double and float primitive types in Java
- Program to convert Primitive Array to Stream in Java
- How to get slice of a Primitive Array in Java
- Primitive data type vs. Object data type in Java with Examples
- Using Above Below Primitive to Test Whether Two Lines Intersect in Java
- Image Processing in Java | Set 3 (Colored image to greyscale image conversion)
- Image Processing in Java | Set 4 (Colored image to Negative image conversion)
- Image Processing in Java | Set 5 (Colored to Red Green Blue Image Conversion)
- Image Processing in Java | Set 6 (Colored image to Sepia image conversion)
- Conversion of Array To ArrayList in Java
- Type conversion in Java with Examples
- Data Conversion Using valueOf() method in Java
- Conversion of Java Maps to List
- Array to ArrayList Conversion in Java
- Base conversion in Java
- ArrayList to Array Conversion in Java : toArray() Methods
- Java.util.BitSet class methods in Java with Examples | Set 2
Improved By : harshgundecha