1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình môn java hay nhất

140 456 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 140
Dung lượng 3,29 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

public class Product { public int Barcode; }  Class variables: These are also known as static member variables and there's only one copy of that variable that is shared with all

Trang 1

Java

Table of Contents

S c v Java 4

JVM( Java Virtual Machine) 5

Đ ng và l p 5

Bi n(Variables) 6

Data types 10

Đ E 10

String 11

String 11

StringBuilder and StringBuffer 14

StringTokenizer 15

T khóa static+this+super+final 16

T khóa static: 16

T khóa this 17

T khóa super 22

T khóa final 24

Override and Overload 25

K th a 26

Abstract 28

Tính tr ng 28

P c tr ng(astract methods) 28

L p tr ng(Abstract class) 28

Interface 29

Interface là gì? 29

T i sao ph i s d ng? 30

M i quan h k th a 30

X lý ngo i l (Exception Handling) 33

S d ng kh i try catch x lý ngo i l 34

T khóa throw 35

T khóa throws 35

Assertion+Logging 36

Assertion 36

Trang 2

Logging 37

S d ng I/O 37

Đ ng(Multithreading) 38

Threads là gì? 38

L i ích c ng 38

Multitasking 38

V 39

Cách t o thread 40

T o thread b ng cách s d ng interface Runnable 41

T o thread b ng cách k th a t l p Thread 42

Th t 42

P c join() 43

Đ ng b hóa gi a các thread 44

M i quan h gi a các thead 47

Hi ng dead lock 49

Daemon threads 51

Garbage Collection 52

P th c finalize () 53

Enumerations, Autoboxing,Static import,Annotations 54

Enumrations 54

Autoboxing 56

Static import 58

Annotations 58

Generics 59

Đ 59

T o class generic và method 60

Các ký hi i di n generic 62

Gi i h n ki u d li u 64

Generic Constructors 65

Generic Interfaces 65

M t s h n ch c a Generic 66

Lambda expressions,Inner classes,Proxies 67

Lambda expressions 67

Trang 3

Class vô danh(Anonymous Classes) 67

Lambda expressions 68

Inner classes 74

Đ 74

Member Inner Class là gì ? 75

Anonymous Inner Class là gì? 76

Local Inner Class là gì? 78

Static Nested Class là gì? 80

Nested Interface là gì? 80

Proxies 84

Collections 84

S d ng Iterator trong Java 89

Concrete Collections 92

ArrayList 92

ArrayList là gì? 94

Vector 99

LinkedList 101

HashSet class 104

TreeSet class 105

Stack and Queues 106

Priority Queues 106

Maps 107

Map Interface 107

HashMap class 108

TreeMap 110

Hashtable class 112

Difference between HashMap and Hashtable 114

B ng tóm t t 115

AWT and Swing 115

AWT(Abstract Windows Toolkit) 116

Container 118

Window 118

Panel 118

Trang 4

Frame 118

Swing 119

So sánh AWT và SWING 120

Container 121

JFrame là gì? 121

JPanel là gì? 126

Graphics 127

X lý nh 132

Cách 1: S d ng Toolkit 132

Cách 2: S d ng BufferedImage 133

Cách 3: s d ng ImageIcon 133

X lý s ki n 135

Tài li u tham kh o 140

S c v Java

 Java là gì?

easily extended since it is based on the Object model

languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on

 SimpleàĐ à n: Java is designed to be easy to learn If you understand the basic concept of OOP Java, it would be easy to master

 Secure: B o m t:With Java's secure feature it enables to develop virus-free,

tamper-free systems Authentication techniques are based on public-key

encryption

 Architecture-neutral: Đ c l p c u trúc:Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system

Trang 5

 Portable: Kh chuy n:Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset

 Robust: M nh m :Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking

 MultithreadedàĐ à ng: With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously This design feature allows the developers to construct interactive applications that can run smoothly

 Interpreted: Thông d ch:Java byte code is translated on the fly to native machine instructions and is not stored anywhere The development process is more rapid and analytical since the linking is an incremental and light-weight process

 Distributed:Phân tán: Java is designed for the distributed environment of the internet

 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed

to adapt to an evolving environment Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time

 High Performance:Hi u su t cao: With the use of Just-In-Time compilers, Java enables high performance

JVM( Java Virtual Machine)

Trang 8

 P à àI àV à àC àStatic variable:

 Instance variables:

These variables belong to the instance of a class, thus an object And every instance of that

class (object) has it's own copy of that variable Changes made to the variable don't reflect

in other instances of that class

public class Product {

public int Barcode;

}

 Class variables:

These are also known as static member variables and there's only one copy of that

variable that is shared with all instances of that class If changes are made to that

variable, all other instances will see the effect of the changes

public class Product {

public static int Barcode;

}

