by Dinesh Thakur Category: Data Type

Java has a wide variety of data types from which we can choose the suitable for a particular purpose. To operate on variables from two different types of data we have to convert Both types to the same.

In Java, the expressions and assignments may involve variables of different data types. This type can derive from the structure of the expression and the types of variables and literals used in the expression. It is possible to write an expression that is inappropriate for the type context. In some cases, this leads to an error in compilation of the program, but in another context can accept type which is similar or related to the type of the expression. To evaluate such expressions and assignments, there is a need to convert a variable of one data type to another. Consider an example in which we declare variables of type integer, but we may need the result to be of floating point number. In such situations, we need type conversion. This property of converting a variable of one data type to another data type is known as type conversion.

Type conversion can occur in some situations like in an assignment statement, in arithmetic expressions involving different data types and in returning value from the function in which the type of the expression differs from the return type.

Specific conversion from type S to type T allow the expression of type S treated as an expression of type T during the execution of the program. In some cases this will require validation conversion. Here are some examples:
1. Conversion from type Object to a String require verification during execution to verify that the value is a correct instance of type String or any class of heirs String.
2. Convert a String to Object does not require verification. A string is the successor of the Object and can convert to its base class without risk of error or loss of data.
3. Conversion from type int to long can be done without check during the performance because there is no danger of losing data.
4. Conversion from type double to long conversion requires 64 - bit floating point value to a 64-bit integer. Depending on value can be obtained data loss because it is
necessary to convert types explicitly. In Java, not all types can convert to any other, but only specific.

Type conversion is usually classified in two categories.

1) Implicit or Automatic Type Conversion
2) Explicit Type Casting or Type Casting

Implicitly (Automatic) Type Conversion

Implicit (hidden) type conversion is only possible when there is no possibility of data loss in the conversion, i.e., When you convert type to a smaller range to type with greater (for example from int to long). To make implicit conversion is not needed to use any operator, so-called hidden.
The conversion is done automatically by the compiler when mapping value of the small-scale variable in a broader scope, or when expression types have a different scope. Then convert it to type with a greater range. This is known as widening a type.

The rules in the sequence in which they checked are as follows,

1. If either operand is a double, the entire expression is promoted to double before the operation is carried out.
2. Otherwise, if either operand is the float, the other is promoted to float before the operation is carried out.
3. Otherwise, if either operand is long, the other is promoted to long before the operation is carried out.
4. Otherwise, if either operand is int, the other operand is promoted to int.
5. If neither operand is double, float, long or int, both operands promoted to int.

Implicit Type Conversion - Example

Here is an example of implicit (implicit) type conversion :

int VarInt = 5;
System.out.println(VarInt); // 5
long Varlong = VarInt;
System.out.println(Varlong); // 5
System.out.println(Varlong + VarInt); // 10

Possible Transformations Implied

These are possible implicit conversion of primitive types in Java:

implicit conversion of primitive typesConversion of types from small-scale to a larger no loss of data. The numerical value remains the same after conversion. As with any rule, there are few exceptions. When convert type int to type float ( 32-bit values), the difference is an int that uses all your bits for a single integer including as part of the float bits used for the presentation of Float. Hence, it is possible in the conversion of int to float to a loss of accuracy due to rounding. The same concerns the conversion of 64-bit long to double.

For example: In the statements,
int i = 10;
double j = 5.6;

Suppose we want to compute i + j, the arithmetic expression i + j involves two variables of different data types int and double; the compiler evaluates this expression by converting the int data type of variable i into double according to rules of implicit conversion discussed — this converted value stored in the temporary double variable before being added to the variable j.
After the conversion, addition performed that results in 15.6. This conversion takes place automatically without any information to the programmer. The implicit type conversion show below

Implicit type conversion of expression

1/2 = 0 (int), 8/2.0 = 4.0 (double)
1.2/2 = 0.5 (double), 8.0/2.0 = 4.0 (double)

The following program shows how implicit type conversion is performed.

