This lab aims to develop the student knowledge and skills data types, required memory storage for each data type, selection of appropriate data types, naming variables, This lab aims to develop the student knowledge, and skills in identifying the appropriate data-types for variables, calculate the required memory storage for each data type, naming variables, casting of data types, and mathematic operations, the casting of data types, and arithmetic operations.
Dev Dives: Streamline document processing with UiPath Studio Web
CIS 1403 Lab 2- Data Types and Variables
1. Lab 2: Data Types and Variables
CIS 1403
Fundamentals of
Programming
201810
2. Introduction
This lab aims to develop the student knowledge and skills data types, required
memory storage for each data type, selection of appropriate data types, naming
variables, This lab aims to develop the student knowledge, and skills in identifying
the appropriate data-types for variables, calculate the required memory storage
for each data type, naming variables, casting of data types, and mathematic
operations. casting of data types, and athematic operations.
Skill-set
By completing this lab, the students will develop the following skills:
• Using appropriate and efficient data types to store data.
• Calculate the memory storage required for each data type
• Convert from binary to decimal systems
• Create variables that follow the rules of naming variables
• Apply correct athematic operators with the correct precedence
of operators
• Apply data type casting that does result in loss of data
How to use this lab?
Follow the lab instruction in step by step and complete all exercises. Watch
the associated videos.
Modify the examples to and exercises to experiment with different scenarios
to solve a similar problem.
3. Why do we need data type?
In life, we are using different data type including numbers, text, and objects.
Using the appropriate data type in our human communication is essential. We
use text (String) for names and description of information and numbers for
counting and applying mathematical calculations. We also refer to objects such
as a cup, chair, people, milk, etc. All these are data types.
Using the appropriate data type in a programming language is essential for two
reasons.
• Data types help to tell the computer processor what type of
data is expected for a specific variable and what amount of
memory space to reserve for it.
• Using appropriate data type will help programmers optimize
the use of computer memory.
You will get a better understanding of the above two points throughout this lab.
Variables
You have seen in Lab 1 that computer programming languages use variable to
represent data. For example, you may use the variable price to store the price
of an item.
float price;
The above line of code is telling the computer processor to reserve a space in
computer memory for the variable price, and that the data type will be a float.
In this example, if the programmer tried to store text in price, the compiler will
generate an error that says “incompatible data types.” Try this example.
4. Rules for naming variables
It is recommended that you use a variable name that will indicate what data will
be stored in this variable. For example, if you want to store a student grade for an
assessment, a variable name grade or quiz is better than x.
Here are the rules that you need to follow when naming variables in Java.
1. Variable names are case-sensitive.
2. It can contain Unicode letter,Digits and Two Special Characters such as
Underscore and dollar Sign.
3. Length of Variable name can be any number.
4. Its necessary to use Alphabet at the start (however we can use underscore ,
but do not use it )
5. Some auto generated variables may contain ‘$‘ sign. But try to avoid using
Dollar Sign.
6. White space is not permitted.
7. Special Characters are not allowed.
8. Digit at start is not allowed.
9. Subsequent characters may be letters, digits, dollar signs, or underscore
characters.
10. Variable name must not be a keyword or reserved word.
Exercise o correct variable names:
Write down ten different correct variable names and discuss with your
colleagues why these names are correct or not.
5. How does computer store data?
Before discussing the different data types and when a particular data type should
be used we need to examine how computer stores data. We will focus here on
numerical data.
In our daily life, we use a numerical system call decimal. The decimal system is
the numbers from 0 to infinity (both positive and negative values). Example,
0,1,2,3,4,, … etc.
However, the computer understands only 0 and 1. This computer system is
called a binary system. For example, if you store the number 25 in a variable
age.
int age = 25;
The computer will store the value 11001 as binary in computer memory. 11001
in binary is equal to 25 in the decimal system.
The binary system is presented as 2 to the power n. As you know from Math,
anything to the power zero 0 is equal to 1. The table below gives an example of
how to represent a decimal number using the binary system. Let us take the
number 25.
256 128 64 32 16 8 4 2 1
1 1 0 0 1
2 = 1
0
2 = 2
1
2 = 4
2
2 = 8
3
In the above table, the blue row represents the decimal system and the second
gray row represents the binary system. By examining the above table, you can
think of computer memory as boxes that store data in 1, 2, 4, 8, 16, etc. bits. See
the decimal row. This is why when we try to buy a USB flash disk or SD we cannot
find 7 or 9 GB memory.
In the binary row of the above table, we can enter only one digit in each cell with
0 or 1. We read this table from right to left. A value of 1 in the first cell is equal
to 1, but in the second cell it is equal to 2, the third cell is 4, etc. The value of
each cell is just twice the value of the previous cell.
Decimal
Binary
6. 256 128 64 32 16 8 4 2 1
1 1 0 0 1
2 = 1
0
2 = 2
1
2 = 4
2
2 = 8
3
1
8
16
+
+
25
Decimal
Binary
In this example, if you add values of all cells in the decimal row the values in the
binary row is 1, we get the equal decimal value to the entered binary number.
Exercises on binary system
Convert the following binary system to decimal: 11111, 101, 11000, and 101010.
You can use the above tables to
convert binary to decimal and vise
versa.
7. Using Java to convert binary to decimal
Try this code to convert binary to decimal:
Here is the explanation of the above code:
• Line 3: stores the binary number as String. Here you can enter the binary
number that you want to convert.
• Line 4: This line uses the object Integer and its function ParseInt to convert
the binary number of decimal the result is stored in the variable decimal as
an int.
• Line 5 and 4: Print the binary and its equivalent decimal number
When you run the above code you get the following results:
Now, you understand how the computer uses binary numbers to store
numerical data. In the next part of this lab, we will discuss all primitive/basic
data types available in Java.
8. Primitive Data Types
The term “Primitive Data-types” means the most basic data types available
within the Java language. There are eight primitive data types supported by
the Java Language.
The table below summarizes primitive data types support in Java Programming
Language.
There are four integer data types. An integer number is a number that does
not include and fractions (or floating point). It is a whole number. The integer
data types are a byte, short, int, and long. The main difference between these
integer data types is the size of memory space allocated to each one. Each one
has a maximum and minimum value that can be stored. For example, the byte
data type can store numbers no larger than 127 or less than -128. If you try to
store the count of students in a variable with the name nstudents and you have
more than 128 students, the following code will generate an error:
byte nstudents = 128;
The maximum and minimum values
9. The memory size allocated to byte data type is 8 bits. The first bit of the 8
bit is reserved for the sign (+ or ).
-2
7
128 64 32 16 8 4 2 1
1 1 1 1 1 1 1
The maximum positive number that we can store in byte as a binary is
If we go back and use our previous Java code that converts binary to decimal
and we use ”1111111” as the value for the binary, we will get 128. This
means the maximum amount is 128 – 1 = 127.
Minimum value can be stored in a byte =
The minimum negative number that we can store in byte is
= -128
2- 1
7
Maximum value can be stored in a byte =
10. Exercise:
Using the table below, you need to calculate the maximum and minimum values
that can be stored in short, int, and long data types.
11. float and double data types:
The data types float, and double are used to store data with a fraction/floating
point. The size of float is 32 bits, and double is 64 bits. This is primarily why it
called double.
Also, a double data type is more precise than a float. A double variable can
provide precision up to 15 to 16 decimal/floating points as compared
to float precision of 6 to 7 decimal digits.
char data type
The char data type stores character. It required 16 bits = 2 bytes. Each char can
hold only a single character.
boolean data type
A boolean data type is used to store data with two choices: true or
false. Here is an example.
Strings, are a sequence of characters/char. In Java programming
language, strings are treated as objects and not a primitive data type.
The Java platform provides the String class to create and manipulate strings.
char sex = “M”;
String fname = “Khalid”;
Both char and String require putting data between two quotations.
boolean isMale = true;
12. Casting
Casting in programming language means converting data from one type
to another.
When do you need to use casting?
Assume that you have declared price as byte and later you want to
convert it to float because the price usually contains a floating point.
What are your options?
One option is to cast byte into a float.
Write and test this code.
Line 4 perform the casting as follows:
Data type of
the new
variable
The new
variable
Casting to
float. Note
the use of
brackets
The original
variable to
be casted
13. Issues with casting
Casting from a lower size data type to a higher size data type does not cause
any issue.
However, casting from a higher size data type to lower size data type may
result in losing data.
Assume you have stored 200 as the price of an item in a short data type and
you are trying to cast to byte.
As you know, a byte can hold the maximum value of 127. 200 is more than
127. We will lose data.
Try and check this code:
The result
As you can see, casting from short to byte results in producing the wrong results.
You will get the correct result only when the value stored in higher data type is
within the limit of the lower data type. Try to change the 200 in line 3 to 125
and run the code. You should get:
14. Exercise
Discuss the table below and complete the missing information:
Description Appropriat
e variable
name
Data Type Rationale for selecting this data
type
Price of items
in a
supermarket
Number of
registered cars
in UAE
Student mark
for an exam
The balance of
a bank
account (think
of Bill Gates
account)
A student full
name
The result of a
student in an
exam as pass
or fail
15. A thematic Operators
To perform a mathematical calculation in programming Languages, you need
to use the appropriate arithmetic operators. You are expected to be familiar
with these athematic operators as you have used them in mathematics to do
addition, subtraction, multiplication, and division. In Java, there are specific
symbols that you have to use to perform to the correct calculation. The table
below summarizes these operators. Assume A is 10 and B is 20.
In Java, if you want to raise a number to the power of some other number, then
you need to import java.lang.Math and use the function pow. Here is an example
that raises 20 to the power 3.
16. Precedence of Java Operators
Operator precedence determines the sequence of expression/calculation. The
word expression refers to the calculation or the formula used to perform the
calculation. An expression may include constants, variables, operators, and
functions. The precedence of Java operators decides how an expression is
evaluated.
Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence/priority than the addition operator
−
For example, x = 20 + 4 * 2; here x is assigned 28, not 48 because operator * has
higher precedence than +, so it first gets multiplied with 4 * 2 and then adds into
20.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest look at the bottom. Within an expression, higher precedence
operators will be evaluated first.
If you want to force any calculation to be performed first, then you have to
include it between brackets. Here is our same example:
x = (20+4)*2
The result will be 48. The computer will give priority for (20+4), and the result
will be multiplied by 2.
17. Exercises:
1. Write a program that would calculate and output the area of a triangle. Assume base and
height are initialized to 10 and 8 in the program.
Hint: area of a triangle is its base multiplied by its height divided by two.
2. Modify question 3 so that the program accepts the base and height in centimeters from the
user. The program then calculates and outputs the area of the triangle.
3. Write a program to convert Fahrenheit to Celsius temperature and output the result on the
screen.
Hint: Celsius = (Fahrenheit – 32) * 5/9
4. Write a program to prompt the user to enter a value for an amount of money in US dollar.
The program should then convert the amount entered to UAE dirham and output the result
on the screen. Assume one US dollar is AED 3.7
5. The over time rate for a company operating in the UAE is 1.5 times the normal rate. Write a
program to ask the operator to enter the normal rate in UAE dirham, the number of hours
worked at normal rate, and the number of hours worked at overtime rate. The program
should then calculate the gross salary and display the result on the screen.
6. Write a program that asks the user to enter the number of DVDs that he wishes to rent and
the charge of renting a DVD, and then calculates the total charge that he should pay.
7. Write a program that will calculate and display the average mark of 3 different tests. The
program should ask the student to enter the 3 marks first and then display the result.
8. Ahmed wishes to buy 3 books from a bookshop that offers 10% discount on books. Write a
program that asks Ahmed to enter the price of each book and then calculates and displays
the amount of money that he should pay.
9. Salem bought a laptop and printer from a shop that offers discounts on some products. The
original prices of the laptop and printer were 3900 AED and 800 AED respectively. Salem
managed to get 15% discount on the laptop and 10% discount on the printer. Write a
program to find out the amount of money that Salem paid for both items.
10. A family of 4 (husband, wife, 3 years old son and 10 months old daughter). They have
decided to visit Egypt during the Eid break. For the children he will pay 60% and 10% of the
normal ticket price for his son and daughter respectively. Write an algorithm that asks the
husband to enter the price of the air ticket and then calculates and displays the amount of
money he should pay for the 4 tickets.
Complete the following exercises: