Unit 1 - Introduction To OOP
Unit 1 - Introduction To OOP
Unit 1 - Introduction To OOP
• Supporting Lecturers:
• Dr Chai Meei Tyng (chaimt@utar.edu.my)
2
We will be using Microsoft Teams as the
main OTL platform.
4
Course Outlines
• Unit 1 – Introduction to Java & Object-Oriented Programming (OOP).
• Unit 2 – Methods
• Unit 3 – Classes and Objects
• Unit 4 – Arrays
• Unit 5 – Class Relationships
• Unit 6 – Inheritance & Polymorphism
• Unit 7 – Abstract Class and Interface
• Unit 8 – GUI Programming
• Unit 9 – Event Driven Programming
• Unit 10 – Exception Handling and File Input/Output
• Unit 11 – Java Database Programming
• Unit 12 – Thread and Multithreading
5
Course Information
• Assessment methods:
1. Coursework – 50%
• 1 Mid Term Test (20%) – Week 9 (Unit 1–7)
Date: TBA
Time: TBA
• https://docs.oracle.com/javase/tutorial/index.html
• https://www.tutorialspoint.com/java/index.htm
• https://www.geeksforgeeks.org/java/ etc
7
Unit 1: Introduction to Java & Object-Oriented
Programming (OOP)
8
Unit 1 Goals
• To understand object-oriented programming (OOP) concepts
• To understand the concepts of classes and objects
• To understand Java language specifications
• To compile and run your first Java program
• To explain the basic syntax of a Java program
• To learn about types and variables
• Primitive type
• Reference type
9
Object-Oriented Programming
(OOP)
What is Object-Oriented Programming (OOP)?
• Object-oriented programming is a programming paradigm that represents
concepts as objects that have data fields (attributes that describe the
object) and functions (methods that represent the object’s behaviour)
Shared Data
vs.
11
Why OOP? What are the benefits?
• Code reuse – objects created for one program can easily be reused in
the other programs.
12
What are the disadvantages?
• Effort – Object-Oriented programming is harder to learn and an OO
program requires a lot of work to create. Specifically, a great deal of
planning goes into an OO program well before a single piece of code is
ever written.
• Size & speed – Object-Oriented programs can be larger and slower than
other programs.
13
Example
typedef struct {
char *name;
int accountNum;
float balance;
char accountType;
} Account;
Object-Oriented Approach
• Objects in the problem domain are mapped to objects in software.
• Data and operations are grouped together
• Data are protected
class Account { Customer
private:
char *name;
int accountNum;
float balance;
char accountType;
public: Account
float withdraw();
void deposit(float amount);
void transfer(Account toAcc, float amount);
); class Customer {
private:
Account [] accounts;
Account acc1 = new Account();
acc1.deposit(100); public:
Account acc2 = new Account(); void addAccount(Account acc);
acc1.transfer(acc2, 50.0); );
Customer cus1 = new Customer();
cus1.addAccount(acc1);
Procedure-Oriented Programming vs. Object-Oriented Programming
Objects and Class Sneak Preview
Understanding Objects
• Objects are made up of attributes and methods.
• Example: a car object
• Attributes: fuel, maxspeed, model, year, price, distance, ...
• Methods: refuel(), setSpeed(), drive(), ...
19
Class vs. Object
In OOP, we need to
define a class first
before we can use it to
create (instantiate)
and use objects
20
Class vs. Object
• As in actual world, class (blue print/template) cannot carry out
actual performance
• Instantiation is the process whereby an object (instance) is
created from a class template.
– One may create as many object instances as desired, each has its own
copy of data fields (called instance variables)
– Once we have created an object instance, then we may manipulate the
object by calling one of its methods (called instance methods) to
perform a task or update its data fields
21
Object-Oriented Programming
• There are many more object-oriented programming concepts
such as encapsulation, inheritance, polymorphism, abstract
class, interface.
*** Acquire basic skills of writing program (fundamentals) using primitive data types & operations, loops (control statements),
methods and arrays.
*** Methods (Lecture 2) and arrays (Lecture 4) will be cover in the lectures. 22
Java Programming Language
Top 10 Programming Languages
24
The Java Programming Language
• Simple
• Object-oriented
• Platform-independent ("write once, run anywhere")
• Rich library (packages)
• Designed for the internet
• Benefits
• Safety
• Portability
Java inventor
25
Java – Platform Independent
Platform Dependent
myprog.c myprog.exe
gcc
(compiler) machine code
C source code
OS/Hardware
Platform Independent
myprog.java myprog.class
javac
(compiler) bytecode
Java source code
JVM
java
(interpreter)
(Java Virtual Matchine)
OS/Hardware
26
Creating, Compiling, and Running Programs
27
Java JDK vs JRE
28
Java JDK Version History
• JDK Alpha & Beta (1995) * Long Term Support (LTS)
• JDK 1.1 (1997)
• J2xE 1.2 (1998) – x = (E, S, M)
• J2xE 1.3 (2000)
• J2xE 1.4 (2002)
• Java 5 (2004)
• Java 6 (2006)
• Java 7 (2011)
• Java 8 (2014) – used in this class (LTS to Dec. 2020)
• Java 9 (2017) – short term release starting Java 9
• Java 10 (March 2018), Java 11 (September 2018) – (18.9 LTS)
• Java 12 (March 2019), Java 13 (September 2019)
• Java 14 (March 2020), Java 15 (September 2020 – latest version)
• Java 16 (is in Rampdown Phase)
29
Java JDK Version History
https://en.wikipedia.org/wiki/Java_version_history
30
Java – Support 3 JDK versions
• Java EE (Java Enterprise Edition)
• Business applications, server-side.
• Java SE (Java Platform Standard Edition)
• General applications, client-side.
• Java ME (Java Platform Micro Edition)
• Small devices such as mobile phone, car navigation.
31
Eclipse - Integrated Development Environment (IDE)
34
Java in action – a sneak preview
public class Car {
private String model; // attribute
private double distance;
int main() {
Output: printf("Hello world\n");
return 0;
Welcome to Java!
}
36
Class
• Every Java program must have at least one class. Each class
has a name.
• Java is fully object-oriented, all codes exists in a class
(identified with class keyword).
• class <ClassName>
37
main Method
38
Writing Procedural Program using Java – static method
} }
} }
• If you want to use a static method declared in another class, use the class
name and (.) to refer to the method you want to call.
ClassX.max(a,b);
Math.sin(a);
Class name
41
Java in action – a sneak preview
public class Car {
private String model; // attribute
private double distance;
• In order to use classes in other packages, you have to first import them.
import <PackageName>.<ClassName>.
45
Special Symbols
" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.
46
Types and Variables
• Java is strongly-typed language, every variable must has a
type, which must be declared before its use
• Two different types of variables:
• Primitive type – the variables store the actual values (discuss
next)
int luckyNumber = 13; // primitive type
double total;
47
Differences between Variables of
Primitive Data Types and Reference Types
Stack Heap
Primitive type: int i = 1; i 1
Reference type: Car c; c null
48
Differences between Variables of
Primitive Data Types and Reference Types
Stack Heap
Primitive type: int i = 1; i 1
c: Car
Reference type: Car c; c reference model "BMW"
distance = 0
c = new Car("BMW"); Created using new Car()
49
8 Primitive Types
Type Description Size
4
int The integer type, with range -2,147,483,648 . . . 2,147,483,647
bytes
byte The type describing a single byte, with range -128 . . . 127 1 byte
2
short The short integer type, with range -32768 . . . 32767
bytes
The double-precision floating-point type, with a range of about ±10308 and about 8
double
15 significant decimal digits bytes
The single-precision floating-point type, with a range of about ±1038 and about 4
float
7 significant decimal digits bytes
2
char The character type, representing code units in the Unicode encoding scheme
bytes
boolean The type with the two truth values: false and true 1 bit
50
Number Types
• int: integers, no fractional part
1, -4, 0
51
Explicit Casting
• Casting is an operation that converts a value of one data
type into a value of another data type
• Casting a type with a small range to a type with a larger
range (e.g. int to double) is known as widening a type.
• Casting a type with a large range to a type with a smaller
range (e.g. double to int) is known as narrowing a type.
• Java will automatically widen a type, but you must narrow
a type explicitly.
int a = 10;
double b = 7.3;
b = a; // ok
a = b; // NOT ok
a = (int) b; // ok
52
Character Data Type
char letter = 'A';
char numChar = '4'; Four hexadecimal digits.
53
ASCII Character Set
54
Primitive Data Types as Objects
• Owing to performance considerations, primitive data type
values are not objects in Java.
• However, some Java methods require the use of objects
as arguments. Java offers a convenient way to incorporate,
or wrap, a primitive data type into an object.
• Java provides Boolean, Character, Double, Float, Byte,
Short, Integer, and Long wrapper classes in the java.lang
package for primitive data types.
• Java allows primitive types and wrapper classes to be
converted automatically.
Integer intObj = 3; // boxing
int i = intObj; // unboxing
55
The String Type
• String is actually a predefined class in the Java library just like the
System class.
56
String Concatenation
// s0 = "Welcome to Java"
String s0= "Welcome " + "to " + "Java";
// s1 = "Chapter2"
String s1 = "Chapter" + 2;
// s2 = "SupplementB"
String s2 = "Supplement" + 'B';
57
Converting Strings to Integers
• To convert a String into an int value, you can use the static
parseInt method in the Integer class as follows:
int i = Integer.parseInt("257");
• To convert an int into a String object, you can use the static
toString method in the Integer class as follows:
String s = Integer.toString(i);
58
Converting Strings to Doubles
double d = Double.parseDouble("23.57");
String s = Double.toString(d);
59
Constants
• Constant – value is fixed for the entire execution of your
program
Note: In Java, const is a
• Declare with keyword final, reserved keyword. It is
not used.
final int NUM_STUDENT = 1000;
60
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
% Remainder 20 % 3 2
61
Integer Division
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
62
Logical Operators
Operator Name
! not
&& and
|| or
^ exclusive or
63
Flow of Control
64
Selections Statement Syntax
65
Examples: selections
66
Loops Statement Syntax
The while loop statement has the following
syntax:
while(condition){
// statements
}
The do-while loop statement has the following
syntax:
do{
// statements
}while(condition);
The for loop statement has the following
syntax:
for(initialization; condition;
increment/decrement){
//statements (For Body)
}
67
Examples: loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
68
Programming Errors
• Syntax Errors
• Detected by the compiler
• Runtime Errors
• Causes the program to abort
• Logic Errors
• Produces incorrect result
• Detected (hopefully) through testing
69
Syntax Errors
missing "
70
Runtime Errors
divided by zero
71
Logic Errors
integer division:
9/5 = 1 (not 1.8)
Output:
Celsius 35 is Fahrenheit degree
67 (true answer = 95)
72
What’s next...
73