Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 208

Java Programming Language

Course Introduction
Outline
I. Instructor Information

II. Course Description

III. Textbook && Reference Resources

IV. Grading Policy

V. Academic Policy
Instructor Information

Dr. Huỳnh Công Việt Ngữ


nguhcv@fe.eu.vn
Why Java?
Language C Java
Basis
Language level • Middle • High
Paradigm • A procedure-oriented • an object-oriented programming
programming language language
Translation • C code is compiled to • Java code is compiled to bytecode, which
machine code for a specific is then interpreted by the Java Virtual
platform Machine (JVM) on any platform.
Memory • Manual memory management. • Automatic memory management
management through garbage collection
Application • Develop system applications and • develop enterprise applications and web-
firmware based applications.
Standard library • Limited • includes a wide range of functionality
Popularity • Less popular programming • The most popular programming
language language
Exception handling • Not present • present
Course Description
 Main content:
 Understand the concepts of object-oriented programs to solve
problems
 Understand fundamentals of object-oriented programming in Java
• Explain the concept and demonstrates the use of Polymorphism,
Encapsulation, Abstraction and Inheritance in java
• Practice basic Java language syntax and write Java programs that
use concepts such as variables, conditional and iterative execution
methods
• Discuss on the benefits and the use of JAVA’s Exceptional handling
mechanism
Resources
 Main textbook:
 Core Java-Volume 1: Fundamentals, Cay Horstmann, 2007
 Core Java-Vol 2: Advanced Features, Cay Horstmann, 2008
Learning Tools
 JDK 1.8
 NetBeans 8.2
 How to download and install NetBeans and JDK:
• https://www.youtube.com/watch?v=jM2B18TvK5k
Grading Policy
1. On-going assessment:
 6 labs :
 1 assignment :
 2 progress tests (PT) :
2. Practical and Final Exams:
 1 practical exam (PE):
 1 final exam (FE):
3. Completion Criteria:
1. Every on-going assessment (average) component > 0
2. PE>0
3. FE>4
Academic Policy
1. Cheating:
 Talking, peeking at another student’s paper or other clandestine
method of transmitting information

2. Plagiarism:
 Using the work of others without citing it; that is, holding the work
of others out as your own work
Introduction to Java
Outline
1. History of Java
2. What is Java?
3. JDK, JRE && JVM
4. How the Java works
5. First Java Program in NetBeans
History of Java
 Introduced in 1995 by Sun Microsystems
 Initially called "Oak"
 Its objective was to develop a software for embedding in
consumer electronic devices
What is Java?
 An object-oriented programming language
 A cross platform language
 A high level programming language
 Characteristics:
 Simple
 Object-oriented
 Distributed
 Architectural neutral
 High performance
 Robust
JDK, JRE && JVM (1/4)
 JDK:
 A platform-specific software
 A software development kit:
• contains tools for developing Java applications: compiler,
debugger, javadoc, ...

How the Java works


JDK, JRE && JVM (2/4)
 JRE:
 Provides the libraries, the JVM and other components to run
applets and applications
 For only Java program execution, JRE installation is enough

How the Java works


JDK, JRE && JVM (3/4)
 JVM:
 Is an instance of JRE
 Translates bytecode into native machine code
 Manages and organizes memory through Garbage collector

How the Java works


JDK, JRE && JVM (4/4)
How the Java works (1/2)

JVM Window

Java Java
Bytecode
source code compiler

JVM Linux
How the Java works (2/2)

file.java (source code)

Java Compiler
Javac.exe

Platform-Independent
Java byte-code: file.class

Java Runtime Interpreter / Java Virtual


Machine (java.exe)
First Java Program in NetBeans (1/7)
 NetBeans:
 A free and open source integrated development environment
(IDE) for application development on Window, Linux, Mac and
Solaris OS
 Supported programming languages:
• Java, HTML5, PHP, C/C++

https://netbeans.apache.org/front/main/index.html
Download && Install
JDK and NetBeans
 JDK: https://www.oracle.com/java/technologies/javase/
javase8-archive-downloads.html

 Apache NetBeans 8.0: https://taimienphi.vn/download-net-


bean-ide-5221/8.2-phien-ban
First Java Program in NetBeans (2/7)
 This program will show the string “Hello World” to the screen.

 Steps
1. Create a new Java NetBeans project
2. Add a Java class
3. Write code
4. Compile/Run the program
First Java Program in NetBeans (3/7)

