0% found this document useful (0 votes)
13 views

CSC 4217 - Lecture 1 & 2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CSC 4217 - Lecture 1 & 2

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

CSC 4217 - Java Programming I

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

 Java Programming Language


 Translating High-level Languages
 The Java Virtual Machine
 Java Program Structure
 Exercises

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.

 Here are some reasons why Java is popular:


 1. Simple.
 Compared to many modern languages, the core of the Java language is simple to master.
 2. Object-oriented.
 Java is an object-oriented language and therefore it has all the benefits of OO languages
described earlier.
 3. Secure.
 The Java system controls what parts of your computer a program access.
 4. Architecture neutral.
 A Java program will run identically on every platform. We will explain how Java achieves
this portability later in this session.
 5. Java is for Internet applications
 Java was designed so that it can download programs over the Internet and execute them.

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.

 High-level languages are translated using language translators.

 A language translator translates a high-level language program or an


assembly language program into a machine language program.

 There are three types of translators:


 1. Assemblers.
 2. Compilers.
 3. Interpreters.

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.

 This is how Java achieves compatibility.


 It does not matter on what computer system a Java program is compiled, provided the target
computer has a Java Virtual machine.

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
}
}

A Java program consists of essential elements called classes. The


classes in a program are used to create specific things called objects.
10
Source Program: Example
 This is an example of a Java source program
public class Greeting {
public static void main(String[] args )
{System.out.println(“Good Morning.”);
}
}

 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.

 Our program contains only one instruction, that is


System.out.println (“Good Morning”);

14
Structure of Simple Java Programs: Printing Output
 The instruction,
System.out.println(“Good Morning”);
prints a line of text namely “Good Morning”.

 A program can send the string : to a window, to a file, to a networked computer.


 However, our program prints the string to the terminal window. That is the
monitor.

 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?

public class Interest{


public static void main (String[] args) {
System.out.print (“The agent’s commission is: ” );
System.out.println (50000 * 0.07 );
System.out.print (“Total amount the buyer pays is: ”);
System.out.println (50000 + 50000*0.07);
}
}
18
Fundamental Data Types

 Primitive Data Types


 Variable declaration
 Numbers and Constants
 Arithmetic Operators
 Arithmetic Operator Precedence
 The Math Class
 Assignment statement
 Increment and Decrement operators
 Writing Algebraic Expressions in Java
 Math Functions: Examples
 Casting

19
Primitive Data Types
 Java has eight primitive data types as described below.

Type Size Range


byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767

int 4 bytes about –2 billion to 2billion


long 8 bytes about –10E18 to +10E18
float 4 bytes -3.4E38 to +3.4E38
double 8 bytes 1.7E308 to 1.7E308
char 2 bytes A single character
boolean 1 byte true or false

 Other information is represented in Java as Objects.

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):

float maxGrade = 100f;


double temp = 583d;
float temp = 5.5; // Error as 5.5 is double
float temp = 5.5f;
long y = 583L;
double x = 2.25e-6;

 One use of the modifier final is to indicate symbolic constants.


 By convention, symbolic constants are written in uppercase letters. Underscores separate
words:
final double SPEED_OF_LIGHT = 3.0E+10;
final double CM_PER_INCH = 2.54;
final int MONTH_IN_YEAR = 12;
22
Arithmetic Operators
 A simple arithmetic expression has the form:
op1 Operator op2
where:

Operator Description

+ Adds op1 and op2

- Subtracts op2 from op1

* Multiplies op1 by op2

/ Divides op1 by op2

% Remainder of dividing op1 by op2

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:

Arithmetic expression Value


1 / 2 0
86 / 10 8
86 / 10.0 8.6
86.0 / 10 8.6
86.0 / 10.0 8.6
86 % 10 6

24
Arithmetic Operator Priority
 An expression is a sequence of variables, constants, operators, and method calls that
evaluates to a single value.

 Arithmetic expressions are evaluated according to priority rules.

 All binary operators are evaluated in left to right order.

 In the presence of parenthesis, evaluation starts from the innermost parenthesis.

Operators Priority (Precedence) Expression 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

 Syntax to call a function in the Math class: Math.functionName(ExpressionList)


 Syntax to access a constant in the Math class: Math.ConstantName
 Example: Math.PI * Math.max(4 * y, Math.abs(x – y))
26
Assignment Statement
 Syntax:

variable = expression;

 The expression on the right –hand side is evaluated and the result is assigned to the variable
on the left-hand side.

 The left-hand side must be a variable.

 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:

double x = 20.5, y = -16.7, temp;


temp = x;
x = y;
y = temp;

28
Short Hand Assignment Operators
 Java provides a number of short hand assignment operators:

Short-Form Equivalent to

op1 += op2 op1 = op1 + op2

op1 -= op2 op1 = op1 – op2

op1 *= op2 op1 = op1 * op2


op1 /= op2 op1 = op1 / op2
op1 %= op2 op1 = op1 % op2

 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.

Operator Use Description

++ 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.

Algebraic expression Java expression

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

public class Circle {


public static void main(String[]args) {
double area, circumference;
int radius = 3;
area = Math.PI * Math.pow(radius, 2);
circumference = 2 * Math.PI * radius;
System.out.println("Area = " + area + “ square cm”);
System.out.println("Circumference = " + circumference + “ cm”);
}
}

33
Algorithms and Problem Solving
 Problem Solving

 Problem Solving Strategy

 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.

 An algorithm has the following properties:


 No ambiguity in any instruction
 No ambiguity which instruction is next
 Finite number of instructions
 Execution must halt

 The description of the instructions can be given in English like statements called
pseudo-code

 The flow control of instructions has three types:


 Sequential
 Selection
 Iteration

37
Sequential Statements
 Instructions in this type of flow control are executed one after the other in sequence

 These statements include:

 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.

area  s s  a s  b s  c 


a b c
s
2
 Algorithm:
» Get the value of a (e.g., a = 3)
» Get the value of b (e.g., b = 4)
» Get the value of c (e.g., c = 5)
» Calculate s using the formula s = (a + b + c) / 2
» Calculate area using the formula area = sqrt( s* (s – a) * (s – b) * (s – c) )
» print area

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?

 Constructing Objects from a class

 Problem Solving in OO languages

 More OO Concepts

 Strength of Object-Oriented Paradigm


43
Object-Oriented Paradigm
 To truly understand Java, we need to understand the paradigm on which it is built on:
the Object-Oriented Paradigm (OOP).

 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.

 Example of an object: You, the student following this Lecture,


are an object.
• Your attributes include your name, your GPA, your major,
etc.
• You also have a set of behavior, including attending lectures,
solving home works, telling
someone your GPA, sleeping, etc.
45
… What is an Object?
 Other examples of objects are:
• The instructor delivering this lecture.
• This room.
• This lecture.
• This University.
• CSC4423.
• Your Bank Account

 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)

Instructor Sahalu Junaidu

University ABU
Course CSC211

Bank Account Ahmad’s Bank Account

 Identify the classes for the objects you identified in the exercise on
Slide#68.

48
Constructing Objects from a Class

 Our main task is to design and implement classes to be used in creating


objects.
 This involves defining the variables, methods and constructors.
 To create an object from a class, we use the new operator, a constructor,
and supply construction parameters (if any).
 Example, we create an object from the Student class as follows:
Student thisStudent =
new Student(993546, “Suhaim Adil”, 3.5);

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:

 The advantage is code-reusability.


 After implementing the Student class, to implement the GraduateStudent,
we inherit the code of Student.

54
Strength of the OO Paradigm

 We conclude this introduction to OOP by summarizing its main


advantages:
 It allows the production of software which is easier to understand
and maintain.
 It provides a clear mapping between objects of the problem domain
(real world objects) and objects of the model.
 It supports code reuse and reduces redundancy.
 It allows "off the shelf” code libraries to be reused..
 It allows the production of reliable (secure) software..

55

You might also like