David P. Reinig’s Post

I had this post on my wall today and actually, while really basic, this topic is weirdly interesting. The post mentioned that "a+b is promoted to int" which is not exactly what happens. Actually the operants are converted to "int" before the operation is performed. This is actually the same (and in fact specified) for several languages like Java, C#, C, C++ and for multiple reasons - which are partially decisions made around historic constraints. Newer languages like Rust, Go, Zig, Kotlin, ... don't mirror this and keep the type as specified in the parameters. Back to the example: Java (and also C#) won't do the implicit narrowing to "byte" for strictness and safety reasons, thus the compiler will complain. In C or C++ the implicit narrowing cast is actually done, so the first example compiles just fine "uint8_t c = a + b;". But handling this strictly raises a problem for C# and Java with compount operators. Here the parameters still are promoted to "int" but the specification explicitely states that the behaviour is identical to "E1 = (T)((E1) op (E2))", so a cast is performed. Pretty much solely to support compount operators as syntactic sugar. #Java #CSharp #CPlusPlus #Codingtrivia

#Java #ProgrammingTips #JavaDevelopment #SoftwareEngineering #ByteShortInt #JavaTricks 𝗝𝗮𝘃𝗮 𝗧𝗶𝗽 : 𝗪𝗵𝘆 𝗯𝘆𝘁𝗲 + 𝗯𝘆𝘁𝗲 𝗯𝗲𝗰𝗼𝗺𝗲𝘀 𝗶𝗻𝘁 𝗯𝘂𝘁 𝗯 += 𝗮 𝘄𝗼𝗿𝗸𝘀 In Java, arithmetic operations on byte and short are automatically promoted to int.  • a + b is promoted to int, so assigning it to a byte requires an explicit cast.  • b += a is a compound assignment operator. It automatically casts the result back to the type of the left-hand side (byte in this case), so no explicit cast is needed. Understanding this subtlety can save you from unnecessary compilation errors when working with smaller numeric types in Java.

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories