INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM
ICS102, SECTIONS 52, 54 & 55
(001 Semester)
INTRODUCTION TO COMPUTING
LAB #02 Primitive Types & Arithmetic Expressions
Instructor: Bashir M. Ghandi
To gain experience with:
Java has very many data types built into it, and you (as a programmer) can create as many more as you want. However, all data in Java falls into one of two categories: primitive data and objects. There are only the eight primitive data types. Any data type you invent will be a type of object.
Much more will be said about objects in the future
(since Java is a object oriented programming language.) The following
will be all you need to know, for now:
A (crude) analogy
is that a primitive data value is like a nut or a bolt, but an object is like a
whole machine.
Integer Primitive Data
Types |
||
Type |
Size |
Range |
byte |
8 bits |
-128 to +127 |
short |
16 bits |
-32,768 to +32,767 |
int |
32 bits |
(about)-2 billion to +2 billion |
long |
64 bits |
(about)-10E18 to +10E18 |
Floating Point Primitive
Data Types |
||
Type |
Size |
Range |
float |
32 bits |
-3.4E+38 to +3.4E+38 |
double |
64 bits |
-1.7E+308 to
1.7E+308 |
Other Primitive Data Types |
||
char |
32 bits |
Unicode character set |
boolean |
8 bits |
true &
false |
If you just type a
whole number, e.g: 125, Java will automatically represent it as type int. If you want it represented as type long, you
must follow the number with L as in, 125L. (You can
also use small letter l, but that can be
confused with the number 1 one). You can do similar thing with byte and
short.
The default
representation for floating point numbers is double. If you specifically wish to request for a float, you must append
your number with f or F. e.g. 12.5f
Variables are used to store data values in the memory for a program to process. You can use any of the above primitive types to declare variables. (You can also declare variables of a particular class. In that case, they are called objects).
A variable declaration is a request to the system to allocate memory for data values to be stored. It involves specifying the type and a name for the variable. The type is used by the system to know how many bytes of memory to allocate and the name is used by the programmer to refer to the allocated memory.
e.g. int age; int numberOfStudents; double average; |
If we have an initial value to assign to your variables, you can do so at initialization as follows:
|
Arithmetic operators are used
to form arithmetic expressions. If
several operators are used in an expression, there is a specific order in which
the operations are done. Operators of higher precedence will operate
first. There are many operators in Java, the following shows just a few:
Operator |
Meaning |
Precidence |
- |
unary
minus |
highest |
+ |
unary
plus |
highest |
* |
multiplication |
middle |
/ |
division
|
middle |
% |
remainder
|
middle |
+ |
addition
|
low |
- |
subtraction |
low |
In the table,
operators in the same group have equal precedence. So, for example, plus
("+") and minus ("-") have the same precedence.
Note: The operators give different result depending on the type of the
operands. E.g.
20.0 12.0 / 10.0 = 20.0 1.2 = 18.8
20 12 / 10 = 20 1 = 19
Variables are called so
because we can change their values any number of times within a program. One way of assigning or changing the value of
a variable is using the assignment statement.
The assignment statement has the form:
variable = expression;
the expression can be a
literal value (e.g. 25), another variable, or an expression involving both
literals and variables. E.g.
int
first, second;
double
average;
first
= 10;
second
= 20;
average
= (first+second)/2.0
If a data value is not
going to change in a program, it is declared to be a constant using the final
keyword. Constants are conventionally declared using capital letters. E.g.
final
double PI = 3.1415;
Many mathematical
functions and constants are included in the Java library. They are included in the Math class. some of these functions are shown below:
.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
To access any of these
methods, we need to prefix it with the name of the class, Math. e.g
root
= Math.sqrt(20.0);
Reading input from the
console (text mode) is a bit complex for beginners to Java. To avoid this
complexity, we shall initially be using a class, TextIO, which has been
designed to simplify console input operations.
The TextIO class has the
following methods which are used to read the desired type of input.
readByte() :
reads a byte from the data source.
readChar() : reads a character.
readDouble() : reads a double
readFloat() : reads a floate.
readInt() : reads an
integer.
readLong() : reads a long
integer.
readShort() : reads a short
integer.
readString() : reads a string
made out of non-white space
To use the TextIO
class, you need to add the following pieces of code to your programs:
import TextIO;
static TextIO stdin = new TextIO(System.in);
Note: The parmeter to
TextIO can be keyboard (System.in), a data file or a URL
public static void
main(String[] args) throws java.io.IOException;
For all these to
work, you need to copy the file TextIO.class to the same folder containing your
program.
You can get the
TextIO.class from my home page by right clicking the previous link. You can also copy it from my machine
(icswww).
Example 1:
The
following program reads two int values from the user and prints the following
·
Their sum
·
Their difference
·
Their product
·
Their average
·
Their distance (absolute
difference)
·
Their Maximum
·
Their Minimum
import TextIO;
/* Reads two
integer numbers from the user and prints the result
of
applying various arithmetic operations with them
*/
public class Arithmetic {
static
TextIO stdin = new TextIO(System.in);
public
static void main(String[] args) throws java.io.IOException {
int
num1,num2; //two variables to be used for reading input
System.out.print("Enter
First integer number: ");
num1=stdin.readInt();
System.out.print("Enter
Second integer number: ");
num2=stdin.readInt();
System.out.println("The
sum is: " + (num1+num2));
System.out.println("The
difference is: " + (num1-num2));
System.out.println("The
product is: " + (num1*num2));
System.out.println("The
average is: " + ((num1+num2)/2.0));
System.out.println("The
distance is: " + Math.abs(num1-num2));
System.out.println("The
maximum is: " + Math.max(num1,num2));
System.out.println("The
minimum is: " + Math.min(num1,num2));
}
}
Comments.
The
message between /*
*/ is called comments.
It is ignored by the compiler.
It is a good practice to always explain the purpose of a program using
comments.
Any
message following // to the end of a line is also regarded as a comment. This is usually used to explain the meaning
of variables.
You
are expected to write comments explaining each program you write in this
course. You are also expected to
comment any variable whose purpose is not obvious.
Layout.
Notice
how the statements inside a class and those inside a method are indented using
tabs. This makes programs very easy to
read. You are equally expected to use
good layout in writing your programs.
Example2:
The
following program reads the sizes of a rectangle and prints:
·
The Area of the
rectangle
·
The Perimeter of the
rectangle
·
The Diagonal of the
rectangle.
import TextIO;
/* Reads the
sides of a rectangle and prints
the area,
circomference and diagonal
*/
public class Rectangle {
static
TextIO stdin = new TextIO(System.in);
public
static void main(String[] args) throws java.io.IOException {
double
length,breadth;
System.out.print("Enter
the lenght of the rectangle: ");
length=stdin.readDouble();
System.out.print("Now
enter the breadth: ");
breadth=stdin.readDouble();
System.out.println("The
area is : "+ (length*breadth));
System.out.println("The
perimeter is : "+ (2*(length+breadth)));
System.out.println("The
diagonal is : "+ Math.sqrt(length*length+breadth*breadth));
}
}
1.
Copy and paste each of
the above programs into a JCreator, or get them from my computer (icswww),
compile and test run them. Make sure
you understand what is going on in each of them.
2.
Write a program that
reads temperature in Fahrenheit and prints the equivalent temperature in
centigrade.
centigrade =
5/9(fahrenheit-32)
Sample Run:
3.
Write a program that
prompts the user for a radius and prints:
·
The area of a circle of
that radius pr2
·
The circumference of a
circle of that radius 2pr
·
The volume of a sphere
of that radius 4/3
pr3
·
The surface area of a
sphere of that radius 4pr2
Sample Run:
4. Write a program that reads two times in 24 hours format and prints the difference between the two times in hours and minutes. You can assume that the second time is later than the first.
Sample Run:
1 Write a program that asks the following user input:
·
The number of gallons of
gas in the tank of a car
·
The fuel efficiency in
miles per gallon
·
The price of gas per
gallon
The
program then prints
·
How far (in miles) the
car can travel with the gas
· The cost of the travelling 100 miles with the car.
2.
Write a program that
direct a Cashier of a super market on how to give change. The program has two inputs:
·
The amount due
·
The amount received
Your program should give
the minimum number of Riyal notes and coins possible. You can assume that the amount due is not more than SR500 and
that it is always less than or equal to the amount received. Assume that the following Riyal notes and
coins are available:
200 Riyals note
100 Riyals note
50 Riyals note
10 Riyals note
5 Riyals note
1 Riyals note
50 halala coin
25 halala coin
10 halala coin
5 halala coin
1 halala coin