1- Create a new Project


First Java Program in NetBeans (4/7)

2- Add a new Class


First Java Program in NetBeans (5/7)

2- Add a new Class-cont


First Java Program in NetBeans (6/7)

3- Write code
First Java Program in NetBeans (7/7)

4- Run program
Basic Object-Oriented
Programming Principles
Outline
 Object-Oriented Programming Principles:
 Object-Oriented Programming (OOP)
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
Object-Oriented Programming (1/2)
 Object-Oriented Programming (OOP):
 A programming paradigm built on the concept of objects
 Each object contains:
• attributes, and behaviors/methods
 Principles of OOP:
• abstraction, encapsulation, inheritance, polymorphism

Name: Hùng
Address: HCM
Bike model: Vario155
Salesman: Mai Anh
--------
Công việc: Lập trình 8h/ngày
Object person
Object-Oriented Programming (2/2)
 Problem:
 Develop a hotel management software

Procedure-oriented Programming Object-Oriented Programming


Abstraction (1/2)
 Abstraction:
 A process of identifying and grouping attributes and actions
related to a particular entity as relevant to the application at
hand
 Advantages:
• Focus on the problem
• Identifies the essential characteristics and actions
Abstraction (2/2)
 Example:
 Identifying and grouping attributes and actions related to
the customer entity in the Bike-sale application

Class name Customer


Attributes  Name of customer
 Adress of customer
 Salesman who sole the bike
 Bike-Model
Actions/Methods  Generate the bill
Encapsulation (1/6)
 Encapsulation:
 A process of binding data (such as attributes and methods)
together in a single entity (Class)
 A combination of Data hiding and Abstraction concepts
• Abstraction: refer to simplifying an entity
• Data hiding: refer to limiting access to data in the class
from other class through the access modifiers

Data
+ Class

Methods
Encapsulation (2/6)
 Class :
 A template in Java that is used to define an entity in terms
of common attributes and actions.
 Defines a new data type (ex: customer)
 Every time an instance of a class is created, an object
is generated
 The object contains its own copy of each attributes defined
by the class

Class Customer
Encapsulation (3/6)
 Object :
Name: Hùng
 An instance of the class
Address: HCM
Bike model: Vario155
Salesman: Mai Anh
Bill-generation: 50$

Instance 1

Class definition Name: Minh


Address: Dak Lak
Bike model: Airblade160
Salesman: Mai Anh
Bill-generation: 55$

Instance 2
Encapsulation (4/6)
 Class && Object:
 Class defines an entity, while an object represent an actual
entity
 Class is a conceptual mode (defines attributes and actions
required of an object), while an object is a real model
 Class is a prototype of an object
 All objects belonging to the same class have the same
attributes and actions
Encapsulation (5/6)
 Advantages:
 Data privacy:
• Limit the access of data existing within a class
• The inner workings of a class hidden from external
entities
 Modularity:
• Set up read-only, write-only, or both mechanisms on
classes based on your specific requirements, selectively.
Encapsulation (6/6)
 Advantages-cont:
 Reusable:
• Reuse your previous Java code in a new context by
combining it with inheritance principles.
 Efficient testing:
• Allows for more efficient testing within a software
application (i.e, unit testing)
Inheritance (1/3)
 Inheritance:
 A mechanism in which one entity (class) acquires all the
attributes and methods of a another class.
 The core idea:
• Allow us to create new classes that are built upon existing
classes

Class name Animal


Attributes  color
Actions/Methods  Eat

Class name Dog Class name Lion


Attributes  owner Attributes  Jungle name
Actions/Methods  Bark Actions/Methods  Roar
Inheritance (2/3)
 Advantages:
 Reusable:
• Reuse your previous Java code in a new context
 Avoiding code duplication:
• Reduce the amount of duplicate code by sharing common
code among multiple derived classes
• Tips: if similar code exits in two related classes, we can
move the common code to a parent class
Inheritance (3/3)
 Advantages-cont:
 Preserves the integrity of parent class:
• Declare a subclass does not affect its parent class's
source code
 Data hiding:
• The parent class can be set to keep some data private so
that it cannot be altered by the derived class
Polymorphism
 Polymorphism (many forms):
 A concept by which we can perform a single action/method in
different ways
 Poly means many, while "morphs" means forms
Java Fundamentals and
Control Structures
Outline
 Analyze the Java Program
 Understand the basic of Java Language
 Format output
