Starting from:
$30

$24

Part 1 Data type convension

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:
    • Go to http://docs.oracle.com/javase/8/docs/api/overview-summary.html
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.
        ◦ http://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html
    • Lower on this page, you will find the class Integer.
        ◦ http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html
    • Now find the method parseInt(String s) and identify the type that it returns.
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?
Question 1.21 :
public class Test {
        public static void main ( String[] args ) {
                int num1 = 9 ;
                double num2 = 12.0;
                double sum = num1 + num2;
                System.out.println(sum);
        }
}
Answer
Question 1.22 :
public class Test {
        public static void main(String[] args) {
                double num1 = 18.4;
                double num2 = 1.6;
                int sum = num1 + num2;
                System.out.println(sum);
        }
}
Answer
Question 1.23 :
public class Test {
        public static void main(String[] args) {
                double num1 = 13.6;
                double num2 = 2.5;
                int sum = (int)num1 + (int)num2;
                System.out.println(sum);
        }
}
                
Answer
Question 1.24 :
public class Test {
        public static void main(String[] args) {
                double num1 = 13.6;
                double num2 = 2.5;
                int sum = (int)(num1 + num2);
                System.out.println(sum);
        }
}
                
Answer
Question 1.25 :
public class Test {
        public static void main(String[] args) {
                int num = 96;
                char a = num;
                System.out.println(a);
        }
}
Answer
Question 1.26 :
public class Test {
        public static void main(String[] args) {
                System.out.println( (float)(int)2017.89432 );
        }
}
Answer
Question 1.27 :
For this question, we will revisit the main method. As you already know, the main method as to contain the argument String args[]. This argument allows you to give data to you program as you start it. To do so, you need to pass the “command-line arguments” upon the invocation of your program like this:
>java MyProgram one two
Where args now contains the strings “one” and “two”. We can now use args like a regular array.
Example:
Now, create the class “Sum” that converts all the elements from the command line from String to int, and then do the sum of the elements.
Hint: Use the method of the class “String” available in the Java documentation
> javac Sum.java
> java Sum 1 2 3 4 5
Your program should look like this:
The sum is 15
You can watch the following video for a step by step explanation : https://www.youtube.com/watch?v=38C2lJTbJNU

More products