Learning Java: in II Days
Learning Java: in II Days
in II days
Training Course Out-Line
Learning Java
Training Course Out-Line
Prerequisites
Tools
Application Server
Sun Java Glassfish v2.1.1
Database
MySql version 5
IDE
NetBeans IDE 6.8 (Sun Micro System corp.)
Other
Java SDK 1.6
Jconnector
Learning Java
Training Course Out-Line
Learning Java
Training Course Out-Line
Java
modifiers
OOP
Operators, Variable Types, Control Flow Statements
(Exception Handler)
section
Basic Java Programming
Java
Learning Java
Training Course Out-Line
object methods
public class TestDog {
public static void main(String args[]) {
// create new object
Dog mydog = new Dog(bangkaew);
// bark
System.out.println(mydog.bark());
Learning Java
Training Course Out-Line
Same Class
Same Package
Subclass
Other packages
public
protected
Not define
private
class Dog {
private String species;
// data_member color protected
protected String color;
// constructor
public Dog(String species) {
this.species = species;
}
public String bark() {
return bog bog;
}
// method color
public String getColor() {
return color;
}
// method color
public void setColor(String color) {
this.color = color;
}
Learning Java
Training Course Out-Line
1.3.1. Encapsulation
1.3.2. Inheritance
extends
Example
public class SuperDog extends Dog {
// methods
public void speak(String message) {
System.out.println(The SuperDog speaks + message);
}
Object
Learning Java
Training Course Out-Line
1.3.3. Polymorphism
Overloaded Methods
// Overloaded methods
public void speak(String message, int count) {
for (int i=0 ; i<count ; i++) {
System.out.println(The SuperDog speaks +
message);
}
}
Overridden Methods
Java
runtime
Learning Java
Training Course Out-Line
dog
sawaddee
hello
bnojour
Learning Java
Training Course Out-Line
Interfaces methods
Example
public interface Working
{
public void work();
}
work() implement
interface class implements .
Example
public class WorkingDog extends Dog implements Working {
public WorkingDog(String species) {
super(species);
// use parent constructor
}
10
Learning Java
Training Course Out-Line
internet
Abstract Interface
Abstract Interface
( extends implements )
?
Interface java
code
java code
Abstract class
extend abstract class code
11
Learning Java
Training Course Out-Line
interface IBoxing {
string Fight(IBoxing enemy);
}
class Fighter implements IBoxing {
string Fight(IBoxing enemy) { ... } // implement iboxing
}
class Tounament {
void Fight(IBoxing a, IBoxing B) { // parameter interface type
a.Fight(B);
}
}
12
Learning Java
Training Course Out-Line
1.5. Constants
constants
keyword final
data, method class
1.5.1) Final classes
Final methods
public class MyClass {
public final double PI = 3.141592653589793;
[...]
}
13
Learning Java
Training Course Out-Line
1.6. Static
Static variables
static
object class
static instance object
instance
public class MyClass {
static int number;
[...]
}
Static methods
14
Learning Java
Training Course Out-Line
1.7. comment
code 2
//
public class MyClass {
static int myStaticMethod() {
//
int x = 10; //
}
}
/* */
public class MyClass {
/**
*
* 2
*/
static int myStaticMethod() {...}
}
15
Learning Java
Training Course Out-Line
1.8) Operators
Summary of Operators
The following quick reference summarizes the operators supported by
the Java programming language.
Simple Assignment Operator
=
Arithmetic Operators
+
*
/
%
Unary Operators
+
Unary plus operator; indicates positive value (numbers are
positive without this, however)
Unary minus operator; negates an expression
++
Increment operator; increments a value by 1
-Decrement operator; decrements a value by 1
!
Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators
==
!=
>
>=
<
<=
Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Conditional Operators
&&
||
?:
Conditional-AND
Conditional-OR
Ternary (shorthand for if-then-else statement)
16
Learning Java
Training Course Out-Line
1.9) Variables
1.9.1) Primitive Data Types
Java 8
Type
byte
short
int
long
float
double
boolean
char
Size (bits)
Default
8
0
16
0
32
0
64
0L
32
0.0f
64
0.0d
1
false
16 (Unicode Characters)
\u0000
Fig 2. Primitive Data Types
1.9.2) Arrays
int []arry1 = {1, 2, 3, 4, 5};
array
int []anArray;
anArray = new int[10];
array
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}};
17
Learning Java
Training Course Out-Line
1.10) Enumerate
Variable Enumerate
Example
enumerate
property ID
public enum EVENT_TYPE {
SERVICE(1),
LINK(2),
SUBSCRIBER(4),
SMS(8),
WAP(16),
MMS(32),
BLOCK_LIST(64),
REPORT_DAILY(128),
REPORT_SUMMARY(256),
REPORT_MONTHLY(512),
REPORT_SMSDOWNLOAD(1024),
LOG_IN(2048),
LOT_OUT(4096);
private final int id;
EVENT_TYPE(final int id) {
this.id = id;
}
public int getId() {
return id;
}
public static EVENT_TYPE fromId(final int id) {
for (EVENT_TYPE e : EVENT_TYPE.values()) {
if (e.id == id) {
return e;
}
}
return null;
}
}
public enum EVENT_ACTION {
NONE(0),
ADD(1),
DELETE(2),
MODIFY(4),
SEARCH(8),
EXPORT(16),
IMPORT(32);
private final int id;
EVENT_ACTION(final int id) {
this.id = id;
}
public int getId() {
18
Learning Java
Training Course Out-Line
}
return id;
19
Learning Java
Training Course Out-Line
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");
}
}
1.11.3) Loop statements
1.11.3.1) while-do & do-while
20
Learning Java
Training Course Out-Line
while-do
while (conditions-to-do){
// your code goes here
}
do {
statement(s)
} while (conditions-to-do);
21
Learning Java
Training Course Out-Line
1.12.1) try-catch
try/catch statement code handle error
try {
// statements
} catch (exception-classname variable-name) {
// to do something to handle the exception
}
1.12.2) try-catch-finally
keyword finally
statements
transactions database /
finally
try {
// open file
} catch (exception-classname variable-name) {
// to do something to handle the exception
} finally {
// close file
}
22
Learning Java
Training Course Out-Line
}
// do other actions
keyword throw
method
void applyBrakes() throws Exception {
try {
if (isMoving){
currentSpeed--; // slow down speed
}
} catch (Exception e) {
throw e;
}
}
23
Learning Java
Training Course Out-Line
Q&A
24
Learning Java
Training Course Out-Line
25
Learning Java
Training Course Out-Line
A
A
D
D
E
E
C
C
B
B
:
:
:
:
:
:
:
:
:
:
enter f()
leaving f()
enter f()
leaving f()
enter f()
leaving f()
enter f()
leaving f()
enter f()
leaving f()
26
Learning Java
Training Course Out-Line
Array
Java
Collections
Collections
implement
Collections
Collections 3 Set, List Queue
Collections variable Map
27
Learning Java
Training Course Out-Line
2.2.1) Set
(unique)
Example
// Create the set
Set set = new HashSet();
// Add elements to the set
set.add("a");
set.add("b");
set.add("c");
// Remove elements from the set
set.remove("c");
// Get number of elements in set
int size = set.size();
// 2
// Adding an element that already exists in the set has no effect
set.add("a");
size = set.size();
// 2
// Determining if an element is in the set
boolean b = set.contains("a"); // true
b = set.contains("c");
// false
// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
}
28
Learning Java
Training Course Out-Line
2.2.2) List
index
Example
// Create the list
List list = new LinkedList();
list = new ArrayList();
array
// Doubly-linked list
// List implemented as growable
29
Learning Java
Training Course Out-Line
Example
// Create the queue
Queue queue = new LinkedList();
// Using the add method to add items.
// Should anything go wrong an exception will be thrown.
queue.add("a");
queue.add("b");
//Using the offer method to add items.
//Should anything go wrong it will just return false
queue.offer("c");
queue.offer("d");
//Removing the first item from the queue.
//If the queue is empty a java.util.NoSuchElementException will be thrown.
System.out.println("remove: " + queue.remove());
//Checking what item is first in line without removing it
//If the queue is empty a java.util.NoSuchElementException will be thrown.
System.out.println("element: " + queue.element());
//Removing the first item from the queue.
//If the queue is empty the method just returns false.
System.out.println("peek: " + queue.peek());
//Checking what item is first in line without removing it
//If the queue is empty a null value will be returned.
String tmp = null;
while ((tmp = (String) queue.poll()) != null) {
System.out.println("poll: " + tmp);
}
30
Learning Java
Training Course Out-Line
2.2.4) Map
Example
HashMap hm = new HashMap();
hm.put("Somchai", new Double(3434.34));
hm.put("Manee", new Double(123.22));
hm.put("Pusin", new Double(1200.34));
hm.put("Thana", new Double(99.34));
hm.put("Kasin", new Double(-19.34));
Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : " + me.getValue());
}
//deposit into Somchai's Account
double balance = ((Double) hm.get("Somchai")).doubleValue();
hm.put("Somchai", new Double(balance + 1000));
System.out.println("Somchai new balance : " + hm.get("Somchai"));
31
Learning Java
Training Course Out-Line
Example
import java.sql.*;
public class getmySQLConnection
{
public static void main(String[] args)
{
DB db = new DB();
Connection conn=db.dbConnect(
"jdbc:mysql://localhost:3306/test", "test", "passwo
rd");
}
}
class DB
{
tance();
(
public DB() {}
public Connection dbConnect(String db_connect_string,
String db_userid, String db_password)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newIns
Connection conn = DriverManager.getConnection
db_connect_string, db_userid, db_password);
System.out.println("connected");
return conn;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
32
Learning Java
Training Course Out-Line
};
33
Learning Java
Training Course Out-Line
web application
connection
1. resource memory transaction
2. connection connection
DBCP
connection pool
pool
connection
DBCP class DBPoolManager
open source apply
XML config config
connect Database Mysql, MSSql, Oracle, etc.
DBCP
Example
1. XML configuration
<Glassfish_Domain>/conf/dbcp_test.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<dbDriverName>com.mysql.jdbc.Driver</dbDriverName>
<dbUser>test</dbUser>
<dbPassword>password</dbPassword>
<dbURI><![CDATA[jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEn
coding=UTF8&autoReconnect=true&zeroDateTimeBehavior=convertToNull]]></dbURI>
<dbPoolMinSize>10</dbPoolMinSize>
<dbPoolMaxSize>30</dbPoolMaxSize>
</config>
DBCP
34
Learning Java
Training Course Out-Line
2.4) Caching
database overhead
caching
callcenter
memory
memory
Example
public class ObjectFactory {
protected List<Object> objectList;
static int MAX_POOL_SIZE = 100;
static float FACTOR = 0.75f;
// shared cache memory
static
static Hashtable objectFactory
= new Hashtable(MAX_POOL_SIZE, FACTOR);
// method
public static Object getMessage(int id) throws Exception {
Object object = null;
//
cache DB
if (!objectFactory.containsKey(id)
|| (object = objectFactory.get(id)) == null) {
System.out.println("caching, object " + id);
object = new LoadFromDB(id);
//
cache
if (objectFactory.size() > (MAX_POOL_SIZE * FACTOR)) {
removeOlder(MAX_POOL_SIZE / 2);
}
if (objectFactory.containsKey(id)) {
objectFactory.remove(id);
}
objectFactory.put(id, object);
}
return object;
35
Learning Java
Training Course Out-Line
}
36
Learning Java
Training Course Out-Line
2.5) Timer
Timer Schedule
Example
// stateless EJB class timer
public class TimerScheduleLearningJavaDemo implements
TimerScheduleLearningJavaDemoRemote {
@Resource
TimerService timerService;
// trigger
enum TimedEvent {
EVERY_7_SECONDS(7 * 1000, 0),
EVERY_8_SECONDS(8 * 1000, 0),
EVERY_9_SECONDS(9 * 1000, 0),
EVERY_10_SECONDS(10 * 1000, 0),
EVERY_11_SECONDS(11 * 1000, 0),
EVERY_12_SECONDS(12 * 1000, 0),
EVERY_13_SECONDS(13 * 1000, 0),
EVERY_14_SECONDS(14 * 1000, 0),
HOURLY(3600 * 1000, 0),
DAILY(24 * 3600 * 1000, 4 * 3600 * 1000),
WEEKLY(7 * 24 * 3600 * 1000, 4 * 3600 * 1000),
MONTHLY(1000, 0);
final long interval;
final long offset;
private TimedEvent(long interval, long offset) {
this.interval = interval;
this.offset = offset;
}
public long getInterval() {
return interval;
}
// initialize timer
public void scheduleTimers() {
// timer
Learning Java
Training Course Out-Line
te);
}
@Timeout
public void timerFired(Timer timer) {
TimedEvent evt = (TimedEvent) timer.getInfo();
try {
// TimedEvent
switch (evt) {
case EVERY_7_SECONDS:
case EVERY_8_SECONDS:
case EVERY_9_SECONDS:
case EVERY_10_SECONDS:
case EVERY_11_SECONDS:
case EVERY_12_SECONDS:
case EVERY_13_SECONDS:
case EVERY_14_SECONDS:
// to do something on this trigger
System.out.println(evt);
break;
case HOURLY: // do stuff we do every hour
System.out.println("timer hourly.");
break;
case DAILY: // do stuff we do every day at midnight
System.out.println("timer daily.");
break;
case WEEKLY: // do stuff we do every week
System.out.println("timer weekly.");
break;
case MONTHLY: // Have to manually schedule the next
one, months are not fixed length
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.set(Calendar.HOUR, 4);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, 1);
timerService.createTimer(cal.getTime(), evt);
}
} finally {
System.out.println("timer monthly.");
break;
38
Learning Java
Training Course Out-Line
// timer
timerService.createTimer(evt.interval + evt.offset, evt);
}
}
TimerSchedule class deploy application
process
context listener servlet
Example
1. package LearningJavaDemoApp-war -> Source Packages
2. new -> Web Application Listener Context Listener
3. Alt+Insert lookup stateless EJB
TimerScheduleLearningJavaDemoRemote
4. implement code contextInitialized(...)
public class init implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
// initialize timer schedule
lookupTimerScheduleLearningJavaDemoRemote().scheduleTimers();
}
public void contextDestroyed(ServletContextEvent sce) {
throw new UnsupportedOperationException("Not supported
yet.");
}
private TimerScheduleLearningJavaDemoRemote
lookupTimerScheduleLearningJavaDemoRemote() {
try {
Context c = new InitialContext();
return (TimerScheduleLearningJavaDemoRemote)
c.lookup("java:comp/env/TimerScheduleLearningJavaDemo");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE,
"exception caught", ne);
throw new RuntimeException(ne);
}
}
}
39
Learning Java
Training Course Out-Line
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
40
Learning Java
Training Course Out-Line
41
Learning Java
Training Course Out-Line
42
Learning Java
Training Course Out-Line
2.8.1) Unmarshaller
XML
1. class netbeans package project build
.jar
2. import .jar library modules method
function XML XML
Example
pubic void unmarshalXml(String data) throws JAXBException {
com.java.training.xml.request.XML xml = null;
try {
JAXBContext jc =
JAXBContext.newInstance("com.java.training.xml.request");
// create an Unmarshaller
Unmarshaller u = jc.createUnmarshaller();
// unmarshal a news instance document into a tree of Java content
xml = (com.java.training.xml.request.XML)
u.unmarshal(new StreamSource(new StringReader(data)));
// print out details of xml
...
} catch (JAXBException e) {
throw new e;
}
}
43
Learning Java
Training Course Out-Line
2.8.2) Marshaller
XML JAXB
Example
import com.java.training.xml.request.XML;
public void main(String args[]) {
try {
XML xml = new XML();
xml.setUSERNAME((user);
xml.setPASSWORD((password);
xml.setCOMMAND(command);
xml.setMESSAGEID(msgid);
xml.setOPERATORID(1);
xml.setSERVICENUMBER(1234);
xml.setPACKAGEID(pkgid);
xml.setCHANNEL(1);
xml.setMSISDN(66844678748);
xml.setMESSAGE(Hello);
xml.setTIMESTAMP(DatetimeUtil.print());
xml.setSTATUSCODE(2);
xml.setSTATUSTEXT(SUCCESS);
StringWriter sw = new StringWriter();
JAXBContext jc =
JAXBContext.newInstance("com.java.training.xml.request ");
Marshaller m = jc.createMarshaller();
m.marshal(xml, sw);
System.out.println(sw.getBuffer().toString());
} catch (Exception e) {
e.printStackTrace();
}
44
Learning Java
Training Course Out-Line
os.write(OK);
} finally {
os.close();
}
45
Learning Java
Training Course Out-Line
46
Learning Java
Training Course Out-Line
47
Learning Java
Training Course Out-Line
48
Learning Java
Training Course Out-Line
-
49