Analyze the Java program

 /* … */:

o commented lines

 public class HelloWorld:

o declare a new class called HelloWorld

 public static void main (String []


args):
o main method where the program
begins

 System.out....:

o Display the string "Hello World" on the


screen
Basic of the Java Language
 Keywords and Naming Convention
 Variables
 Data types
 Type casting
 Reference && Pointer
 Operators
 Control structure
Keywords and Naming Convention
 Keywords: Almost keywords are reused from C language
 Naming convention:
Type Convention Example
package • lowercase package calculator
Class • CamelCase format Class CustomerService
• Use Nouns
Interface • CamelCase format Interface Comparable
• Use verb-phase
Variable • Mixed case String firstName
• Use nouns
Methods • Mixed case Void calculatorTax()
• Use verb to describe the goal of method
Constants • Uppercase Static final int HEIGHT
Variable (1/3)
 Variable:
 A container which holds a value while the Java program is
executed

Variable declaration syntax datatype identifier [=value];


Variable (2/3)
 Scope and Lifetime:
 Variables can be declared inside a block
 The block begins with an opening curly brace and ends with
a closing curly brace
 A block defines a scope
 A new scope is created every time a new block is created
 The block also determines the life of an object
Variable (3/3)
 Scope and Lifetime:
 Example:
Data types (1/3)
 Data types:
 Primitive data types:
• Simple non-object data type
• Primitive variable store a actual value

 Reference data types:


• Object data type
• Reference variable store a reference /address of created
object
Data types (2/3)
 Primitive data types:
Type Bytes Minimum Maximum
char 2 \u0000 \uFFFF
byte 1 7
-2 2 -1
7

short 2 -2
15
2 –1
15

int 4 -2
31
2 –1
31

long 8 -2
63
2 -1
63

float 4
double 8
boolean true/false

DataType var [=Initial value] ;


Data types (3/3)
 Reference data types:
 Array for example:
String s=new String("Hello");
 Class
 Interface
Type Casting (1/2)
 Type casting:
 A conversion between primitive data types
 Widening casting(automatically):
• Converting a smaller type to a larger type size
byte short char int long float

 Narrowing casting (manually):


• Converting a larger type to a smaller type size
• Placing the type in parentheses in front of the value

float long int char short byte


Type Casting (2/2)
 Type casting:
 Example:
Reference && Pointer Comparison
Reference in Java Pointer in C
Role A variable that holds the A variable that holds
address of object the address of
another variable
Arithmetic operation No Yes
Location Objects are put on the Objects/struct are put on
heap only the stack
Casting rule Only related objects (same Free casting pointer to
hierarchy) can be cast totally different type
Operators
Category Operators
(Descending Precedence)

Unary ++ -- + - ! ~ (type)
Arithmetic * / %
+ -
Shift << >> >>>
Comparison < <= > >= instanceof
== !=
Bitwise & ^ | They are the same with
Short-circuit && || those in C language
Conditional ?:
Assignment = op=
Control Flow Structure (1/2)
 Decision-making:
 If-else statement
 Switch-case statement

 Loops:
 while loop
 do-while loop
 for-loop
 jump statement
Control Flow Structure (2/2)
An enhanced for loop
Implementation Encapsulation
Outline
 Recall
 Class and Object Implementation
 Concept Package
 Access modifiers
 Case study
Recall
 Encapsulation:
 A process of binding data (such as attributes and methods)
together in a single entity (Class)
 A combination of Data hiding and Abstraction concepts

• Class: Class = Data (attributes) + Methods


How to access
• Data of a class should be hidden from
data?
the outside (other classes).
Getter, Setter • Constructor: A special method that is used
to initialize a new object.
Class && Object Implementation (1/10)

 How to represent a Class?


 UML Diagram
 Example:

Class name Animal


Attributes  Color
 owner
Actions/Methods  Eat

Class name
Animal
Color : String attributes
Owner: String
Eat()
methods
UML Diagram
Class && Object Implementation (2/10)

 Class Implementation

Class implementation in Java


Class && Object Implementation (3/10)

 Constructor:
 Is invoked to create a new object from
the class
 No datatype in the declaration
 The method name is similar to the
class name
 The compiler automatically provides a
no argument, default constructor for
any class without constructor
Class implementation in Java
Class && Object Implementation (4/10)

 Constructor-cont:
 Example:
Class && Object Implementation (5/10)

 Keyword this:
 a reference to the current object

