CSC 4217 - Lecture 1 & 2
CSC 4217 - Lecture 1 & 2
1
Content
1. Programming Languages Translation
2. Fundamental Data Types
3. Algorithms
4. Basic OO Concepts
2
Programming Languages Translation
Lecture Objectives:
Be able to list and explain five features of the Java programming language.
Be able to explain the three standard language translation techniques.
Be able to describe the process of translating high-level languages.
Understand the concept of virtual machines and how Java uses this concept to achieve platform
independence.
Understand the structure of simple Java programs
3
The Java Programming Language
The object-oriented paradigm is becoming increasingly popular compared to other paradigms.
The Java programming language is perhaps the most popular object-oriented language today.
4
High Level Language Translators
As mentioned earlier, one of the disadvantages of a high-level language is that it must be
translated to machine language.
5
High Level Language Translators
Assemblers
An assembler is a program that translates an assembly language program, written in a
particular assembly language, into a particular machine language.
Compilers
A compiler is a program that translates a high-level language program, written in a
particular high-level language, into a particular machine language.
Interpreters
An interpreter is a program that translates a high-level language program, one
instruction at a time, into machine language.
As each instruction is translated it is immediately executed.
Interpreted programs are generally slower than compiled programs because compiled
programs can be optimized to get faster execution.
Note that:
Some high-level languages are compiled while others are interpreted.
There are also languages, like Java, which are first complied and then interpreted
6
Compilation Process: Traditional Compilers
In the traditional compilation process, the compiler produces machine code for a specific family of
processors
For example, given a source program, a compiler for the x86 family of processors will produce binary
files for this family of processors.
A disadvantage of this compilation method is that the code produced in each case is not portable.
To make the resulting code portable, we need the concept of a virtual machine as we discuss in the
following page.
7
Compilation Process: Java Compilers
8
Java Virtual Machine
Instead of producing a processor-specific code, Java compilers produce an intermediate
code called bytecode.
The bytecode is also a binary code but is not specific to a particular CPU.
A Java compiler will produce exactly the same bytecode no matter what computer system is
used.
The Java bytecode is then interpreted by the Java Virtual Machine (JVM) interpreter.
Notice that each type of computer system has its own Java interpreter that can run on that
system.
9
Structure of Simple Java Programs
The following figure shows a simplified structure of Java programs. We
will consider a more detailed structure of Java programs later in this course.
public class ClassName {
public static void main(String[] args ){
statement 1
statement 2
* * *
statement N
}
}
You must type this program and save it in a file named Greeting.java
Java is case sensitive and has a free-form layout
The words public, class, static, void, main and etc are called reserved or
keyword words
The meaning of the words is fixed by the language. For now, they must
appear in the places shown.
11
Structure of Simple Java Programs (cont’d)
By contrast, the word Greeting, varies from program to program.
What exactly goes there is chosen by the programmer.
The first line, public class Greeting, start s a new class called Greeting.
Classes are a fundamental concept in java. Their role is as factories for objects.
But here we are using the Greeting class as a container for our program’s instructions.
Java requires that all program instructions be placed inside methods and that every
method must be placed inside a class.
Thus we must define methods that would contain our instructions and a class that holds
the methods.
In our program, main() is our only method while Greeting is our class.
12
Structure of Simple Java Programs (cont’d)
At this point, simply regard
public class ClassName{
...
}
as a necessary part of the plumbing that is required to write a java
program.
The construction
public static void main (String[] args){
...
}
is where we define the method main ( )
13
Structure of Simple Java Programs (cont’d)
The parameter String[] args is a required part of the main method.
At this time, simply consider
public class ClassName{
public static void main (String[] args){
…
}
}
as yet another part of the plumbing for the time being, simply put all instructions
between the curly braces {} of the main() method.
There is no limit to the number of instructions that can be placed inside the body of the
main method.
14
Structure of Simple Java Programs: Printing Output
The instruction,
System.out.println(“Good Morning”);
prints a line of text namely “Good Morning”.
Terminal window is represented in java by an object called out and out object is
contained in the System class.
The System class contains useful objects and methods to access System resources. To
use the out object in the System class, you must to refer to it as System.out
To use System.out object, specify what you want to do to it. In this case, you want to
print a line of text. The println() method carries out this.
15
Structure of Simple Java Programs: Printing Output
The println() method prints a string or a number and then start a new line. For example
The sequence of statements:
System.out.println (“Good”);
System.out.println (“Morning.”);
prints two lines of text
Good
Morning.
The statement:
System.out.println (3 + 4);
prints the number
7
There is a second method called print(), which print an item without starting a new line.
For example
System.out.print (“Good”);
System.out.println (“ Morning.”);
prints a single line
Good Morning.
16
Escape Sequences
An escape sequence is a special two-character sequence representing another
character. Suppose you want to display a string containing quotation marks, such as
Hello, “World”!
You shouldn’t use
System.out.println(“Hello, “World”!“);
To display quotation marks in the above example, you should write:
System.out.println(“Hello, \“World\”!“);
Therefore, \” is an escape sequence representing quotation mark “ .
Similarly, \n an escape sequence representing a new line or line feed character.
Printing a new line starts of a new line on the display.
For example the statement:
System.out.println(“*\n ** \n *** \n);
prints the following
*
**
***
17
Example 2
An agent sold a property worth N50000. If the buyer pays the agent 7% of the
sale amount, find the agent’s commission and the total amount that the buyer
must pay. The following program computes the agent’s commission and the
total amount the buyer must pay. Study the program and try to relate it with
the above java fundamentals you learned so far. What would be the output of
the program?
19
Primitive Data Types
Java has eight primitive data types as described below.
20
Variable Declaration
A variable can be declared to hold a data value of any of the primitive types.
A variable is a named memory location in which a value is stored.
A variable name is a sequence of letters and digits starting with a letter.
int counter;
int numStudents = 583;
long longValue;
long numberOfAtoms = 1237890L;
float gpa;
float batchAverage = 0.406F;
double e;
double pi = 0.314;
char gender;
char grade = ‘B’;
boolean safe;
boolean isEmpty = true;
21
Numbers and Constants
By default, whole numbers are int and real numbers are double.
However, we can append a letter at the end of a number to indicate its type.
Upper and lower case letters can be used for ‘float’ (F or f), ‘double’ (D or d), and ‘long’ (l
or L):
Operator Description
23
Arithmetic Operators (Cont’d)
The operators give results depending on the type of the operands.
If operand1 and operand2 are integer, then the result is also integer. But if either operand1
and/or operand2 is double, then the result is double.
Examples:
24
Arithmetic Operator Priority
An expression is a sequence of variables, constants, operators, and method calls that
evaluates to a single value.
+ - (unary) 1 3+7%2 4
* / % 2 (2 – 5) * 5 / 2 -7
+ - (binary) 3
2–5+3 0
25
The Math class
Many mathematical functions and constants are included in the Math class of the Java
library. Some are:
Function /constant Meaning
sqrt(x) Returns the square root of x.
abs(x) Returns the absolute value of x, x can be double, float, int or long.
cos(a), sin(a), tan(a) Returns the trigonometric cosine/sine/tangent of an angle given in radians
exp(x) Returns the exponential number e raised to the power of x
log(x) Returns the natural logarithm (base e) of x
max(x, y) , min(x, y) Returns the greater/smaller of two values, x and y can be double, float, int or
long
pow(x, y) Returns xy
PI The approximate value of PI
variable = expression;
The expression on the right –hand side is evaluated and the result is assigned to the variable
on the left-hand side.
Examples:
a = 5;
b = a;
b = b + 12; // valid: assignment operator , =, is not an equality operator
c = a + b;
a + b = c; // invalid: left side not a variable
27
Assignment Statement (cont’d)
To exchange (or to swap) the contents of two variables, a third variable must be used.
Example:
28
Short Hand Assignment Operators
Java provides a number of short hand assignment operators:
Short-Form Equivalent to
Example:
a += 5; // equivalent to a = a + 5;
29
Increment and Decrement Operators
Increment/decrement operations are very common in programming. Java provides
operators that make these operations shorter.
++ op++ Increments op by 1;
++ ++op Increments op by 1;
-- op-- Decrements op by 1;
-- --op Decrements op by 1;
Example:
int y = 20; x = 10, z;
y++ ;
z = x + y;
30
Writing Algebraic Expressions in Java
All operators must be explicit especially multiplications.
For a fraction, you must use parenthesis for the numerator or denominator if it has addition
or subtraction.
4X Y z = (4 * x + y) / x2 – 2 * y
Z 2Y
X2
z = Math.sqrt(x + Math.pow(y, 2))
2
Z X Y
31
Example1
The following example computes the roots of a quadratic equation using the formula:
Algorithm:
» a=1
» b = -5
» c=6
» root1 = (-b + sqrt(b * b – 4 * a * c ) ) / ( 2 * a)
» root2 = (-b - sqrt(b * b – 4 * a * c ) ) / ( 2 * a)
» print root1, root2
Java code:
public class QuadraticEquation {
public static void main(String[] args) {
double a = 1, b = -5, c = 6;
double root1 = (-b + Math.sqrt(b*b - 4*a*c))/(2*a);
double root2 = (-b - Math.sqrt(b*b - 4*a*c))/(2*a);
System.out.println("The roots are: "+root1 + " ,"+root2);
}
}
32
Example2
The following example calculates the area and circumference of circle.
Algorithm:
» radius = 3
» area = pi * radius2
» circumference = 2 * pi * radius
» print area, circumference
33
Algorithms and Problem Solving
Problem Solving
Algorithms
Sequential Statements
Examples
34
Problem Solving
Solving a problem means that we know the way or the method to follow manually
from the start till the end.
Having the method known, the same method is used by the computer to solve the
problem but faster and with higher precision.
If we do not know how to solve a problem ourselves, the computer will not be of
any help in this regard.
The strategy for solving a problem goes through the following stages:
Analysis: in this stage, we should find what the problem should do.
Design : the way or method of how your problem is solved is produced
Implementation: the method found in design is then coded here in a given
programming language.
Testing: here we verify that the program written is working correctly
Deployment : finally the program is ready to use
35
Problem Solving Strategy
36
Algorithms
An algorithm is a sequence of instructions that solve a problem.
The description of the instructions can be given in English like statements called
pseudo-code
37
Sequential Statements
Instructions in this type of flow control are executed one after the other in sequence
Assignment statement
Method calls
38
Example1
Write a program that assigns the Cartesian coordinates of two points (x1, y1) and (x2,
y2) and displays the distance between them using the following formula.
d ( x1 x2 ) 2 ( y1 y2 ) 2
Algorithm:
» Get a value for x1 (e.g., x1 = 1)
» Get a value for y1 (e.g., y1 = 1)
» Get a value for x2 (e.g., x2 = 4)
» Get a value for y2 (e.g., y2 = 6)
» Calculate the distance using the formula:
– distance = sqrt( (x2 – x1) ^ 2 + (y2 – y1) ^ 2 )
» print distance
39
Example1 (cont'd)
Java code:
public class Distance {
public static void main(String[] args) {
double x1, y1, x2, y2, dist;
x1 = 1.0;
y1 = 1.0;
x2 = 4.0;
y2 = 6.0;
dist = Math.sqrt(Math.pow(x2-x1,2)+ Math.pow(y2-
y1,2));
System.out.println("The distance is " + dist);
}
}
40
Example2
Write a program that finds the area of a triangle given the length of its sides: a, b, c.
Use a = 3, b = 4, c = 5 to test your solution.
41
Example2 (cont'd)
Java code:
public class Distance {
public static void main(String[] args) {
double a, b, c, area;
a = 3.0;
b = 4.0;
c = 5.0;
s = (a + b + c ) / 2.0;
area = Math.sqrt(s * (s - a) * (s – b) * (s – c) );
System.out.println("The area is " + area);
}
}
42
Basic Object-Oriented Concepts
Object-Oriented Paradigm
What is an Object?
What is a Class?
More OO Concepts
OOP is a model whereby a problem domain is modeled into objects, so that problem
solving is by interaction among objects.
OOP is a more natural model compared to other models since OOP’s approach is
exactly the way humans view problem solving.
We take a closer look at the main ingredients of the model: Objects and Classes.
44
What is an Object?
An object is an individual, identifiable entity, either real or
abstract, that has a well-defined boundary.
An object has two main properties, namely:
• State: each object has attributes, whose values represent its
state.
• Behavior, each object has a set of behavior.
Try to list some of the attributes and set of behavior for each of
the above objects.
Also look around you and identify the objects you can see or
imagine.
46
What is a Class?
A class is a general specification of attributes and behavior for a set of objects.
Each object is an instance of a class. It shares the behavior of the class, but has specific
values for the attributes.
Thus, a class can be viewed as an abstract specification, while an object is a concrete
instance of that specification.
An example of a class is Student, an abstract entity that has attributes and a set of behavior.
However, unless we have an actual student, we cannot say what the ID number is or what
the major is.
47
What is a Class? (cont’d)
The following table shows further examples of classes and
their instances:
Classes Instances of (or Objects)
University ABU
Course CSC211
Identify the classes for the objects you identified in the exercise on
Slide#68.
48
Constructing Objects from a Class
49
… Constructing Objects from a Class
Student thisStudent =
new Student(993546, “Suhaim Adil”, 3.5);
The relationship between the reference variable, thisStudent, and the
object created is shown by the following figure:
50
Problem Solving in OO languages
In the real world, problems are solved by interaction among objects.
If you have a problem with your car, you take it to a mechanic for repair.
Similarly, in OO programming languages, problems are solved by
interactions among objects.
Objects interact by sending messages among themselves.
51
Problem Solving in OO languages
Student thisStudent =
new Student(993546, “Suhaim Adil”, 3.5);
Messages are sent using the following general syntax:
referenceVariable.methodName
To know the GPA of the student object we created, a message is sent as
follows:
double gpa = thisStudent.getGPA();
We have been sending messages to the System.out object in
previous examples.
System.out.println(“Salaaam Shabaab”);
52
Encapsulation
Having understood the main ingredients of OOP, we can now take a closer
look at its main features.
One of the key features is the bringing together of data and operations –
Encapsulation.
Encapsulation, also called information hiding, allows an object to have
full control of its attributes and methods.
The following shows how an object encapsulates its attributes and
methods.
53
Inheritance
Another powerful feature of OOP is inheritance.
Classes are organized in hierarchical structure.
For example, the following shows a Student class and its related sub-
classes:
54
Strength of the OO Paradigm
55