Does Java always convert addition result into int? - java

is it true that java converts primitive Type addition (like byte+short) results into integers?

I suspect you are talking about promotion. Its not as simple as always promoting to an int. Section 5.1.2 talks about primitive widening in detail, but here are a few guidelines:
If the result is assigned to a variable then it will be promoted to the type of the variable (if possible)
A more limited type will be promoted to the more expansive type
A result can be promoted if it is likely to be larger than the type will handle
Like I said this is a simplification of the actual rules, but in general Java does the right thing.

The following sections of the Java Language Specification (JLS) are applicable:
Section 5.6 Numeric Promotions) "Numeric promotion is applied to the operands of an arithmetic operator"
Section 5.6.2.2 Binary Numeric Promotion) "...If either operand is of type double...long...float...Otherwise both operands are converted to type int"
So in your example of byte + short, the operands would each first be converted to ints.
To further illustrate:
short a = 1;
short b = 2;
short c = a + b;
will produce a compile error "required short, found int".
You would need to cast the result of the addition (an int) to a short, like this:
short c = (short) (a + b);

You need to know about argument promotion and casting concept.
Java can only evaluate the expressions which have values of the same type. for example if you have the expression a = b + c; then a and b and c must have the same type. you now might wonder so how you can add up an integer and a double without anything goes wrong. this is where the concept of type promotion is applied implicitly by Java. in this case your integer variable is implicitly changed to double only for performing your operation (remember the type of your integer variable is not changed only a double copy is made for your expression).
Now the point is that java only uses type promotion implicitly if the data of your variable is not lost. For example if you change integer to double you will not lose any data. but if you want to change let's say a double variable with value 1.2 to integer then you will lose the fraction part. This is where java will not apply type promotion and you need to do type casting manually. Basically what type casting means is to take control over the compiler and telling to compiler that I know I might lose some data in my variable but it is ok and perform the casting for me.
Type promotion and casting occur in expressions and in method calls.
The table below shows the valid promotions which java would do automatically.
Type Valid Promotion
double None
float double
long float or double
int long, float or double
char int, long, float or double
short int, long, float or double (but not char)
byte short, int, long, float or double (but not char)
boolean None(boolean values are not considered to be numbers in java)

Related

Customized Base64 algorithme [duplicate]

Can any one tell what is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
Numeric Promotion Rules
If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.
If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.
Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.
After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands
Numeric promotion is a conversion of an operand (at least one of the numbers involved) to a common type.
For example:
int i = 10;
double d1 = 2.5;
double d2 = d1 * i;
In this case, i is promoted to double so the calculation can be performed. In some ways, you can think of this is analogous to boxing, but boxing involves moving from a struct to an object (from the stack to the heap). But, using the analogy does give an idea of the fact the integral value is being made into a floating point to perform the calculation.
If you look here, you will see the following quote:
Numeric promotion (§5.6) brings the
operands of a numeric operator to a
common type so that an operation can
be performed.
They are referencing this section, where they give a variety of examples. The classic example is that of an int times a float. The integer is promoted to a float so that the multiplied result is, therefore, a float.

Java Numeric Types [duplicate]

