Please enable JavaScript.
Coggle requires JavaScript to display documents.
java (Class (Constructor (about parameter (default: don't have custom…
java
Class
class classname {
// declare instance variables
type var1;
// ...
// declare methods
type method1(parameters) {
// body of method
}
}
Objet: instance of class
Init: Class_name a = new Class_name()
object1 = object2
obect1 and object2 refer to same object
Method:
ret-type name( parameter-list ) {
// body of method
}
Constructor
same name class
dont have value return
about parameter
default: don't have
custom: have one or more parameters
garbage collection
reclaims objects automatically
work principle:
When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by
the object is released. This recycled memory can then be used for a subsequent allocation.
finalize method
ensure that an
object terminates cleanly
finalize be called before garbage collection work
Access modifier
Private
Public
Protected
Arguments Passed
Primitive variable: call-by-value
Object variable: call-by-reference
Method Overloading
Same name method
Differ: type return, parameters
Keyword
static
accessed before any objects of its class are created,
and without reference to any object
When an object is declared,
no copy of a static variable is made
static block
A static block is executed
when the class is first loaded
Variable length arguments
A variable-length argument is specified by three periods (...)
the varargs parameter must be last
Example:
static void vaTest(int ... v) {
//bla bla
}
Inheritance
Using keyword
EXTENDS
inheritancing class
class subclass-name extends superclass-name {
// body of class
}
Call SuperClass Constructor
super(parameter-list);
Multilevel Hierarchy
class A
class B extends class A
class C extends class B
Constructor executed
B extends A
C extends B
Executed:
A -> B -> C
super reference subclass
superObj = subObj
but error happened
superObj.b = value (b is variable of subObj)
Override method
Example:
A has method print();
B extends A and override method print();
Khi execute obj B and call method print()
method print in B will execute
B: method print() call super()
-> call method print() in class A
Abstract method
abstract type name(parameter-list);
keyword
FINAL
method final:
Prevent override method from subclass
class final :
prevent inherit from other class
variable final:
be inherited by subclass
accessed directly inside those subclasses
parameter final:
prevents it from being changed within the method
Generics
one class has generic type parameter
Use type parameter muse be reference type
Cannot primitive type
General Form
class class-name<type-param-list> { // ...
class-name<type-arg-list> var-name =
new class-name<type-arg-list>(cons-arg-list);
Bounds type
<type extends superclass
Wildcard argument
using
?
Example: type_oarameter<?>
bounds type
using extends superclass
example:
static void test(Gen<
? extends A
> o) {
// ...
}
Generic method
<type-param-list> ret-type meth-name(param-list) { // ...
Generic Interface
interface interface-name<type-param-list> { // ...
class class-name<type-param-list>
implements interface-name<type-param-list> {
Type inference
class-name<type-arg-list> var-name = new class-name< >(cons-arg-list);
Generic class
Ex: class Gen<T>
Control Statement
IF
if (condition) {
statement if;
} else {
statement else }
SWITCH
switch(expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
default:
statement sequence
}
The default statement sequence is executed
if no case constant matches the expression
Using keyword BREAK
FOR
FOR-EACH
for(type itr-var : collection) statement-block
WHILE
while(condition) {
statement;
}
DO...WHILE
do {
statements;
} while(condition);
keyword BREAK
exit loop
break label
set label in loop
call breal label to exit that loop
(example page 91)
CONTINUE
skip one time loop if condition correct
look the difference between break label with continue label in example "CONTINUEANDBREAK.java"
INTERFACE
access interface name {
ret-type method-name1(param-list);
type varN = value;
}
variable: public, static, final and must be initialized.
implementing interfaces
one class can implement more interfaces
class classname extends superclass implements interface {
// class-body
}
Interface Reference
interface reference to object which implement it's interface
interface can not access members of object
Default Interface method
default type_return name_method(){
//body
}
issues:
interface A has method reset()
interface B extends A and override reset()
then use override method in B
IF user want to use reset method in A
InterfaceName.super.methodName( )
static interface method
EXCEPTION HANDLING
Parent class: Throwable
Two subclass: Exception and Error
Try-catch
try {
// block of code to monitor for errors
}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}
Throw
throw exceptOb;
methods in throwable
Throwable fillInStackTrace( )
String getLocalizedMessage( )
String getMessage( )
String getMessage( )
void printStackTrace(PrintStream stream)
void printStackTrace(PrintWriter stream)
String toString( )
finally
try {
// block of code to monitor for errors
}
catch (ExcepType1 exOb) {
// handler for ExcepType1
}
catch (ExcepType2 exOb) {
// handler for ExcepType2
}
//...
finally {
// finally code
}
Throws
ret-type methName(param-list) throws except-list {
// body
}
Using I/O
inherit java.io package
I/O stream has two type:
byte stream: access binary data
character stream: input/output is charater
BYTE STREAM defined by:
INPUT STREAM and OUTPUT STREAM
CHARACTER STREAM defined by:
WRITER and READER
Read/Write File
Byte Stream
FileInputStream(String fileName) throws FileNotFoundException
int read( ) throws IOException
TARGET: read data from file and show it
FileOutputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName, boolean append)
throws FileNotFoundException
void write(int byteval) throws IOException
TARGET: write data to file
Auto close file
try (resource-specification) {
// use the resource
}
resource-specification is declares and initializes a resource
Example:
try (FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1]))
{ catch () {}
Binary Data
DataInputStream
DataInputStream(InputStream inputStream)
TARGET
: read primitive data from file (after that show it)
DataOutputStream
DataOutputStream(OutputStream outputStream)
TARGET
: write primitive data to file
Character Stream
Console Input
using BufferedReader
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Console output
using PrintWriter
PrintWriter(OutputStream outputStream, boolean flushingOn)
File I/O
FileReader
FileReader(String fileName) throws FileNotFoundException
FileWriter
FileWriter(String fileName) throws IOException
FileWriter(String fileName, boolean append) throws IOException
Note of Big Practice
comment code
follow URL:
http://www.oracle.com/technetwork/articles/java/index-137868.html
Use modifier
private: use with method same class
public: other class can use it
protected: inheritance class use it
comment about result of method: clear and detail
handle error by input of user
Using string step by step:
replace special character with whitespace
split whitespace
add all word of string into a string array
access string by choice of user
use linewhite suit situation
Multithreaded programming
create a thread:
extends Thread
implement runnable
Runnable define method run()
call mehod start() to execute run method
Method in thread
Init thread in custom class
Thread(Runnable threadOb, String name)
get name of thread
final String getName( )
set name of thread:
final void setName(String threadName)
status of thread
final boolean isAlive( )
thread alive or end
final void join( ) throws InterruptedException
Thread Priorities
final void setPriority(int level)
final int getPriority( )
The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY.
default priority, specify NORM_PRIORITY, which is
currently 5
thread communicate
wait
final void wait( ) throws InterruptedException
final void wait(long millis) throws InterruptedException
final void wait(long millis, int nanos) throws InterruptedException
notify
final void notify( )
notify all
final void notifyAll( )
only apply for synchronized method
control thread
resume
final void resume( )
don't use suspend -> don't use resume
suspend
final void suspend( )
involve deadlock
-> don't use it
stop
final void stop( )
can sometimes cause serious problems -> dont use
class extends thread
synchronization
A synchronized method
declare with synchronized
When a thread leaves the synchronized method,
the object is unlocked
When the object is unlocked, the other thread
can enter it. Otherwise can't enter to it
synchronized block
synchronized(objref) {
// statements to be synchronized
}
example using variable
declares two variables with type integer
set value for variable which name dividend
set value for variable divisor is half of dividend
print value of variables
to declare a variable, precede its name with type of it
Array
one dimension
type array-name[ ] = { val1, val2, val3, ... , valN };
type array-name[ ] = new type[size];
two dimensions
type array_name[][] = new type[size row][size column]
irregular
need to specify only the memory
for the first (leftmost) dimension
Ex: int table[][] = new int[3][];
three or more dimensions
type name[ ][ ]...[ ] = new type[size1][size2]...[sizeN];
type-specifier array_name[ ] [ ] = {
{ val, val, val, ..., val },
{ val, val, val, ..., val },
.
.
.
{ val, val, val, ..., val }
};
Declaration Syntax
type[ ] var-name;
PACKAGE
define a package
package package_name;
put on the top of a java code file
package name ís lowercase
hierarchy of packages
package pack1.pack2.pack3...packN;
keyword
PROTECTED
layers can access directly:
same class, same package
different package by sub-class
execute java file in another package
compiler: javac package_name/file_name.java
run: java package_name.file_name
import package
import packaege_name.classname_imported
import package_name.*
import all classes in the package
Java'Class Libraries
java.lang
java.net
java.io
java.awt
java.applet
The FOR loop
for(initialization; condition; iteration) statement;
initialization
sets a loop control variable
to an initial value
condition
a Boolean expression
tests the loop control variable
Iteration
control variable is changed each
time the loop iterates
Enum
Enumerations Inherit Enum
inherit
java.lang.Enum
final int ordinal( )
enumeration constant’s position in
the list of constants
final int compareTo(enum-type e)
Restrictions
can not extends class
cannot be a superclass
methods
public static enum-type[ ] values( )
public static enum-type valueOf(String str)
keyword
enum
first program
class Example, class is package unit. Name class is similar with name file
method main
public: allow called by code outside of its class when the program is started
static: JVM call it before create any object. it's necessary for this method
void: this method dont has a value return
String args[]
A command-line argument is the information that directly follows the program's name on the command line when it is executed
it's array object type String. args receive any command-line arguments present when the program is executed
comment in code. using /
content comment
/ or // cmt comment
Data Types
Object-Oriented Data
Non Object-Oriented Data
( Primitive Data )
int
boolean
byte
double
float
char
long
short
Some notes
Integer
byte
short
int ( most common used)
long
Float-Point type
float - 32 bit
double - 64 bit ( most common used )
Character
char type
use Unicode
Boolean
Has 2 values: TRUE or FALSE
default value: FALSE
Short-Circuit Logical
evaluate the second operand only when necessary
AND: &&
prevent divide with zero
OR: ||
Cast Data
Auto cast
The two types are compatible
The destination type is larger than the source type.
manual cast
double x = 10;
double y = 3;
int i = (int) ( x / y );
Variable
init: type var_name
init dynamic:
type var_name;
var_name = 3.14 * 3.14 + 3.14;
scope of variable
global: can call it in anywhere in class or method main
local: can call it in block code where init it
The IF statement
If (condition) statement;
operator
" > " : Greater than
" >= " : Greater than or equal
" < " : Less than
" <= " : Less than or equal
" == " : equal to
" != " : Not equal
operator
Arithmetic
"+" "-" "*" "/" "%" "++" "--"
Relational and Logical
Relation "==" "!=" "<" ">" ">=" "<="
Logical "& | ^ || && !"
Bitwise Operator
AND, OR, XOR, NOT
Uppercase -> Lowercase:
char & 65503
Lowercase -> Uppercase:
char | 32
XOR:
R1 = X ^ Y; R2 = R1 ^ Y;
Recursion
Implement recursion method
new local variables and parameters are allocated storage on
the stack
not make a new copy of the method
execute a bit more slowly than their iterative