attributes
this
methods

Reference Object
variable
Class && Object Implementation (6/10)

 Methods:
 A block of code is utilized to execute specific actions outlined within it

syntax

 dataType:

• Expected return data type of the method

• Using void if the method does not need to return


Class && Object Implementation (7/10)

 Methods:
 Example:
Class && Object Implementation (8/10)

 How to access attributes?


 Accessing or editing data should be accomplished through
methods
 Specific solution: getters && setters

• Getters: A set of methods, each of which allows getting


the value of an attribute respectively
• Setters: A set of methods, each of which allows setting
the value of an attribute respectively
Class && Object Implementation (9/10)

 How to access attributes?


 Example:
Class && Object Implementation (10/10)

 Creating objects:
 An actual object is created a class template

ClassName obj = new ClassName ()

ClassName obj = new ClassName (params)

 Accessing a attribute of the object: obj.attribute


 Call a method of the object : obj.method()
Demo (1/7)
 In this demonstration (package
point1):
 The class IntPoint1 represents a
point in a two-dimensional coordinate
system

 The class IntPoint1_Use contains


the main method, within which the
class IntPoint1 is utilized
Demo (2/7)

(2) Setup
values

y 0
100 x 0

(1) Memory
allocation

An object variable is a reference p 100


Demo (3/7)
 This demonstration will depict:
 The way to insert some methods
automatically in NetBeans

 If user-defined constructors are


implemented, compiler does not insert
the system default constructor
Demo (4/7)
Insert constructor

Parameter names are the same as those


in declared data filed. So, the keyword
this will help distinguish field name and
parameter name.
this.x means that x of this object
Demo (5/7)
Insert getter/setter
Demo (6/7)
Demo (7/7)
Package in Java (1/2)
 Package
 a namespace that organizes a set of related classes and
interfaces
 Categories:
• Built-in Packages (packages from the Java API):

• User-defined Packages (create your own packages)


Package in Java (2/2)
 Package
 Advantages:
• Categorize the classes and interfaces so that they can be
easily maintained
• Java package provides access protection
• Java package removes naming collision
Package in Java: Demo
• Add a Java
class

If package is used, it must be


the first line in Java code
Access modifiers (1/3)
 Modifier
 Keywords are used to control the visibility of an interface,
class, method, or attribute
 Categories:
• Access modifiers: specifies the accessibility or scope of a
attribute, method, or class
• Private, default, protected, public
• Non-access modifier: change the behavior of a class,
method or attribute
•  final, abstract, static, volatile, …
Access modifiers (2/3)
Order:
public > protected > default > private
Access level
Applied to
Free-accessing public

interface
package/ subclass

protected
class
outside cannot access
private
members of
interface/class
package
no specifier
(default)
Interface is a group of prototyped
methods and they will be
Note: If you don't use any modifier, it is implemented in a class afterward. It
treated as default by default. will be introduced later.
Access modifiers (3/3)
Case Study (1/6)
 Problem:
 A sports car can be available in a variety of colors, featuring
an engine power ranging between 100 HP and 200 HP. It may
come in either a convertible or a standard model. Equipped
with a starter button for the engine and a parking brake, upon
releasing the parking brake and depressing the accelerator, it
moves according to the transmission setting
Case Study (2/6)
 Class design:
Case Study (3/6)
 Using UML diagram to represent the Car class:
Case Study (4/6)
Case Study (5/6)
Case Study (6/6)
Inheritance Implementation
Outline
 Recall
 Basic concepts: super class, subclass
 Syntax of Java Inheritance
 Inheritance types
 Demo
 “Instanceof” Operator
 Casting with Reference Variable
Recall
 Inheritance:
 A mechanism in which one entity (class) acquires all the
attributes and methods of a another class
 The core idea:
• Allow us to create new classes that are built upon existing
classes
Super class, subclass, reusability
 Super class (parent class):
 A class from where a subclass inherits the features.
 Subclass (derived class):
 A class which inherits the other class.
 Reusability:
 In subclass, we can re-use the same attribute and
methods already defined in the parent class
without declaration
 Note:
 Constructor is not inherited
 All classes are inherited from Object class
Syntax of Java Inheritance (1/2)
 Syntax:
Syntax of Java Inheritance (2/2)
 How to re-use constructor from parent class?
 Solution:
 subclass constructor must invoke super-class constructor
