Part 1 Data type convension

$24.99 $18.99

Objectives Learning about the concept of data type convension; Differentiate between explicit and implicit data conversion Understand when it is possible to force a type conversion without consequences on the accuracy of the result. 1. Type conversion As we have seen in the last lab, Java is a strongly typed language. It is sometime useful to convert a…

5/5 – (2 votes)

You’ll get a: zip file solution

 

Categorys:

Description

5/5 – (2 votes)

Objectives

  • Learning about the concept of data type convension;

  • Differentiate between explicit and implicit data conversion

  • Understand when it is possible to force a type conversion without consequences on the accuracy of the result.

1. Type conversion

As we have seen in the last lab, Java is a strongly typed language. It is sometime useful to convert a primitive type to another type. To do so, we need to be very careful to not lose any information. There are 2 types of conversion: Explicit and implicit

Implicit conversion (no information loss)

The implicit conversions are those where there is no possible loss of information. They happen automatically when the program runs.

For example, when assigning a value to a variable, the conversion is implicit:

float money; int cash= 25; money = cash;           // Converts from int to float System.out.println (money);

This conversion is implicit because the conversion of an integer to a decimal float happens without any loss of information. We also note that the program prints “25.0”. the “.0” comes from the fact that the int 25 is converted to a float

That is also what happens when a value of type int is assigned to a variable of type long. The type long also represents an integer but the range of value that it can have is far greater than the type int. The implicit conversion cannot be done in the opposite direction (long to int) because there are some values represented by a long that cannot be represented by an int. There is a lot of combination of primitive type conversion. You can find them in the table below.

There is a second case where the implicit conversion happens. It is the arithmetic promotion, which is when the compiler has to modify the type of one of the operand to do an operation.

For example:

double num1 = 2.0; int num2 = 6; System.out.println (num2/num1);

In this example, the program prints 3.0. The variable “num2” is converted to double before the division.

For reference, there exist a list of rules that we can use to know the type of the operand when operations are used with+, -, *, /, %, <, <=, >, >=, == and != .

To do in the following order:

  1. If one of the operands is a double, the other is converted to a double

  2. If one of the operands is a float, the other is converted to a float

  3. If one of the operands is a long, the other is converted to a long

  4. In any other case, the two operands are converted to int

Note that there is not conversion for the type boolean.

The following table gives the list of conversions of primitive type without any data loss:

From

To

byte

short, int, long, float, double

short

int, long, float, double

char

int, long, float, double

int

long, float, double

long

float, double

float

double

Explicit conversion/ Cast

Explicit conversions are conversion where it is possible to lose data. To do it, we need to use the “cast” operator. It is 2 parentheses preceding a value, between the parentheses is the data type that we want to convert the value to.

For example:

double d = 16.987; float f = (float) d;            // Converts from double to float without any loss of data int i = (int) f;                // Converts from float to int with loss of data long l = (long) i;              // Converts from int to long without any loss of data System.out.println (d); System.out.println (f); System.out.println (i); System.out.println (l);

We get this output:

16.987 16.987 16 16

In the output we can see that the decimal value “.987” is lost in the conversion from float to int. It is very important to be careful when doing this kind of conversion to make sure that any loss of data does not affect the output of our program. You will experiment more about this type of conversion in the next part of the lab.

2. Error messages

Through the semester, many ideas will be presented to you so that you learn to program more efficiently. One of the things that you will need to learn is: debugging. At first, students might have to spend a lot of time doing it, sometimes they will look at the wrong part of the code when trying to fix a mistake. We will come back to this in another lab. For now we will focus on the error messages. It is important to understand the error messages and to be familiar with each of them. To help you learn about them, I suggest that you create some small test programs that will show errors.

Exercice! Create a new class named Test with a main method. In the body of the main method, declare a variable of type int to which you will assign the value Long.MAX_VALUE. It is the biggest value of the type long.

What error message is displayed by the compiler?

Sometimes, depending on the logic of our program we might still want to do the conversion. If so, we need to be very careful. Always use a test to make sure that the value of the expression is within the interval of the target type. When we force a conversion (cast), we ignore the compiler’s check to see if the expression is uses compatible types. It is as if we tell the compiler “trust me I know what I’m doing; let me assign this value to the variable”.

long l; ... if (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) {    int i = (int) l;    ... }

Since the value of the variable “l ” is within the possible interval for an int, why do we still need to force the conversion using the syntax (int)? Why can’t we simply write it like this:

long l; ... if (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) {    int i = l;    ... }

The answer is quite simple: the compiler will never do an implicit conversion if there is the possibility of losing information! If you try it you will get this error message.

Test.java:5: error: incompatible types: possible lossy conversion from long to int                    int i = l;                            ^ 1 error

Also, we can’t use the cast to transform an array of character (String) to a number! However, each primitive type has a class “wrapper”. This class has a name similar to the type to which it is associated. For example, for the type int, there is a class Integer (in the same way there is Double, Boolean, Character, etc). As the name indicates, each of these class wrappers are used to save a value within an object like this:

public class Integer {         private int value;         public Integer(int v) {                 value = v;         }         ... }

We will later see some example where theses object will be necessary (in the presentation of the abstract data type). However, an important aspect of these classes is that they regroup a number of methods useful for its type.

Take a look:

It is documentation about the class and method of Java 8.0. Through the session, you will need to reference this documentation in order to use its class and methods.

  • Visit the package lang.

This is always loaded by default in your program (you do not need to use the import command). This is the package in which you will find the wrapper classes. You will also find the class System used to print to the console.

There are a lot of compilation error. These errors can be eliminated if you clearly understand the types and if you apply the syntax rules properly. The following table gives an overview of the most common compilation errors:

ERROR MESSAGE

DESCRIPTION

variable VARIABLE_NAME might not have been
initialized

You tried to use the variable VARIABLE_NAME without initializing it. Careful, it might have been a typo!

';' expected

A semi-colon was expected at the end of a line.

cannot assign a value to a final variable
VARIABLE_NAME

You are trying to assign a value to a constant VARIABLE_NAME that was already initialized.

incompatible types
found:
TYPE1
required: TYPE2

You are trying to assign a value of TYPE1 to a variable of type TYPE2

cannot find symbol
symbol:
WORD
location: LINE

The compiler finds a word that it does not understand. Make sure that it is not a typo.

illegal start of expression

The compiler finds an element that should not be there

not a statement

The line of code is not valid

reached end of file while parsing
}
^

There is probably an error in your code block. Check your brackets {}

In short, the error messages give you a lot of information (type and place of the error). Learn to read and understand these errors. This will help you to debug your code.

Exercices!

What will be the output when compiling and running these programs?

You can watch the following video for a step by step explanation : https://www.youtube.com/watch?v=38C2lJTbJNU

Part 1 Data type convension
$24.99 $18.99