//program to show implicit type converstion
public class ImplicitConv {
   public static void main(String[] args) {
     byte i = 10;
     long j = i + 8;
     double k = i * 2.5 + j;
     System.out.println("i = " +i);
     System.out.println("j = " +j);
     System.out.println("k = " +k);
Output: i = 10 j = 18 k = 43.0

Here, the variable i is of byte data type and j is of the long data type. So during the evaluation of the expression i + 8, the data type of the variable is converted temporarily from byte data type to that of int data type so that it can add to int literal 8. Now both the temporary variable and literal 8 to be added are of the same type, the result obtained is of int type which again stored in a new temporary variable which is .created during its execution.
Since the datatype of variable j (i.e., long) on the lefthand side differs from the data type on the right side (i.e., int), so the int data type is converted into long and stored in a temporary variable created internally. Finally, the result assigned to variable j.
Similarly, an implicit conversion takes place for the expression k = i  * 2.5 + j;

Explicitly (explicit) Type Conversion

Explicit type conversion is needed when it is probable loss of data. When you convert a floating-point type to an integer type, there is always loss of data coming from the float and must use explicit conversion (double to long). To make such conversion is necessary to explicitly use operator for data conversion (cast operator): (type). possibly There may be data loss also when converting from type larger range to type with less (double to float or long to int). Explicit type conversion is also known as narrowing a type.

Explicit Type Conversion - Example

The following example illustrates the use of an explicit conversion types and data loss:

double VarDouble = 5.1d;
System.out.println(VarDouble); // 5.1
long Varlong = (long)VarDouble;
System.out.println(Varlong); // 5
VarDouble = 5e9d; // 5 * 10^9
System.out.println(VarDouble); // 5.0E9
int VarInt = (int) VarDouble;
System.out.println(VarInt); // 2147483647
System.out.println(Integer.MAX_VALUE); // 2147483647

The first line of the example you assign a value to the variable 5.1 VarDouble. Once you convert it (explicitly) by the operator (long) long to type and print the console variable Varlong, we see that the variable is the value lost after float (for long to integer). Then on the seventh row Assign variable VarDouble 5 billion. finally convert VarDouble to int by the operator (int) and print variable VarInt. Then same result as when print Integer MAX_VALUE, this is because VarDouble incorporates more value of the range of int.

Loss of Data Type Conversion

Example of loss of information on type conversion:

long Varlong = Long.MAX_VALUE;
int VarInt = (int)Varlong;
System.out.println(Varlong); // 9223372036854775807
System.out.println(VarInt); // -1

Conversion operator can be used in implicit conversion. This makes for code readability, reduces chance of errors and is considered good practice by many programmers.
Here are a few examples of the type conversion:

float height = 1.74f; // Explicit conversion
double MaxH = height; // Implicit
double MinH = (double) height; // Explicit
float AHeight = (float) MaxH; // Explicit
float MaxHFloat = MaxH; // Compilation error!

In the example, the last line we have an expression that will generate error compilation. This is because we are trying to implicitly convert type double to type float, which may be a loss of data. Java is strictly typed programming language and does not allow this kind assign values​​.

Possible Explicit Transformations

These are possible explicit transformations and all of them have the possibility of data loss, so be careful:
1. Short to byte or char
2. Char to byte or short
3. Int to byte, short or char
4. Long to byte, short, char or int
5. Float to byte, short, char, int, or long
6. Double to byte, short, char, int, long or float

These transformations can lose as information about the size the number, and information about its accuracy (precision).
When you convert a byte to char have the first secret of converting byte to int, then it explicit conversion from int to char.

Converting to string

If necessary, we can convert to string each type including the value null. Conversion of strings happens automatically whenever you use the concatenation operator and any argument is of type string. In this case, the argument is converted, forms a string to the operator returns a new string representing the concatenation of two strings.
Another way to convert objects to different types such as string is call method toString () of the variable.

Converting to string - example
Let us examine some examples of the conversion of different types of data to a string:

int a = 5;
int b = 7;
String s = "Sum=" + (a + b);
String incorrect = "Sum=" + a + b;
System.out.println("Perimeter = " + 2 * (a + b) +". Area = " + (a * b) + ".");

The results of the example is as follows:

Perimeter = 24.
Area = 35.

From the results it appears that a number attached to a string returns as a result the string, followed by the text representation of number. Note that the '+' to glue strings can cause unpleasant effect the recovery of numbers because it has the same priority with the "+" collection. Unless explicitly change priority of operations by placing the brackets, they always run from left to right.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.