by using keyword super
Inheritance Types
 Inheritance types in Java:
 Single inheritance
 Multi-level inheritance
 Hierarchical inheritance

single Multi-level Hierarchical


Demo- Single Inheritance (1/2)
Demo- Single Inheritance (2/2)
“Instanceof” Operator
 instanceof:
 A method to check whether an object is an instance of the
specified type (class, subclass, or interface)
 Notes:

• An object of subclass type is also a type of parent class


Casting with Reference Variables
 Casting types:
 Upcasting:
• Casting from a subclass to a superclass Dog dog = new Dog()
Animal animal = dog ;
• Implicitly performed by the compiler.

 Downcasting:
• Casting from a superclass to a subclass
• Explicitly use a cast operator.

Animal animal = new Animal () ;


Dog dog = (Dog) animal
Polymorphism Implementation
Outline
 Recall
 Overloading && Overriding
 Interface
 Abstract Class
Recall
 Polymorphism:
 A concept by which we can perform a single action/method in
different ways
 Poly means many, while "morphs" means forms

Overloading && Overriding


Overloading
 Overloading:
 A feature that allows the creation of multiple methods in a
class with the same name but different parameters

 overloading with constructors


public Rectangle(){…}
Rectangle public Rectangle(int length, int width){… }
# length: int
# width: int  Overloading also extends to general
+ Rectangle();
methods.
+ Rectangle(int, int) public void setValue(int len){
+ setValue(int): void length= (len>0)?1:0;
+ setValue(int, int): void }
public void setValue (int len, int wi){
length= (len>0)? 1: 0;
width= (wi>0)? wi:0;
}
Overriding
 Overloading:
 A feature that allows the subclasses to modify the
method of parent classes by redefining the methods
defined in the super class
Demo
Overridden method: An inherited method is re-written

Overloaded methods: Methods have the same


name but their parameters are different in a class
Interface (1/2)
 Interface :
 A blueprint (sketch) that is used to implement a class
 It only contains : constants, initialized attributes, static
methods, abstract methods, default methods
 Cannot be instantiated because they can contain abstract
methods
 It can only be implemented by classes or extended by
other interfaces
 Note:
• Multiple inheritance in Java can be achieved through
the use of interfaces
Interface (2/2)
 Syntax:
Interface-Demo (1/4)
 Create an Interface:
Interface-Demo (2/4)
 Implement an Interface:

Output:
set lock in the default method
on TV
off TV
shut down after 10000 seconds
TV remote's price:10
TV Remote has: 20buttons
Interface-Demo (3/4)
 Using multiple Interfaces:

Output:
set lock in the default method
on TV
off TV
shut down after 10000
seconds
TV remote's price:10
TV Remote has: 20buttons
increase volumn
Interface-Demo (4/4)
 Interfaces extends Interface:

Output:
on AC
display Korean
set lock in the default method
Abstract Class (1/2)
 Abstract Class:
 A class that is declared abstract
 It may or may not include abstract methods
 It cannot be instantiated but can be inherited
• The subclass must provides implementations for all abstract.
Otherwise, the subclass must also be declared abstract.
Abstract Class (2/2)
 Syntax:
Abstract Class-Demo (1/3)

Modified
Abstract Class-Demo (2/3)

This class have no abstract method but it is declared as an


abstract class. So, we can not initiate an object of this class.
Abstract Class-Demo (3/3)

Error.
Why?
Wrapper Classes and String
Outline
 Wrapper class
 String , StringBuffer, Stringbuilder
 Scanner Class
 Formatting Output
Wrapper class (1/7)
 Wrapper class:
 Pre-defined classes in Java library
 Provide a way to use primitive data type as objects
• Convert primitive to object
 Each java primitive has a corresponding wrapper class
Wrapper class (2/7)
 Primitive and Corresponding Wrapper Class
Wrapper class (3/7)
 Why Wrapper class?
 Reasons:
 Collections handles only object data
 Object data allow null value
 Serialization
 Safe-thread (wrapper classes are immutable):
• Immutable: the value cannot be changed because
wrapper classes do not provide setters
Wrapper class (4/7)
 Example:
Wrapper class (5/7)
 Example-cont:
Wrapper class (6/7)
 Example-cont:

Some
common
methods

Wrapper
classes are
immutable
(non-
changeable)
because they
do not have
setters
Wrapper class (7/7)
 Data type Conversion?
 Autoboxing:
