Java Summary
Java Summary
Course Introduction
Outline
I. Instructor Information
V. Academic Policy
Instructor 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, ...
JVM Window
Java Java
Bytecode
source code compiler
JVM Linux
How the Java works (2/2)
Java Compiler
Javac.exe
Platform-Independent
Java byte-code: file.class
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
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)
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
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
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
/* … */:
o commented lines
System.out....:
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
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 name
Animal
Color : String attributes
Owner: String
Eat()
methods
UML Diagram
Class && Object Implementation (2/10)
Class Implementation
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:
Methods:
Example:
Class && Object Implementation (8/10)
Creating objects:
An actual object is created a class template
(2) Setup
values
y 0
100 x 0
(1) Memory
allocation
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
Downcasting:
• Casting from a superclass to a subclass
• Explicitly use a cast operator.
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)
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
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.
• Collection framework:
• Offer the capability to Collection to represent a group of
objects in Interfaces and Classes
Collection Framework (2/4)
keySet() Use
values() iterator
Common Collections
Common collections:
List
• Collection in which elements are stored in an order manner
Set
• Collection that store distinct elements
Map
• Collection that store key-value pairs
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
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, ..