Java Training 2

undefined
undefined
undefined
undefined
undefined
C++
string object is the same
raises exception
generate exception if queue is empty
Object
Java Training
trainer
Ihar Blinou
schedule
9:00 - 16:00
dinner
14:00 - 15:00
contents
main concepts
exceptions
jdbc
xml
collections
multithreading
networking
books
java code conventions
core java
horstman
полный справочник
code complete
java philosophy
eckel
java - промышленное программирование
refactoring to patterns
resources
http://tutorials.jenkov.com
http://java2s.com
features
no functions, only methods
all functions are inline
everything is a class
every language construct in a separate file
there should be no two public classes in one file
static method cannot be virtual
all classes are in package
there is default package
every object is passed via reference
== vs equals
oop principle obtrusion
serialization/deserialization
deep cloning
horstman
case sensitive
str to num
Integer.parseInt
Integer.valueOf
Integer.decode
new Integer
questions
@override and other annotations
code inspections
jlint
pmd
checkstyle
copying objects
why do we need static import?
casting/conversion
classes
interfaces
arrays
constructors are not inherited
??
are arrays serializable?
instanceof vs getClass
code conventions
methods
classes
constants
packages
design patterns
GOF
types
creational
singleton
assumes only one (or limited) instance(s) of specific class
factory
factory creates objects of different
subclasses using similar approach
abstract factory
factory method
builder
builder creates one large object
prototype
structural
composite
used for hierarchical data representation
(fs tree, xml, categories, syntax parser,
matryoshka doll etc)
features
recursive composition
allows treat both individual objects
and their clusters uniformly
examples
fs tree
xml
categories
syntax parser
AST
matryoshka doll
hierarchies
church
military
aristocratic
administrative
genres
art
music
compexity classes
decorator
wrapper is the synonym of decorator
facade
provides interface for the
more complex architecture
flyweight
proxy
bridge
features
run-time binding implementation
hierarchies are being implemented independently
decoupling abstraction from implementation
example
different implementations for different platforms
adapter
matches interfaces of different classes
features
legacy classes have replacements
decorator provides enhanced interface
facade defines new interface
while adapter reuses the old one
behavioral
command
observer/listener
chain of responsibility
iterator
mediator
memento
imitates ctrl+z behavior
often used in a tandem with a command pattern
state
strategy
template method
visitor
GRASP
knowledge classes
action classes
patterns
expert
high cohesion
glaukap ??
examples
http://fluffycat.com
language
errors handling
exceptions
try-catch-finally
finally
used for
db connection close
close files
release other allocated resources
throw
throws
types
checked
throws
Exception
unchecked
RuntimeException
multiple catch blocks
two catches cannot handle exception
catch(Exception e)
deprecated!
redefine constructor in order to
be able passing error message
all exceptions implement interface Throwable
classes
IOException
NullPointerException
ArithmeticException
CloneNotSupportedException
inheritance
subclass methods should throw
subexceptions which overridden
method throws
narrowing approach
subclass constructor should throw all
exceptions (or its parent classes)
parent constructor throws
widening approach
errors
OutOfMemoryError
StackOverflowError
program is allowed to terminate
assertions
assert <condition>:<expression>;
JavaBeans
public contstructor
for possibility of creation via reflection
implements Serializable
private fields
setters/getters
concept
object as a single
information domain
types
base types
boolean
Boolean
booleanValue
parseBoolean
byte
Byte
byteValue
parseByte
char
Character
charValue
----
short
Short
shortValue
parseShort
int
Integer
intValue
parseInt
long
Long
longValue
parseLong
float
Float
floatValue
parseFloat
double
Double
doubleValue
parseDouble
valueOf
primitive
byte
1
short
2
int
4
long
8
float
4
double
default
8
char
2
bool
arithmetic promotion (implicit)
long
char
int
short
byte
float
double
literals
number
int
10
012
0xA
float/double
1.0001
5.3e-3
6.89e-8f
chars
\u0004
'a'
escape sequence
\n
\r
\t
\b
\f
\'
\"
\\
null
boolean
true
false
NaN
variables
types
local
static
instance
comments
javadoc
@
author
version
exception
param
return
deprecated
since
throws
see
...
one line
//
multiline
/* */
operators
relative
!=
>=
>
other
==
&
^
*
|
&&
||
? :
=
arithmetic
+
++
-
--
*
/
%
remainder
logical
bitwise
assignment
flow
switch/case
does not accept long ??
for
while
do
continue
break
advanced
[]
? :
.
()
casting
params list
new
instanceof
returns true for
class
or its subclass
'a instanceof Object' always returns true
except 'null instanceof Object';
oop
constructors
default constructor is used when
explicit constructor is absent
overloading
not always default
constructor is reasonable
constructor is
the class method without return value
are not inherited
inheritance
all methods and fields
are inherited to subclass
logical blocks are not inherited
default class is being Object inherited
fields are not overridden even
though they are being inherited
there might be id field in
both parent and subclass
incapsulation
access modifiers
private
protected
default (private-package)
public
polymorphism
types
static
templates
template methods
overloading
generics
?
dynamic
late binding
overriding
method visibility should be
widened, not narrowed
ability of change reference depending
on the passed object type
polymorphic substitution
static + dynamic = combined polymorphism
sublass reference cannot be
initialized with superclass object
relationships
is-a
has-a
modifiers
abstract
final
static
transient
native
synchronized
volatile
private
public
protected
classes
abstract
inner
1 to 1 classes relationship
used for
unique concept existing only
in the scope of the outer class
compound data types
Enum declarations
outer class cannot see fields
and methods of inner class if
there is no instance
inner class sees all, even private
access to outer class instance
Outer.this.field
subclass of inner class loses
access to the outer class
though subclasses of inner and
outer keep accessibility rules
nested
static inner class
can be created without instantiation of outer class
static keyword before inner class definition
describes instantiation approach. it tells
nothing about fields and methods
new Outer.Inner()
no instance of outer class required
inner classes of interfaces are static by default
can imitate methods implementation
inside the interface
anonymous
example
AnonClass anon = new AnonClass { ... }
inherited from the class where it is defined
often used in enums
in case of abstract method definition in enum
it is required to override it with anon class in each
enum value
it is not allowed to
inherit from enum
interfaces
names
-able
Serializable
-or
Iterator
should represent complex actions
can have details of implementation
can inerit from each other
extends keyword
interfaces parametrization
vs abstract classes
it is useful to parametrize interface
with the abstract class
interface Interface<T extends AbstractClass>
common
cannot create objects
unimplemented methods
difference
class has
fields
methods
constructor
abstract
reasonable when there are
common fields
common methods implementation
single inheritance
can have default implementation
interface
just a list of methods
multiple inheritance
super
super(a, b, c)
super.method()
each constructor of inherited class has
implicit super() call without params
this
this(a, b, c)
chain constructor
this.method()
import
static
import static java.util.Math.*
java.util.* is imported by default
types
numeric
Number
Byte
Short
Integer
Long
BigInteger
BigDecimal
Float
Double
String
immutable
if literal is the same, reference also the same
String s1 = "Java"
String s2 = "Java"
String s3 = "Ja" + "va"
methods
concat
individual chars
charAt
comparison
compareTo
compareToIgnoreCase
equals
equalsIgnoreCase
contentsEqualsTo
substring search
startsWith
endsWith
indexOf
lastIndexOf
substring
extract substring
uppercased string
toUpperCase
lowercase string
toLowerCase
length
replace
trim
toString
valueOf
intern
String s1 = "Java"
String s2 = new String("Java")
s1 == s2 -> false
s2 = s1.intern()
s1 == s2 -> true
isEmpty
added in java 6
format
split
buffers
StringBuffer
modifiable strings
append
insert
reverse
setCharAt
deleteCharAt
setLength
toString
StringBuilder
unsynchronized StringBuffer
hashCode and equals are not
overridden for both classes
Locale class
getCountry
getDisplayCountry
getLanguage
getDisplayLanguage
...
regexes
Pattern class
compile
matches
matcher
split
toString
formatting
numbers
dates
currency
Formatter class
close
flush
format
toString
%[<argumentIndex>$][<flags>][<width>][.<precision>] <type>
types
%b
Boolean
%c
Character
%d
Decimal
%f
Floating point
%s
String
parsing
Scanner class
all related classes are final
arrays
cannot convert into each other
arrays array
references array
definition
{}
enums
generics
?
anonymous type
T
type
can use 'extends' keyword
can not
generic constructor can not be instantiated
be used in static methods
logical blocks
types
default
run on class initialization
static
run on class loading
run only once
methods
variable params
method(String s, int ... k)
method(String ... s)
method(Object ... o)
method(int ... k)
method(1, 2, 3, 4)
method(String[] ... arr)
should be at the end
works with both params list and arrays
autoboxing/unboxing
Integer num = 170
object creation + boxing
Integer k = ++num
unboxing + operation + object creation + boxing
int i = k
unboxing
Integer i = null
int j = i
dynamic comparison
unboxing, comparison, boxing
Float f = new Float("7")
does not work
serialization
implements Serializable
requires serialVersionUID
transient
cannot be serialized
as well as static fields
collections
hierarchy
Map
SortedMap
AbstractMap
TreeMap
HashMap
LinkedHashMap
EnumMap
WeekHashMap
java6
Subtopic 1
IdentityHashMap
allow duplicated keys
System.identityHashCode()
Hashtable
legacy
Collection
List
AbstractCollection
AbstractList
ArrayList
AbstractSequenceList
LinkedList
Vector
legacy
Stack
legacy
AbstractQueue
PriorityQueue
ArrayDeque
AbstractSet
TreeSet
HashSet
LinkedHashSet
EnumSet
Set
NavigableSet
SortedSet
Queue
Deque
ArrayDeque
thread-safety
java 1
all thread-safety
java 2
emerged non thread-safety
methods
Collection
add
addAll
clear
equals
isEmpty
iterator
remove
size
Queue
element
remove
offer
peek
poll
List
indexOf
add
addAll
get
remove
set
subList
LinkedList
addFirst
addLast
getFirst
getLast
removeFirst
removeLast
removeFirstOccurence
removeLastOccurence
Comparator
compare
sort
Comparable
compareTo
TreeSet
first
last
subSet
tailSet
headSet
comparator
EnumSet
noneOf
of
complementOf
range
Map
containsKey
containsValue
entrySet
keySet
get
put
putAll
remove
values
Map.Entry
getKey
getValue
setValue
auxillary interfaces
Iterator<T>
reference to the next element
methods
hasNext
next
remove
Comparator<T>
Map.Entry
Enumeration<T>
legacy
methods
elements
keys
auxillary classes
Collections
legacy
static class with static
methods for actions with
collections
methods
checkedCollection
addAll
copy
disjoint
emptyList
fill
frequency
max
min
nCopies
replaceAll
reverse
rotate
shuffle
singletonMap
sort
swap
Arrays
legacy
class for manipulation with arrays
methods
fill
sort
copyOf
copyOfRange
asList
foreach
is applicable on classes implementing
Iterable interface
TreeSet cannot be parameterized
with StringBuilder or StringBuffer
because those classes do not
have compareTo implemented
how to make java 1.4 collection type-safe?
checkedCollection method
multithreading
application has at least one thread: main
it waits until all spawned
thread will be terminated
class Thread
methods
run
throws InterruptedException
interface Runnable
methods
run
start
thread
states
new
ready/runnable
running
non-runnable
sleeping
time waiting
blocked
state becomes active
on synchronization
waiting
wait
is called on non-runnable thread
stops thread
releases object block
object becomes
available
notify
makes thread ready
notifyAll
all waiting threads are
notified to be ready
it is not recommended to kill/terminate/interrupt
thread from non-runnable state
dead/terminated
class State
priorities
MIN
MAX
NORM
groups
ThreadGroup class
control
yield
join
?
close
daemons
isDaemon
setDaemon
synchronization
thread-safety of
file
object
thread
it is not required for writing/reading
except 64bit platform
semaphors
restrict the number of threads
than can access some
(physical or logical) resource
core
java.util.concurrent.*
ConcurrentHashMap
CopyOnWriteArrayList
Executor
AtomicInteger
AtomicLong
AtomicReference
SynchronizedInt
Semaphore
CyclicBarrier
Exchanger
core
IO
java.io.File class
streams
low-level
FileInputStream
FileOutputStream
ObjectInputStream
ObjectOutputStream
high-level
DataInputStream
DataOutputStream
readers
low-level
FileReader
high-level
BufferedReader
file
socket
readline
writers
low-level
FileWriter
high-level
BufferedWriter
PrintWriter
Random
java.util.Random
Object
clone
class should implement Cloneable interface
if interface is not implemented, then
CloneNotSupportedException will be raised
approach
deep
example is in the book by Horstman
shallow
super.clone()
immutable objects are cloned automatically
hashCode
implementation should try to map object and unique hash code
equals
equals assumes that two equal objects have the same hash codes
Effective Java describes how to violate equivalence criteria
consists of
null check
objects classes check
object casting
object properties null check
object properties comparison
toString
getClass
part of the the reflection mechanizm
finalize
Effective Java describes the way how to halt
the system with finalize overriding
threading
notify
notifyAll
wait
ResourceBundle
Properties
console
System.console()
console.readPassword()
Scanner
zip
jar
jdbc
concepts
result sets
queries
run on the statement instance
CRUD
create
st.executeUpdate("INSERT employee VALUES(" + 13 + "," + "'Aman'" + ")");
retrieve
udpate
delete
example
statements
example
Statement st = connection.createStatement()
types
prepared
PreparedStatement
executeBatch
callable
CallableStatement
for stored procedures
drivers
driver should be
loaded into memory
Class.forName(driverName)
new com.mysql.jdbc.Driver()
metadata
used to work with table and db structure
interfaces
ResultSetMetaData
methods
getColumnCount
getColumnName
getColumnType
DatabaseMetaData
methods
getDatabaseProductName
getDatabaseProductVersion
getDriverName
getUserName
getURL
getTables
example
ResultSetMetaData md = resultSet.getMetaData()
DatabaseMetaData md = connection.getMetaData()
connections
example
Connection.getConnection("jdbc:mysql://localhost:3306/mydb")
uses specific connection syntax
jdbc:[dbtype]://[host]:[port]/[dbname]
surely should be closed
connection creation is really expensive
pools
in connection pools connections are placed
into the list (pool) in order to store expensive
connections and allow users to use them
DAO
Data Access Object pattern
log4j
appender
console
files
gui
jms
sockets
event loggers
syslog
levels
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
rotation
every N hours/days/...
new file is being created
layouts
custom filters
jUnit
test cases
fixtures
@Before
@After
@Test
@BeforeClass
suites
assertions
exceptions handling
@Test(expected=Exception.class)
parameterized test
timeout test
networking
classes
Socket
example
Socket sock = new Socket(host, port)
Socket sock = new ServerSocket(port)
InetAddress
DatagramSocket
auxillary classes usage
BufferedReader
InputStreamReader
PrintStream
tasks
lesson 1
chapter 3,4
implementation of factory and/or command
lesson 3
composite + builder
bridge
composite + bridge
lesson 4
ResourceBundle
lesson 5
implement some specific domain
airplanes
books
musicshop
...
entity classes with code conventions
use DB
connection pool
data source
add functionality of filtration/search
and adding/deletion to the db
collections + generics
patterns
DAO
Command
Memento
View/Controller
Factory
Singleton
...
resource bundle
db properties
log4j
junit
multithreading
command line interaction
virtual machine
garbage collector
System.gc()
Runtime.getRuntime().gc()
System.runFinalization()
XML
xerces
org.w3c.*
org.xml.*
BookLibrary application
0.x.1
factory pattern
singleton pattern
command pattern
0.x.2
patterns
factory
singleton
command
memento
dao
composite
usage
db
filtration
by title
by id
resource bundle
collections
arraylist
enum
0.x.3
improvements
add some pattern
bridge
builder
strategy
listener
add interactivity
vim-like input
modify factory to create
instances of proper classes
logger
56 1