• Convert a primitive data type into its corresponding
wrapper class:
 ex: byte to Byte , int to Integer
 Unboxing:
• Convert a wrapper type into its corresponding primitive
data type
 ex: Byte to byte , Integer to int
Autoboxing && Unboxing -Demo

obj
x 5 Boxing/auto boxing:
encapsulating/wrapping a
int x= 5;
primitive value to an object.
Integer obj = new Integer(5);
Unboxing: get primitive value
Integer obj2 = new Integer (“123”);
wrapped in a wrapper object.
Strings Class

 String:
 Pre-defined java class to encapsulate strings of characters
 Contains an immutable string
 Almost methods return a new string
 Usage:
String Demo
String Demo
StringBuffer and String Builder Classes

 StringBuffer and StringBuilder:


 Represent strings that can be dynamically modified.
 StringBuffer is threadsafe, while StringBuilder is not
threadsafe.
 Almost of their methods are the same as methods in the
String class.
StringBuffer Demo
Formatting Output (1/2)
Formatting Output (2/2)
Array of Objects
Outline
 What is Array in Java?
 Case Study using Array
Array in Java (1/2)
 Array:
 A container object that holds a fix number of values of a
single type
Array in Java (2/2)
 Basic Operations in Array:
 Print all the array elements (objects)
 Add an object at the given index
 Delete an object at the given index
 Search an object using the given index or by the value
 Update an object at the given index
Case Study (1/4)
 Problem:
 A antique shop that sells antique items, namely vases, stat-
ues and paintings. The owner can add item to inventory. The
shop will keep items in the list. The owner can add a new
item to it, he search also the item,….

Using Array to store and