Full example:

// INSTANCE VARIABLE

public class Main {

public static void main(String[] args) {

Product prod1 = new Product();

public class Product {

public int Barcode;

public class Main {

public static void main(String[] args) {

Product prod1 = new Product();

prod1.setBarcode(123456);

Trang 9

Product prod2 = new Product();

publicclass Product {

publicstaticint Barcode;

public int getBarcode() {

Trang 10

sub-Package khác

Trang 11

 Tính nguyên th y: String name="HK";

 T à à ng : String object = new String("Hello World");

ch nh

int offset, int count)

Trang 12

14 void getChars(int srcBegin, int

srcEnd, char[] dst, int dstBegin)

Copy các ký t t chu i này vào m ng

the string object

chính quy ch nh hay không

ignoreCase, int toffset, String other,

int ooffset, int len)

Ki m tra chu i có m t ph n gi ng nhau

Trang 13

28 boolean regionMatches(int toffset,

String other, int ooffset, int len)

Ki m tra chu i có m t ph n gi ng nhau

29 String replace(char oldChar, char

newChar)

Tr v m t chu i m i t thay th t t c các l n xu t hi n c a ký t oldChar trong chu i này v i ký t newChar

30 String replaceAll(String regex, String

replacement)

Thay th t t c các chu i con c a chu i này kh p v i bi u th c chính quy b i String m i replacement

31 String replaceFirst(String regex,

String[] split(String regex, int limit)

Tách chu i này thành các chu i con, t i các ch kh p v i bi u th c chính quy

37 String substring(int beginIndex) Tr v m t chu i ký t m i là m t dãy

Trang 14

45 String trim() Tr v m t String m i, sau khi lo i b

các ký t tr ng (whitespace) bên trái và bên ph i

46 static String valueOf(primitive data

type x)

Returns the string representation of the passed data type argument

StringBuilder and StringBuffer

ng StringBuffer, StringBuilder l i có th à i (mutable có th à i giá tr ) T c

là giá tr (chu à à à à à ng String không th à à c

 Hi u su à à à“ àV à n gi a chúng gi ng nhau, ch khác là cách dùng sao cho phù h p v i yêu c u:

StringBuffer() // an initially-empty StringBuffer

StringBuffer(int size) // with the specified initial size

StringBuffer(String s) // with the specified initial content

Đ dài

int length()

// Các method xây d ng n i dung

// type đây có th là ki u nguyên th y (primitive), char[], String,

StringBuffer, v.v

StringBuffer append(type arg) // ==> chú ý ( trên)

StringBuffer insert(int offset, type arg) // ==> chú ý ( trên)

// Các method thao tác trên n i dung

StringBuffer delete(int start, int end)

StringBuffer deleteCharAt(int index)

void setLength(int newSize)

void setCharAt(int index, char newChar)

StringBuffer replace(int start, int end, String s)

StringBuffer reverse()

// Các method trích ra toàn b ho c m t ph n d li u

char charAt(int index)

String substring(int start)

String substring(int start, int end)

Trang 15

String toString()

// Các method tìm ki m v trí

int indexOf(String searchKey)

int indexOf(String searchKey, int fromIndex)

int lastIndexOf(String searchKey)

int lastIndexOf(String searchKey, int fromIndex)

StringTokenizer

 Cách t o:

 StringTokenizer(String str)

 StringTokenizer(String str, String delim)

 StringTokenizer(String str, String delim, boolean returnValue)

Trang 16

T khóa static+this+super+final

T khóa static :

 Bi n static:

 Là bi n c a class, không ph i là instance variable

Trang 17

public static void main(String[] args) {

Tukhoathis hi = new Tukhoathis();

Trang 18

Student13(){System.out.println("Constructor mac dinh duoc goi");}

Student13(int id,String name){

this no duoc su dung de goi constructor cua lop hien tai ph i đ c đ t đ u tiên trong contructor

this.id = id;

this.name = name;

}

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

Student13 e1 = new Student13(111,"Hoang");

Student13 e2 = new Student13(222,"Thanh");

e1.display();

e2.display();

}

}

Trang 22

void msg(){System.out.println("Hello java");}

ng l p cha g n nh t B t c khi nào b n t o instance (s th hi n) c a l p con, m t instance

Trang 23

public static void main(String args[]){

Bike3 b=new Bike3();

super();//se trieu hoi constructor cua lop cha

System.out.println("Bike duoc tao");

}

public static void main(String args[]){

Bike5 b=new Bike5();

}

}

Trang 24

class Student16 extends Person{

void message(){System.out.println("Chao mung ban den voi java");}

void display(){

message();//se trieu hoi phuong thuc message() cua lop hien tai

super.message();//se trieu hoi phuong thuc message() cua lop cha

}

public static void main(String args[]){

Student16 s=new Student16();

Trang 25

Override and Overload

No Method Overloading Method Overriding

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class Dog extends Animal{

void eat(){System.out.println("eating bread ");}

}

Trang 26

K th a

m i quan h cha-con

S phân c p:

 Các l p trong java t n t i trong m t h th ng th b c phân c p, g i là cây k th a

 L p b c trên là l p cha(super class), l p b à i là l p con(sub class)

 L p con không th truy c p thành viên private c a l p cha

 L p con không k th a các hàm t o c a l p cha

 Các lo i k th a:

 Multilevel: nhi u t ng

 Hirarchical:có c u trúc

Trang 27

 Trong l à àJ à à th a (multiple) và k th a lai (hybrid) ch c h tr thông qua

S d ng t khóa extends

Do java không h tr à th a=> h tr qua interface=> s d ng t khóa implements

Trang 28

Abstract

Tính tr u t ng

i dùng Nói cách khác, nó ch hi n th các th quan tr ng t à i dùng và n các chi ti t

n i t i, ví d à g i tin nh à i dùng ch c n so n text và g i tin B n không bi t ti n trình

x lý n i t i v phân ph i tin nh n Tính tr à ng giúp b n tr à à à à à ng

 N u m t class khai báo là abstract thì nó không th bi u di n c th (instantiated)

 Đ s d ng abstract class, ph i k th a nó qua class khác, hoàn thi n abstract

methods trong nó

 Example:

// lop truu tuong Bike

abstract class Bike{

abstract void run(); // phuong thuc truu tuong voi tu khoa abstract

Trang 29

}

// lop Honda4 ke thua lop truu tuong Bike

class Honda4 extends Bike{

void run(){

System.out.println("Dang chay mot cach an toan ");

}

// phuong thuc main()

public static void main(String args[]){

/* Following is not allowed and would raise error

Bike obj = new Bike();// Bike is abstract; cannot be instantiated */

Bike obj = new Honda4();

Trang 31

Thân hàm ch ch à à c m à à à à c static.interface không

class A6 implements printable{

public void print(){System.out.println( "Hello" );}

public static void main(String args[]){

A6 obj = new A6();

Trang 32

public void print(){System.out.println( "Hello" );}

public void show(){System.out.println( "Welcome" );}

public static void main(String args[]){

A7 obj = new A7();

obj.print();

obj.show();

}

}

 So sánh abstract class và interface:

 Cách s d ng abstract class và interface:

 Cân nh c s d ng abstract class:

v

 Cân nh c s d ng interface:

không liên quan

i implements hành vi c a nó

Trang 33

X lý ngo i l (Exception Handling)

Trang 34

S d ng kh i try –catch x lý ngo i l

try { // block of code to monitor for errors }

catch (ExcepType1 exOb) { // handler for ExcepType1 }

catch (ExcepType2 exOb) { // handler for ExcepType2 }

 Dùng try có nhi u catch

Scanner hi = new Scanner(System.in);

boolean test = false;

Trang 35

 Example :

public class TestThrow1{

static void validate(int age){

trình

Trang 36

}

 Phân bi t throw và throws

Đ c s d b qua ngo i l Đ c s d à khai báo ngo i l

Checked exception không th lan truy n

, ch ném

Checked exception có th lan truy n

Theo sau nó là instance Theo sau nó là class

Trang 37

assert value>=18:" Not valid";

Compile it by: javac AssertionExample.java

Run it by: java -ea AssertionExample

Không nên dùng :

 According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g

IllegalArgumentException, NullPointerException etc

 Do not use assertion, if you don't want any error in any situation

Logging

S d ng I/O

Trang 38

Đ ng(Multithreading)

Threads là gì?

th

c giao cho m t thread

 Cost of communication between the process is high

 Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc

 Thread-based Multitasking(Multithreading)

Trang 40

Cách t o thread

Có 2 cách:

1 By extending Thread class

2 By implementing Runnable interface

public void run(): C à àthread

 public void join(): waits for a thread to die

 public void join(long miliseconds): waits for a thread to die for the specified miliseconds

 public int getPriority(): returns the priority of the thread

 public int setPriority(int priority): changes the priority of the thread

 public String getName(): returns the name of the thread

 public void setName(String name): changes the name of the thread

 public Thread currentThread(): returns the reference of currently executing thread

 public int getId(): returns the id of the thread

 public Thread.State getState(): returns the state of the thread

 public boolean isAlive(): tests if the thread is alive

 public void yield(): causes the currently executing thread object to temporarily pause

and allow other threads to execute

 public void suspend(): is used to suspend the thread(depricated)

Ngày đăng: 12/12/2017, 19:50

TỪ KHÓA LIÊN QUAN