Explain what is meant by a type, illustrating your answer by explaining what the following fragment of code does:
int x = 1; double y; y = x + 3;
Answer 1:
A type is something which categorizes data into subsections, with each subsection having a specific function in programming, for example, integers, doubles, and booleans are all types which have a particular and different purpose when used to store or process data in programming. Types help identify the amount of storage required to store a particular set of data. Therefore types each have a particular function when compiled in a program. It can be used to classify variables as well. The code takes a variable called x assigned the type of int, which means it holds any …show more content…
Examples of types are Strings, Integers, Booleans, and Doubles. The type defines the set of operations that can be performed on a particular piece of data. Declaring data types allows the appropriate bytes of memory to be allocated when data is stored. For example, while type int requires 4 bytes of memory, type double requires 8 bytes of memory. Therefore type declarations affect the way values of data is stored and compiled.
The fragment of code presented involves two different types. The first type is ‘int’ which can be assigned to any whole integer value, and the second is type ‘double’, which can be assigned to any floating point numbers.
Line 1 creates the variable name x, and assigns x to the data type int and initializes x to the value of 1. Line 2 creates variable y, and assigns y to the data type double, and leaves y uninitialised. Line 3 is an assignment and evaluates y to int x, which has the value of 1, and adds the integer 3 to x. The result of y is the sum of two integers (1 + 3) which gives y the value of 4 as an integer. However as y was initialised as a double, there is a type mismatch. Therefore a type conversion takes place where the value of y changes from int value of 4 to the equivalent double value of 4.0. y = 4.0 is