mange list of objects
Case Study (2/14)
Case Study (3/14)
public class Item
{ // declare fields
protected int value; // the price of a Item (>=0)
protected String creator; // the creator who creates the item( is not empty)
//constructors
public Item(){ value=0; creator=""; }
public Item(int value, String creator){
this.value=value;
this.creator=creator;
}
//getters,setters: you is required to add more code to get/set fields of a Item object
//this method is used to input all fields of a Item object
public void input(){
//use Scanner class to input fields
//use try..catch/throws to handle exceptions
}
//this method returns a string that includes value, creator of a Item object
public String toString(){
//return
}
}
Case Study (4/14)
public class Vase extends Item
{
private int height;//height of a vase (>=0 and <=2000)
private String material;//material of a vase (is not empty)
//TODO: you add more your codes
//constructors
//getter
//setter
//this method is used to input all fields of a Vase object
public void input(){
//use Scanner class to input fields
//use try..catch/throws to handle exceptions
}
//this method returns a string that includes value, creator, height, material of a vase
object
public String toString(){
//return ;
}
}
Case Study (5/14)
public class Statue extends Item
{
private int weight; //the weight of a statue object (weght>=0 and
<=1000)
private String colour; ////the colour of a statue object (is not empty)
//You add more your code
//constructors
//getter
//setter
//this method is used to input all fields of a statue object
public void input(){
//use Scanner class to input fields
//use try..catch/throws to handle exceptions
}
//this method returns a string that includes value, creator, weight, colour of a statue
object
public String toString(){
//return ;
}
}
Case Study (6/14)
public class Painting extends Item
{
private int height; //the height of a painting object (height>=0 and <=2000)
private int width; //the width of a painting object (height>=0 and <=3000)
private boolean isWatercolour; //the painting object use s a watercolor or not
private boolean isFramed; //the painting object has s a frame or not
//You add more your code
//constructors
//getter
//setter
//this method is used to input all fields of a painting object
public void input(){
//use Scanner class to input fields
//use try..catch/throws to handle exceptions
}
//this method returns a string that includes all fields of a painting object
public String toString(){
//return ;
}
}
Case Study (7/14)
public class ItemList
{
Item [] list; // an array to store all items
int numOfItem; // to store the number of items that added to the list
final int MAX=100; // is the size of the array
public ItemList(){
list=new Item[MAX];
numOfItem=0;
}
//this mothod add an Item object to the list
//input: a new item that needs to add
//output: return true/false
public boolean addItem(Item item){
if( item==null || numOfItem>=MAX)
return false;
list[numOfItem]=item;
numOfItem++;
return true;
}
Case Study (8/14)
//this method prints out information of all items
public void displayAll(){
if(numOfItem==0)
System.out.println("the list is empty");
for(int i=0; i< numOfItem; i++){
System.out.println(list[i]);
}
}
//this method finds the item by its creator
//return the item that is found of the first occurrence.
pulic Item findItem(String creator){
for(int i=0; i< numOfItem; i++)
if( list[i].getCreator().equals(creator))
return list[i];
return null;
}
Case Study (9/14)
//this method returns the zero_based index of the first occurrence.
pulic int findItemIndex(String creator){
for(int i=0; i< numOfItem; i++)
if( list[i].getCreator().equals(creator))
return i;
return -1;
}
//this method updates the item at the specified position in this list
//input: the index you wish to update

pulic boolean updateItem(int index){


if( index >= 0 && index < numOfItem){
list[i].input();
return true;
}
return false;
}
Case Study (10/14)
//this method removes the item at the specified position in this list.
//Shifts any subsequent elements to the left
//input: the index you wish to remove
pulic boolean removeItem(int index){
if( index >= 0 && index < numOfItem){
for(int j=index; j< numOfItem; j++ ){
list[j]=list[j+1];
}
numOfItem --;
return true;
}
return false;
}
Case Study (11/14)
//this method prints out all items that belong to the given type in the list.
public void displayItemsByType(String type){

if (type.equals("Vase")){
for(int i=0; i < numOfItem; i++)
if ( list[i] instanceof Vase) System.out.println( list[i]);
}
else if (type.equals("Statue")){
for(int i=0; i < numOfItem; i++)
if ( list[i] instanceof Statue) System.out.println( list[i]);
}
else {
for(int i=0; i < numOfItem; i++)
if ( list[i] instanceof Painting) System.out.println( list[i]);
}
}
Case Study (12/14)
//this method sorts items in ascending order based on their values.
public void sortItems(){
for(int i=0; i< numOfItem; i++)
for(int j=numOfItem-1; j>i ;j--){
if( list[i].getValue()< list[j-1].getValue()){
Item tmp=list[j];
list[j]=list[j-1];
list[j-1]=tmp;
}
}

}//end class
Case Study (13/14)
public class antiqueShop{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int choice=0;
do{
System.out.println("1. add a new vase");
System.out.println("2. add a new statue");
System.out.println("3. add a new painting");
System.out.println("4. display all items");
System.out.println("5. find the items by the creator ");
System.out.println("6. update the item by its index");
System.out.println("7. remove the item by its index");
System.out.println("8. display the list of vase items ");
System.out.println("9. sorts items in ascending order based on their values
");
System.out.println("10. exit");
System.out.println("input your choice:");
choice=sc.nextInt();
switch(choice){
Case Study (14/14)
case 1:
Item tmp=new Vase();
tmp.input();
if(obj.addItem(tmp)){
System.out.println("added");
}
break;
case 2:
…..
break
case 3:
….
break;
…..
}//end switch
} while(choice<=9); //end while
} //end class
Exception Handling
Outline
 exception
 exception handling
 Demo
Exception (1/2)
 Exception:
 In Java, exception is an event that disrupts the normal flow of
the program at runtime.

Exceptions are pre-defined data


(Exception classes) thrown by
JVM and they can be caught by
code in the program
Exception (2/2)
 Exception Types:
 Checked Exception: Exceptions are checked at compile time
(IOException, …).
 Unchecked exceptions: Exceptions are not checked at com-
piletime, but they are checked at runtime (ArimeticException, Ar-
rayOutOfBoundsException, …).
 Error: Error is irrecoverable. Some example of errors are Out-
OfMemoryError, VirtualMachineError, AssertionError etc.
Exception Handling (1/4)
 Exception handling solutions:
 Using try-catch block
 Throws mechanism
Exception Handling (2/4)
 Try-catch block:
Exception Handling (3/4)
 Try-catch block-cont:
Exception Handling (4/4)
 Using throws mechanism:

The throws keyword indicates what exception type may be thrown by


a method.
Exception Handling: Demo (1/3)
Using try…catch to input an integer ,10<=n<=50

public static int inputInteger(){


Scanner in = new Scanner(System.in);
boolean cont = true;
int n;
do {
try {
System.out.print(“Enter a whole number: ");
n = Integer.parseInt(in.nextLine());
cont = false;
} catch (Exception e) {
System.out.println("Required integer!");
}
} while (cont == true|| n<10 || n>50);
return n;
}
public static void main(String[] args){
int n= inputInteger();
System.out.print(“number:” + n);
}
Exception Handling: Demo (2/3)
Using try…catch to input an integer ,10<=n<=50
Exception Handling: Demo (3/3)
Using try…catch to input an integer ,10<=n<=50
Collection
Outline
 Introduction to Collection Framework
 Common Collections:
 List
 Set
 Map
Collection Framework (1/4)
 Collection:
 Java Collections are the one-stop solutions for all the data
manipulation jobs:
• storing data, searching, sorting, insertion, deletion, and
updating of data.
• Java collection responds as a single object

• Collection framework:
• Offer the capability to Collection to represent a group of
objects in Interfaces and Classes
Collection Framework (2/4)

Java framework hierarchy


Collection Framework (3/4)
 Common methods in Collection interface:
Collection Framework (4/4)
 Common Interfaces and Classes:

Central Interfaces Common Used Classes


Store: Dynamic array
Use index to access an
element.

Store: Specific structure/tree


Use iterator to access elements
java.lang.Comparable interface

keySet() Use
values() iterator
Common Collections
 Common collections:
 List
• Collection in which elements are stored in an order manner

• Elements can be duplicated

 Set
• Collection that store distinct elements

 Map
• Collection that store key-value pairs

• Allow fast access to the value based on their corresponding keys


List (1/2)
 List:
 Keeps its elements in the order in which they were added
 Each element in List has an index, starting from 0
 Common methods:
• void add(int index, Object x)
• Object get (int index)
• int index (Object x)
• Object remove (int index)
List (2/2)
 Implemented Classes:
 ArrayList
 Vector (is synchronized)
 LinkedList
List –Demo (1/2)
 ArrayList:
List –Demo (2/2)
 Vector:
Set
 Set:
 Store distinct objects

 Implemented Classes:
 TreeSet:
• Objects are sorted in the ascending order
 HashSet
• Constant time performance for the basic operations: add,
remove, search, …
Set –Demo (1/7)
 TreeSet-cont:
Set –Demo (2/7)
 TreeSet-cont:
Set –Demo (3/7)
 TreeSet-cont:
Set –Demo (4/7)
 TreeSet-cont:
 How to TreeSet ordering objects?
 Solution:
 Provide specific criteria based on one of the object's
attributes

Comparable
Set –Demo (5/7)
 TreeSet-cont:
 How to TreeSet ordering objects?
Set –Demo (6/7)
 HashTable:
 Index of an element is determined by a predefined-function: F

storage with Array/Vector Storage with Hashtable


Set –Demo (7/7)
 HashTable-cont:
Map
 Map:
 Store data in the format <key, value>
 Each key maps to a value
 It does not allow duplicate keys

 Implemented Classes:
 TreeMap:
• Keys are sorted
 HashSet
• Leverage the pre-defined hash-function
Map –Demo
Further Discussion
Why Wrapper Classes are Immutable?
Why Wrapper Classes are Im-
mutable? (1/3)
 Wrapper classes in Java:
 String, Boolean, Character, Byte, Short, Integer, ..

 Why are all wrapper classes kept as immutable?


 Reason: Catching, security, synchronization
Why Wrapper Classes are Immutable
in Java? (2/3)
 Security:
 Since they typically all are widely used in most java
applications (i.e, sensitive pieces of information), se-
curing stored value in wrapper classes is crucial regard-
ing the security of the whole application in general
 Synchronization:
 Being immutable makes Wrapper classes thread safe
since they won’t be changed when accessed from mul-
tiple threads.
Why Wrapper Classes are Immutable
in Java? (3/3)
 Catching:
 The references to the immutable objects can be easily
shared or cached without having to copy or clone them
as their state cannot be changed ever after construc-
tion. -> save heap memory -> increase performance
Parameter Passing Mechanism
Parameter Passing Mechanism
 Parameter passing in Java:
 Passing mechanism: Passed by value
 Datatype of parameters :
• primitive and reference data type
Abstract Class and Interface
Comparison
Interface && Abstract Class
Type
Abstract class Interface
Aspects
Declaration Abstract class ClassName Interface InterfaceName
Can be instantiated? No No
 a mix of methods declared  a mix of methods declared
with or without an with or without an
Methods implementation implementation
 Methods can be set to  All methods are set to
private, protected, … public
Attributes?  Do not need initialized  must be initialized
 share code among related
classes.  unrelated classes would
When to use? implement the interface.
 You want to declare non-
static or non-final fields  multiple inheritance

You might also like