Consider the below code snippet:
// automatic casting works for int to byte conversion as integer literal 127
// is in the range for byte
byte b1 = 127; //OK
// automatic casting doesn't work for long to int conversion
// even if long literal is in the range of int.
int i5 = 100L; // NOT OK - compilation error
Is there any explanation for such behavior?
Why is explicit conversion not needed in the case of int to byte, but needed for long to int?
The How does Java convert int into byte? question is different. It is about an issue in implicit conversion of int to byte when the int value is out of range.
Widening conversions (eg. byte to int) are generally accepted implicitly by the Java compiler, as there's no loss of information (the range of int is greater than that of byte).
Narrowing conversions (eg. long to int, as in your case) can cause a loss of information, so are generally required to be explicitly casted.
See this similar question, and this. A relevant piece of the Java Language Specification:
Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.
...
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
Byte and the value of the constant expression is representable in the type byte
Short and the value of the constant expression is representable in the type short.
Character and the value of the constant expression is representable in the type char.
(emphasis mine)
Some confusion stems from the fact that we're dealing in particular with constant expressions, as we're using numeric literals. The above spec also needs some careful reading.
To clear some things up and directly answer some of the OP's queries:
Why implicit narrowing is supported for one type of narrowing and not the other?
Ie. why does byte b1 = 127 work implicitly, while int i5 = 100L not?
byte b1 = 127 performs an implicit conversion as (cf. the bold text in the above quote), "the value of the constant expression is representable in the type byte". That is, 127 is representable by a byte, so the conversion is implicit. If you try byte b1 = 128, you'll get an error about incompatible types, as 128 isn't representable by byte. The only reason we're allowed an implicit cast here at all is because we're using a constant expression.
We don't get an implicit conversion in int i5 = 100L (even though 100 is in the range of int) as that's simply not listed in the allowed implicit conversions (the variable's type, int, is not one of byte, short, or char).
We also don't get an implicit conversion in byte a = 0L, this time as the constant expression is of type long, not of type byte, short, char, or int.
How will a normal programmer know which narrowing conversion is allowed implicitly?
The implicit narrowing conversions only occur when you're assigning a constant expression to a variable. In these cases, implicit conversions are good as we don't want to be writing code like byte b = (byte)0 all the time. At the same time, we do want to be warned if we write something like byte b = 128, as that doesn't have intuitive behaviour.
When we're not assigning constant expressions (so eg. int x = 0; byte b = x;), we always want to be warned when we're doing a potentially lossy conversion, as they're dangerous - so explicit conversions in this case also make sense.

Can an integer be added with a long?

I'm sorry for such a lame-o question. I would test this myself... But unfortunately I do not know how to code for java, and it would not be worth answering just for this one question.
Is it possible to add a long and an integer together?
My friend is working on a project, and I think he can fix one of his errors by using a long instead of an integer. (He wants numbers to be higher than 2.147 billion).
I tried doing a bit of research on my own, and I was surprised that the answer wasn't as easy to find. This is one source of information that I was able to find.
"If either or both of the integer types is a long, the result is a long."
https://community.oracle.com/message/5270213
Is that correct? Again, sorry that I'm not able to test this out myself.
Yes, you can add a long and an int just fine, and you'll end up with a long.
The int undergoes a widening primitive conversion, as described in the Java Language Specification, specifically JLS8, §5.1.2. JLS8 §5.6.2 is the important part that details what happens here (my emphasis):
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
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 remains the case even for the (currently) latest JLS18 spec, in 5.6 Numeric contexts:
If any expression is of a reference type, it is subjected to unboxing conversion (§5.1.8).
Next, widening primitive conversion (§5.1.2) and narrowing primitive conversion (§5.1.3) are applied to some expressions, according to the following rules:
If any expression is of type double, then the promoted type is double, and other expressions that are not of type double undergo widening primitive conversion to double.
Otherwise, if any expression is of type float, then the promoted type is float, and other expressions that are not of type float undergo widening primitive conversion to float.
Otherwise, if any expression is of type long, then the promoted type is long, and other expressions that are not of type long undergo widening primitive conversion to long.
And so on ...
Yes you can add a long and an integer together. in java there are several primitive data types. int and long variables are two of them. these two data types are used to store integer values. the difference is the size of the variable,
int : 32bit
long : 64bit
you can add int and long together, when jvm add these two variables, the result is generated as a long value. so you have to use a long variable to store the answer. This is due to the auto type conversion of java.
if you want to get int value as an answer, you have to cast the long value in to int,
int x=5; //int value
long y = 10; //long value
long z = x + y; //result is a long value(normally jvm does)
int i=(int) (x+y); // result is cast into a int value.
both z and i get value: 15
You can always simply try such things. For instance using jdoodle
As you can see it is perfectly possible. It is advisable to use a long to store the result, but not necessary. In case of overflow in the latter case, Java will simply use the 32 least significant bits, thus:
6666555555555544444444443333333333222222222211111111110000000000 (index)
3210987654321098765432109876543210987654321098765432109876543210
----------------------------------------------------------------
0101010101010010000011110010101111101010101111101011101011011101 (value)
will be stored as:
33222222222211111111110000000000 (index)
10987654321098765432109876543210
--------------------------------
11101010101111101011101011011101 (value)

explicit use of l for Long,D for Double,,F for Float in autoboxing

Byte byte1=10;
Short short1=20;
Integer integer=30;
In the above code autoboxing happens successfully
see the below code here I am doing casitng explicitly because It is taking 20 as integer numeric literal by default.
Byte byte1=new Byte((byte) 20);
Short short1=new Short((short) 20);
but see the below code , I have to use l,f and d explicitly without this it is showing error........what is the reason behind it.I am not getting it.
Long long1=40l;
Float float1=50f;
Double double1=60d;
Auto-boxing doesn't include automatic widening of primitives.
The default type of a constant integer numeric expression in java is int, so those numbers are ints, which will be auto boxed to Integers if required. Automatic widening will occur when a narrower primitive type is assigned to a wider type, such as an int to a long.
But the two compiler actions will not both happen; that's why you need to get the primitive constant expression to the appropriate type so that the auto boxing will be to the correct type.
This is part of the Language Specification for floating point literals, ie. F or f for float, and D or d for double
For decimal floating-point literals, at least one digit (in either the
whole number or the fraction part) and either a decimal point, an
exponent, or a float type suffix are required.
For integers,
An integer literal is of type long if it is suffixed with an ASCII
letter L or l (ell); otherwise it is of type int (§4.2.1).
The unboxing conversions are, among other,
From type long to type Long
From type float to type Float
From type double to type Double
So unless your types are the correct type, you cannot unbox.
As for the Byte, Short, Integer, the JLS again comes to the rescue
A narrowing conversion of a signed integer to an integral type T
simply discards all but the n lowest order bits, where n is the number
of bits used to represent type T. In addition to a possible loss of
information about the magnitude of the numeric value, this may cause
the sign of the resulting value to differ from the sign of the input
value.
In your case, an explicit cast isn't necessary because the values fall within the range of their specific type. If instead, you had
Byte b = 1251;
that would create a compilation error, solved by doing
Byte b = (byte)1251;
but losing information in the value.

What is numeric promotion?

Can any one tell what is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
Numeric Promotion Rules
If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.
If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.
Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.
After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands
Numeric promotion is a conversion of an operand (at least one of the numbers involved) to a common type.
For example:
int i = 10;
double d1 = 2.5;
double d2 = d1 * i;
In this case, i is promoted to double so the calculation can be performed. In some ways, you can think of this is analogous to boxing, but boxing involves moving from a struct to an object (from the stack to the heap). But, using the analogy does give an idea of the fact the integral value is being made into a floating point to perform the calculation.
If you look here, you will see the following quote:
Numeric promotion (§5.6) brings the
operands of a numeric operator to a
common type so that an operation can
be performed.
They are referencing this section, where they give a variety of examples. The classic example is that of an int times a float. The integer is promoted to a float so that the multiplied result is, therefore, a float.

Categories