Rocking on Java
Vo Minh Tam
vo.mita.ov@gmail.com
Intro
Objective
Understand OOP Review all features of Java language Get you out of confusion Update latest changes in Java (since 1.5) How to make your code more beautiful
Requirement
Understand OOP Have a little knowledge with Java
pg. 2
Outline
Java Basics Java Advanced Code Convention Performance Tips Design Pattern
pg. 3
Java Basics
Outline
Java Basics
A little history Features OOP Exception Handling Collection Thread GUI & IO & Networking & Database
Java Advanced Code Convention Performance Tips Design Pattern
pg. 5
A little history
1991 James Gosling Oak Java Star 7: a personal hand-held remote control Includes
J2EE J2SE J2ME
pg. 6
Features
JVM
Bytecode
Garbage Collection Code Security
Class Loader Bytecode verifier
pg. 7
Java Basics
OOP
Class and Object Abstract class and interface Encapsulation Inheritance Polymorphism Overload
characterized by their properties and behaviors
pg. 8
Java Basics
OOP
Abstract class and interface
Same
Derived class must implement all abstract methods Cannot create instances by using new operators The purpose in POLYMORPHISM
Difference from abstract class
[I] Have multiple interface in one class [I] CANNOT include nonabstract method [I] Interface is NOT designed to be superclass. Interface is designed to add some behaviors to a class.
A relationship between class/abstract class and class is a strong relationship. It is known as IS-A relationship. A relationship between class and interface is a weak relationship. It is known as Is-kind-of relationship.
pg. 9
Java Basics
OOP
Inheritance
Super and sub class Object members Constructor Calling Chain Override
instance methods static methods hiding methods
Casting Final class and method
pg. 10
Java Basics
OOP
Polymorphism
Ph.D Nguyen Hua Phung, Dept of CSE pg. 11
Unified Modeling Language (UML) class diagram
abstract
0..*
association (using)
1
static
inheritance (is a)
private
Java Basics
Exception Handling
Error vs. Exception
Immediate subclasses of Throwable
Error Exception
(1) Generally beyond the control of user programs
Out of memory errors Hard disk crash
(2) Usually the result of some flaws in the user program code
Checked Exception vs. Unchecked Exception
pg. 13
Java Basics
Exception Handling
Error vs. Exception Checked Exception vs. Unchecked Exception
Common unchecked exception
NullPointerException ArithmetrictException IllegalArgumentException IllegalStateException UnsupportedOperationException AssertionError
pg. 14
Java Basics
Exception Handling
pg. 15
Java Basics
Collection
pg. 16
Java Basics
Collection
Normal Array vs. List Vector vs. ArrayList Traversing
pg. 17
Java Advanced
Outline
Java Basics Java Advanced
Scanner printf Autoboxing Enumerated Types Foreach loop Generic Types
Code Convention Performance Tips Design Pattern
pg. 19
Java 1.0
8 packages 212 classes
Java 1.1
23 packages 504 classes
Java 1.2
59 packages 1520 classes
Java 1.3
77 packages 1595 classes
Java 1.4
103 packages 2175 classes Regular Exp Logging Assertions NIO
Java 1.5
131 packages 2656 classes javax.activity, javax. management
New Events Inner class Object Serialization Jar Files International Reflection JDBC RMI
JFC/Swing Drag and Drop Java2D CORBA
JNDI Java Sound Timer
java.nio, javax.imageio, javax.net, javax.print, javax.security, org.w3c javax.naming, javax.sound, javax.transaction
javax.accessibility, javax.swing, org.omg
java.math, java.rmi, java.security, java.sql, java.text, java.beans java.applet, java.awt, java.io, java.lang, java.net, java.util
Other New Features
Static import:
import static java.Math.*;
Variable length argument lists. Semaphores Metadata
pg. 21
java.util.Scanner
Initialize
Scanner stdin = Scanner.create(System.in); Scanner stdin = new Scanner();
Read from keyboard
nextXXX() hasNextXXX()
InputTest.java pg. 22
printf method
Similar to C style printf Handles
strings native types numeric types java.util.Date
See java.util.Formatter for details
OutputTest.java pg. 23
Autoboxing/Unboxing
Wrap ints into Integers Extract ints from Integers
Automatically
Notice
NullPointerException with wrapper class Inmutability
This is now legal: Integer x = 6; Integer y = 2*x + 3;
//6 is boxed //x is unboxed, 15 is boxed
AutoBoxTest.java pg. 24
Object Only Performance
int x = 6; int y = 2*x;
Code: 0: bipush 2: istore_1 3: iconst_2 4: iload_1 5: imul 6: istore_2 6
pg. 25
Object Only Performance
Integer x = 6; Integer y = 2*x;
Code: 0: bipush 6 2: invokestatic 5: astore_1 6: iconst_2 7: aload_1 8: invokevirtual 11: 12: 15:
#2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
#3; //Method java/lang/Integer.intValue:()I
imul invokestatic astore_2
#2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
pg. 26
Object Only Performance
Integer x = Integer.valueOf(6); Integer y = Integer.valueOf(2 * x.IntValue); Generates the same byte code.
EnumTest.java & EnumAdvanceTest.java pg. 27
Type-safe enum
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } //used Day today = Day.WEDNESDAY; switch(today){ case SUNDAY: break; // }
EnumTest.java & EnumAdvanceTest.java pg. 28
More Complex Enum
enum Suit { CLUBS(Color.BLACK), DIAMONDS(Color.RED), HEARTS(Color.RED), SPADES(Color.BLACK); private Color color; Suit(Color color) { this.color = color; } public Color getColor() { return color; } }
EnumTest.java & EnumAdvanceTest.java pg. 29
Generics
ArrayList<Number> list = new ArrayList<Number>(); list.add(new Integer(5)); list.add(6); list.add(new Double(3.14159/2)); list.add(new BigInteger("123456789012301234567890") ); list.add(new Long(127L)); Number n = list.get(i);
GenericUseTest.java pg. 30
Defining Generics
public class GenericStack<T> implements Iterable<T> { private T[] data; public GenericStack() { data = (T[])new Object[MIN_SIZE]; } public T pop(){ } public void push(T item) { } public Iterator<T> iterator(){ } //since it is iterable }
pg. 31
Defining Generic Iterator
//inner class of GenericStack private class GenericStackIterator implements Iterator<T> { int index; GenericStackTestIterator() { index = top; } public boolean hasNext() { return index >= 0; } public T next() { if(index < 0) { throw new java.util.NoSuchElementException(); } T item = data[index]; index--; return item; } public void remove() { throw new UnsupportedOperationException( ) } }
pg. 32
For each loop (arrays)
double[] array = {2.5, 5.2, 7.9, 4.3, 2.0}; for(double d: array) { System.out.println(d); } Iterate (forward) through the array without paying attention to indices.
ForLoopTest.java pg. 33
For each loop (Collections)
ArrayList<Integer> list = new ArrayList<Integer>(); list.add(7); list.add(15); list.add(-67); for(Integer number: list){ System.out.println(number); }
pg. 34
For each loop enums
for( Suit s: Suit.values()){ System.out.println(s.getColor()); } values() returns an Iterator for enum types
pg. 35
Code Convention
Outline
Java Basics Java Advanced Code Convention
Class, Variable, Method Exception Handling Comment Naming
Performance Tips Design Pattern
pg. 37
Programming Style Guidelines
80% of the lifetime cost of a piece of software goes to maintenance. Hardly any software is maintained for its whole life by the original author. Code conventions improve the readability of the software, allowing programmers to understand new code more quickly and thoroughly. If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.
pg. 38
Programming Style Guidelines
http://www.3cardbragrules.com/solutions/index-quality.html pg. 39
Code Convention
Class
Class Well-organized in package name MicroarrayData
layout: Layout R: double[][] G: double[][] Rb: double[][] Gb: double[][] nbrOfSlides(): int nbrOfSpots(): int swapDyes(...) append() as.data.frame(): data.frame getLayout(): Layout setLayout(layout) subtractBackground(...) normalizeWithinSlide(...) normalizeAcrossSlides(...) plot(...) plotSpatial(...) boxplot(...) hist(...) static read(...): MicroarrayData write(...)
Classes should be declared in individual files with the file name Fields matching the class name Avoid God classes -> remember Single Responsibility Principle Fields
Class (static) variables Instance variables
public class variables Methods protected package level (no access modier) private
Methods
These methods should be grouped by functionality rather than by scope or accessibility
pg. 40
Code Convention
Variable Minimize
the scope the visibility the mutability
One variable per declaration Initialize local variables where they are declared Use generics-version of a type instead of its raw type when possible
pg. 41
Code Convention
Methods
only one job Avoid methods which have more than 30 lines of code Public methods must validate their input arguments Avoid writing methods accepting any more than 5 parameters -> wrap them DRY (Dont Repeat Yourself) Return empty collection instead of null
pg. 42
Code Convention
Exception Handling
Do not use status code to communicate error conditions Never declare an empty catch block Only use the finally block to release resources from a try statement Catch with specific exception first Catch as lately as possible
pg. 43
Code Convention
Comments Single line comment
// TODO, // HACK
Block comment Special Javadoc comment
/***/ Generate an HTML documentation Popular tags
@author @version @param @return @throws @see @since @deprecated
Advices
Remove unused code
http://javaworkshop.sourceforge.net/chapter4.html
pg. 44
Code Convention
Naming Naming rules:
Must consist of only letters, digits, _ and $ Cannot start with a number Cannot use Java reserved words
Naming Conventions:
Package names are all lower cases Class names are capitalized with each new word capitalized Variable names have lower case letter, new words are separated by _ or start with a capital letter (except for the first) Methods starts with verbs in camel case
E.g.: getLayout(), normalize(method, slides)
Constants are all in upper case
pg. 45
Code Convention
Naming Naming advices Names should be short but meaningful
e.g. nbrOfGrids (or ngrids) is much better than ngr
Use nouns for names of interfaces, enums, delegates, classes and variables. Not use identifiers such as String, System, out, etc are not reserved words and could be used Use as English rules Consider prefix Boolean variables and properties with can, is or has
pg. 46
Code Convention
Style good programming style means that your program is readable
pg. 47
Code Convention
Style good programming style means that your program is readable Blank lines between
Instructions Functional block
Writing multiple instructions on one line Separating an instruction onto multiple lines Adding spaces between words Declare array type Use one and only one statement per line.
pg. 48
Code Convention
Indentation
Block section
Indent with tab character (4 characters) if else, while, do, try catch Do not nest code any more than 3 levels of depth
Line
Not excess 80 characters each line
70 characters for documentation
Wrapping Lines
Break after a comma. Break before an operator.
pg. 49
Code Convention
Declarations One declaration per line is recommended since it encourages commenting initialize local variables where theyre declared Placement
pg. 50
Code Convention
Other
String
StringBuilder > StringBuffer > String concatenation
enum Use enum types instead of constants when possible
for: Use foreach-style loop instead of for loop when possible switch:
include default case Do not use magic number
Do not miss access modifier Avoid boxing and unboxing value types Use prefix in UI components
pg. 51
Performance Tips
Performance Tips
pg. 53
Performance Tips
Prefer static final Perfer static method Avoid getter and setter Use exact type when creating new object ArrayList<String> a = new ArrayList<String>() > List<String a = new ArrayList<String>() Avoid Creating Objects -> Try to reuse
Use Object Pool
pg. 54
Performance Tips
Avoid use Collection, use native array Avoid Enums Where You Only Need Ints
public enum Shrubbery { GROUND, CRAWLING, HANGING } Use public static final int instead
Use Floating-Point Carefully
Use double instead of float Reduce divide and modulo
Know And Use The Libraries
Use System.arraycopy, String.indexOf
pg. 55
Questions?
pg. 56
References
J2SE Sang Shin course Code Convention Document from SUN Microsystems KMS Code Convention Buu Nguyen, Duy Lam http://www.jpct.net/wiki/index.php/Performance _tips_for_Android http://d.android.com/guide/practices/design/p erformance.html Calvin Austin. J2SE 1.5 in a Nutshell. http://java.sun.com/developer/technicalArticles /releases/j2se15
pg. 57