chapter 3. java fundamentals
TRANSCRIPT
Java Simplified / Session 22 / 2 of 45
Các thành phần◦Biến, hằng, toán tử, kiểu dữ liệu◦Cấu trúc điều khiển
Xử lý Ngoại lệ Truyền tham số và các lời gọi hàm Cấu trúc mảng Một số lớp cơ bản:
◦Lớp String và ◦StringBuffer◦Math
Nội dung
2
Java Simplified / Session 22 / 3 of 45
Basics of the Java Language
3
• Identification• Keywords• Comment• Data types• Variables• Operators• Control Structures• Classes
Java Basic
Components
Java Simplified / Session 22 / 4 of 45
abstract boolean break byte byvaluecase cast catch char classconst continue default do doubleelse extends false final finallyfloat for future generic gotoif implements import Instanceof innernull operator outer package privateprotected Public rest return shortstatic Super switch synchronize
dthis
threadsafe Throw throws transient truetry Var void volatile while
Keywords
4
Java Simplified / Session 22 / 5 of 45
/* Here is comment which extends across two lines */
/* * This comment has especial meaning for the javadoc unitily.It will be part of documenttation
automaticlly generated By the javadoc program */
// this comment extends to the end of this line of text
Comment: 3 types
5
Java Simplified / Session 22 / 6 of 45
// A program to display the message// "Hello World!" on standard outputpublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello World!");}} // end of class HelloWorld
Command line and block
6
Java Simplified / Session 22 / 7 of 45
Data Type Xác định loại dữ liệu được lưu trữ trong biến Xác định những tác vụ có thể thực hiện trên
dữ liệu Có 2 loại kiểu dữ liệu trong Java:
1. Primitive data types (kiểu cơ bản/nguyên thủy)2. Reference data types (kiểu tham chiếu)
Java Simplified / Session 22 / 10 of 45
Các kiểu dữ liệu tham chiếu• Một biến thuộc kiểu dữ liệu tham chiếu chỉ chứa tham khảo đến giá trị thực sự được biểu diễn bởi biến đó.
Java Simplified / Session 22 / 11 of 45
Hằng ký tự• Dãy ký tự đặc biệt dùng để biểu diễn các ký tự không thể nhập trực tiếp vào một chuỗi.
Java Simplified / Session 22 / 12 of 45
Variables must be declared before using, Syntax
datatype identifier [=value][, identifier[=value]...]; Three components of a declaration are:
◦ Data type◦ Name◦ Initial value to be assigned (optional)
Ex:int numberOfStudents; String name; int x=10; boolean isFinished; char firstInitial, middleInitial, lastInitial;
2. Variables
12
Java Simplified / Session 22 / 13 of 45
Example
13
class DynVar{
public static void main(String [] args){
double len = 5.0, wide = 7.0; double num = Math.sqrt(len * len + wide * wide); System.out.println("Value of num after dynamic
initialization is " + num);}}
Java Simplified / Session 22 / 14 of 45
Biến cục bộ có thời gian tồn tại giới hạn và quan hệ chỉ trong phần nhỏ của mã.
Scope variable
14
class ScopeVar {public static void main(String [] args){int num = 10;if ( num == 10){// num is available in inner scopeint num1 = num * num;
System.out.println("Value of num and num1 are " + num + " " + num1);
}//num1 = 10; ERROR ! num1 is not knownSystem.out.println("Value of num is " + num);
}}
Java Simplified / Session 22 / 15 of 45
JAVA có 4 loại biến : ◦Biến thành phần: là các thành phần của lớp và
được khởi tạo giá trị khi một đối tượng của lớp được tạo ra
◦Biến tĩnh: là các thành viên của lớp, đại diện cho cả lớp
◦Biến tham chiếu: được sử dụng để xử lý các đối tượng.
◦Biến cục bộ: được khai báo trong các phương thức và các khối, khai báo trước khi dùng
Variables
15
Java Simplified / Session 22 / 17 of 45
Dữ liệu cơ bản Cú pháp: (NewType) Value; Ex: float f= (float) 100.15D (double->float)
Các đối tượng: thành 1 đối tượng của một lớp khác. ◦ Với điều kiện các đối tượng muốn đổi kiểu phải thuộc các
lớp thừa kế nhau.◦ Cú pháp : (NewClass) Object ;
Dữ liệu cơ bản sang đối tượng và ngược lại:◦ Trong gói java.lang có sẵn những lớp đặc biệt tương ứng
với từng kiểu nguyên thủy: lớp Integer, Float,..Tạo đối tượng, ex: int Intobj = new Integer (32); ◦ Khi muốn lấy lại giá trị ban đầu ta dùng phương thức có sẵn
trong lớp tương đương. Như intValue() cho kiểu int...
Chuyển đổi kiểu dữ liệu: 3 dạng
17
Java Simplified / Session 22 / 18 of 45
Ép kiểu Một kiểu dữ liệu chuyển
sang một kiểu dữ liệu khác
Hai loại ép kiểu1. Implicit casting (ngầm định)2. Explicit casting (tường minh)
Java Simplified / Session 22 / 19 of 45
Ép kiểu ngầm định Chuyển kiểu tự động Điều kiện
◦Kiểu đích phải lớn hơn kiểu nguồn◦Mở rộng kiểu ◦Các kiểu phải tương thích với nhau
int a= 100;double b = a + 2.5f;
Java Simplified / Session 22 / 20 of 45
Ép kiểu tường minh Chuyển kiểu có độ chính xác
cao hơn sang kiểu có độ chính xác thấp hơn
Thu hẹp kiểu Ex, float sang intfloat a=21.2345f;int b = (int)a + 5;
Java Simplified / Session 22 / 21 of 45
Arithmetic Operators Assignment operators Relational Operators and
Conditional Operators Logical Operators
3. Operators
21
Java Simplified / Session 22 / 23 of 45
Toán tử một ngôi
“++”, “--” : có thể dùng:• trước (prefix) hoặc • sau (postfix) toán hạng
Java Simplified / Session 22 / 24 of 45
Toán tử quan hệ• Kiểm tra mối quan hệ giữa hai toán hạng.• Luôn trả về một giá trị luận lý (true hay false)
Java Simplified / Session 22 / 25 of 45
Toán tử điều kiện
“&&”, “||” : làm việc trên hai toán hạng luận lý
“ ? : ” : toán tử điều kiện chấp nhận 3 toán hạng
Java Simplified / Session 22 / 26 of 45
Toán tử trên bit Làm việc trên dạng biểu diễn nhị phân của dữ liệu
Java Simplified / Session 22 / 29 of 45
Class declaration Syntax
4. Classes in Java
29
class Customer {
var_datatype variablename;:
met_datatype methodname(parameter_list):
}
Java Simplified / Session 22 / 31 of 45
Input: System.in (ko cho nhập “ “)◦Scanner nhap = new Scanner(System.in);◦ int x = nhap.nextInt();◦String e= nhap.next();
Input: Luồng ký tự: BufferedReader (cho “ ”)BufferedReader in =new BufferedReader (new InputStreamReader (System.in));String name = in.readLine ();int hours = Integer.parseInt (in.readLine());Double rate = Double.parseDouble (in.readLine());
Output: System.out ◦System.out.println (“Hello”);
Input/ Output
31
Java Simplified / Session 22 / 32 of 45
Có các loại biểu thức như biểu thức logic, biểu thức số học, biểu thức gán ◦Ví dụ : a <= 10; ◦Biểu thức gán: Variable1= Variable2=...=Value; ◦Biểu thức điều kiện : Expression ? Expression_true : Expression_false;
Express
32
Java Simplified / Session 22 / 33 of 45
All application development environments provide a decision making process called control flow statements that direct the application execution.
Flow control enables a developer to create an application that can examine the existing conditions, and decide a suitable course of action.
Loops or iteration are an important programming construct that can be used to repeatedly execute a set of actions.
Jump statements allow the program to execute in a non-linear fashion.
5. Control Flow
33
Java Simplified / Session 22 / 34 of 45
Decision-making◦if-else statement◦switch-case statement
Loops◦while loop◦do-while loop◦for loop
Control Flow Structures in Java
34
Java Simplified / Session 22 / 35 of 45
if (condition){
action1;}else{
action2;}
if-else statement
35
Java Simplified / Session 22 / 36 of 45
Example: checkNum
36
class CheckNum{public static void main(String [] args){int num = 10;if (num % 2 == 0)System.out.print(num + " is an even number");elseSystem.out.print(num + " is an odd number");}}
Java Simplified / Session 22 / 38 of 45
switch(integer expression) { case integer expression: statement(s) break; ... default: statement(s) break; } Expression : Biểu thức điều kiện phụ thuộc vào kiểu dữ liệu cơ bản (byte, int ...)
switch – case statement
38
Java Simplified / Session 22 / 40 of 45
class SwitchDemo {public static void main(String[]
args){
int day = 4;String str;switch (day)
{ case 0: str = "Sunday";break;
case 1: str =
"Monday"; break;
case 2: str =
"Tuesday"; break;
case 3: str =
"Wednesday"; break;
case 4: str = "Thursday"; break;
case 5: str = "Friday"; break;case 6: str = "Saturday"; break;default: str = "Invalid day"; }
System.out.println(str);}
}
Example
40
Java Simplified / Session 22 / 41 of 45
while loops are used for situations when a loop has to be executed as long as certain condition is True.
The number of times a loop is to be executed is not pre-determined, but depends on the condition.
The syntax is:
while (condition){action statements;..
}
while Loop
41
Java Simplified / Session 22 / 43 of 45
The do-while loop executes certain statements till the specified condition is True.
These loops are similar to the while loops, except that a do-while loop executes at least once, even if the specified condition is False. The syntax is:do{action statements;..} while (condition);
do – while Loop
43
Java Simplified / Session 22 / 45 of 45
Syntax:for (initialization statements; condition; increment /
decrement statements){
action statements;..}
for Loop
45
Java Simplified / Session 22 / 47 of 45
Three jump statements are:◦break◦continue◦return
The three uses of break statements are: ◦It terminates a statement sequence in a switch
statement.◦It can be used to exit a loop.◦It is another form of goto.
Jump Statements
47
Java Simplified / Session 22 / 49 of 45
Ngoại lệ là gì?
Khi một ngoại lệ xảy ra, chương trình kết thúc đột ngột, điều khiển được trả về cho OS
Trình xử lý ngoại lệ được thực hiện để xác định lỗi và bẫy nó
Nếu gặp phải một lỗi khi thực thi chương trình, một ngoại lệ sẽ xảy ra
ERROR !! Ví dụ:
Java Simplified / Session 22 / 50 of 45
Trình xử lý ngoại lệ – Ví dụ
Một đoạn mã giả…………IF B IS ZERO GO TO ERRORC = A/BPRINT CGO TO EXIT
ERROR:DISPLAY “DIVISION BY ZERO”
EXIT:END
Block xử lý lỗi
Java Simplified / Session 22 / 51 of 45
Trình xử lý ngoại lệ trong Java Các lớp Error và Exception xử lý các lỗi
trong Java Khi một ngoại lệ xảy ra:
◦ một thể hiện biểu diễn ngoại lệ đó được tạo ra. ◦ Thể hiện này sau đó được truyền cho phương thức
rút trích và xử lý thông tin Trình xử lý ngoại lệ Java được quản lý thông
qua năm từ khoá: try, catch, throw, throws, và finally.
Java Simplified / Session 22 / 52 of 45
Trình xử lý ngoại lệ trong Java khối try : chứa các lệnh trong chương trình
cần được khảo sát ngoại lệ Từ khoá catch: có thể bắt ngoại lệ và xử lý nó
một cách hợp lý Throw: Để ném bằng tay một ngoại lệ Mệnh đề Throws: được dùng trong một
phương thức để xác định phương thức này sẽ ném một ngoại lệ
Khối finally: ta có thể xác định mã lệnh thực sự cần thực thi trước khi một phương thức trả về
Java Simplified / Session 22 / 54 of 45
Mô hình xử lý ngoại lệ Hai cách xử lý ngoại lệ trong Java
◦ Các lệnh có thể ném các ngoại lệ nằm trong khối try và các lệnh xử lý ngoại lệ trong khối catch
◦ Một phương thức có thể được đặc tả theo cách sao cho khi ngoại lệ xảy ra thì việc thực thi nó bị cấm
Java Simplified / Session 22 / 55 of 45 Java Simplified / Session 12 / 55 of 27
Khối try và catch – Ví dụclass ExceptionDemo{
public static void main(String args[]){
try{
String text = args[0];System.out.println(text);
} catch(Exception ne)
{ System.out.println("No arguments
given! ");}
}}
Java Simplified / Session 22 / 56 of 45
Ex Ngoại lệpublic class StckExceptionDemo {
public static void main(String args[]){
try {
int num = calculate(9,0); // user defined method System.out.println(num);
} catch(Exception e) // exception object
{ System.err.println("Exception occurred :" + e.toString()); e.printStackTrace(); } }
static int calculate( int no, int no1) { int num = no / no1; return num; }}
Java Simplified / Session 22 / 57 of 45
Các phương thức trong ví dụ toString() rút trích biểu diễn thông tin
lưu trong một đối tượng Exception dưới dạng String
printStackTrace() dùng để in ra nguyên nhân gây ngoại lệ và dòng lệnh tạo ra nó
Java Simplified / Session 22 / 58 of 45
……….try{}catch(ArrayIndexOutOfBoundsException e)
{}catch(Exception e) {}……….
Nhiều khối catch
ArrayIndexOutOfBoundsException là một lớp con của lớp Exception được xử lý đầu tiên
Một đoạn code có thể tạo ra nhiều lỗi Nhiều khối catch phải được cung cấp Mỗi lệnh catch có thứ tự xuất hiện của nó
Java Simplified / Session 22 / 59 of 45
Ví dụclass MultipleCatch{
public static void main(String args[]){
try{
String num = args[0];int numValue = Integer.parseInt(num);System.out.println("The square is: " + numValue *
numValue); } catch(ArrayIndexOutOfBoundsException ne)
{ System.out.println("No arguments given!");
} catch(NumberFormatException nb)
{ System.out.println("Not a number!");
}}
}
Java Simplified / Session 22 / 60 of 45
Khối try - catch lồng nhau
Trong trường hợp đó, các trình xử lý ngoại lệ phải lồng nhau
Khi các khối try lồng nhau được dùng, khối try bên trong sẽ thực thi trước
Đôi khi một phần của khối có thể gây ra một lỗi và toàn bộ khối có thể gây ra một lỗi khác
Java Simplified / Session 22 / 61 of 45
class NestedTry{
public static void main(String args[]){
try{
int num = args.length;try{
int numValue = Integer.parseInt( args[0]); System.out.println("The square is " + numValue *
numValue); }
catch(NumberFormatException nb){
System.out.println("Not a number! "); }
}catch(ArrayIndexOutOfBoundsException ne){
System.out.println("No arguments given! ");}
}}
Ví dụ
Java Simplified / Session 22 / 62 of 45
Khối finally Đảm bảo rằng tất cả các việc dọn dẹp được
thực hiện khi một ngoại lệ xảy ra Dùng kết hợp với khối try Được đảm bảo thực thi bất kể ngoại lệ có xảy
ra hay không
catch block finallyException
finallyNo exception
try block
Java Simplified / Session 22 / 63 of 45
Khối finallytry {…} catch(Exception1 e1) {…}catch(Exception2 e2) {…}finally {…}
Java Simplified / Session 22 / 64 of 45
Khối finally – Ví dụstatic String str;public static void main(String s[]) {try{System.out.println("A"); tmp.staticLengthmethod(); System.out.println("B"); //this code is not executed } catch(NullPointerException ne) {System.out.println("Exception occured"); System.out.println("C"); } finally{ System.out.println("Done"); }}static void staticLengthmethod() {System.out.println(str.length());}
Java Simplified / Session 22 / 65 of 45
Sử dụng throw
Một phương thức có thể ném ra nhiều ngoại lệ
Ngoại lệ được ném ra dùng từ khoá throw try
{if(flag<0){
throw new NullPointerException();
}}
Java Simplified / Session 22 / 66 of 45 Java Simplified / Session 12 / 66 of 27
Sử dụng throws
Từ khoá throws liệt kê các ngoại lệ mà phương thức chặn.public static void main (String[] args) throws IOException {BufferedReader in =new BufferedReader (new InputStreamReader (System.in));int num1;double num2, Mul;System.out.print ("Enter the number 1: ");num1 = Integer.parseInt (in.readLine());System.out.print ("Enter the number 2: ");num2 = Double.parseDouble (in.readLine());
Mul = num1 * num2;System.out.println ("Mul is: " + Mul);}
Java Simplified / Session 22 / 67 of 45
Ngoại lệ do người dùng định nghĩa
Cần có lớp ngoại lệ do người dùng định nghĩa:◦ Nên là lớp con của lớp Exception ◦ Kiểu ngoại lệ mới có thể được bắt độc lập với
những lớp con khác của Throwable◦ Được tạo ra sẽ có tất cả các phương thức của lớp Throwable
Những ngoại lệ xây dựng sẵn không phải lúc nào cũng đủ để bẫy tất cả lỗi
Java Simplified / Session 22 / 68 of 45 Java Simplified / Session 12 / 68 of 27
class ArraySizeException extends NegativeArraySizeException
{ArraySizeException() // constructor{
super("You have passed illegal array size");}
}class UserDefinedException{
int size, array[];UserDefinedException(int val){
size = val; try
{ checkSize();
}catch(ArraySizeException e)
{System.out.println(e);
}}
void checkSize() throws ArraySizeException{
if(size < 0)throw new ArraySizeException();
array = new int[3];for(int count = 0; count < 3; count++)
array[count] = count+1;}public static void main(String arg[]){
new UserDefinedException(Integer.parseInt(arg[0]));}
}
Java Simplified / Session 22 / 69 of 45
RuntimeException ArithmeticException IllegalArgumentException ArrayIndexOutOfBoundsException NullPointerException SecurityException NoSuchElementException ClassNotFoundException AWTException DataFormatException SQLException IOException UnknownHostException SocketException
Một số ngoại lệ thường gặp
69
Ngoại lệ Ý nghĩaRuntimeException Lớp cơ sở cho nhiều ngoại lệ java.langArthmeticException Trạng thái lỗi về số, ví dụ như ‘chia cho 0’IllegalAccessException Lớp không thể truy cập IllegalArgumentException Phương thức nhận một đối số không hợp lệ ArrayIndexOutOfBoundsExeption
Kích thước của mảng lớn hơn 0 hay lớn hơn kích thước thật sự của mảng
NullPointerException Khi muốn truy cập đối tượng nullSecurityException Việc thiết lập cơ chế bảo mật không được
hoạt động ClassNotFoundException Không thể nạp lớp yêu cầu NumberFormatException Việc chuyển đối không thành công từ chuỗi
sang số thực AWTException Ngoại lệ về AWTIOException Lớp cha của các ngoại lệ I/OFileNotFoundException Không thể định vị tập tin EOFException Kết thúc một tập tin NoSuchMethodException Phương thức yêu cầu không tồn tại InterruptedException Khi một luồng bị ngắt
Java Simplified / Session 22 / 70 of 45
Dễ sử dụng�◦dàng chuyển điều� khiển đếnnơi có khả năng xử lý
ngoại lệ◦có thể ném nhiều loại ngoại lệ�
Tách xử lý ngoạ� ilệ khỏi thuật toán◦ tách mã xử lý�◦ sử dụng cú pháp khác�
Không bỏ sót ngoại lệ (ném tự động)� Làm chương trình dễ� đọc hơn, an toàn hơn
Ưu điểm của ném bắt ngoại lệ
70
Java Simplified / Session 22 / 71 of 45
Khai báo: ◦ <Type>[] <arrayname>;◦ <Type> <arrayname>[];◦ <Type>: kiểu nguyên thủy hoặc kiểu lớp◦ Ex: int [] IntArray, IntVariable;
Poly[] recArray, squArray, ovalArray;
Tạo lập đối tượng: dùng new
◦ <Arrayname> = new <Type>[size];
◦ Ex: IntArray=new Int[10]; recArray=new Poly[5];
Kết hợp: <Type1>[] <arrayname> = new <Type2>[size]; Khởi tạo: khai báo, tạo lập, gán gtri
◦ <Type>[] <arrayname>={value1, value2..}
Cấu trúc mảng
71
Java Simplified / Session 22 / 72 of 45
Truy xuất mảng: <Arrayname>.[index]◦index: 0-> Arrayname.length-1
Ngoại lệ: ArrayIndexOutOfBoundsExceptin
Array
72
Java Simplified / Session 22 / 73 of 45
class arr-ex{static int [] mangA;static int n;public static void main (String [] args){nhap();xuat();}
public static void nhap(){Scanner input=new Scanner(System.in);System.out.print("n= ");n=input.nextInt();mangA = new int[n];for (int x=0; x<n;x++ ) {System.out.print("mangA[" + x + "]=");mangA[x]=input.nextInt();
}}
Example
73
public static void xuat(){for (int i=0; i < mangA.length; i++)System.out.print(" " + mangA[i]);System.out.println();}
Java Simplified / Session 22 / 74 of 45
int[] myCopy(int[] a) {int b[] = new int[a.length];for (i=0; i<a.length; i++)b[i] = a[i];return b;}...int a[] = {0, 1, 1, 2, 3, 5, 8};int b[] = myCopy(a);Ex: sx mảng
Truyền tham số và nhận giá trị trả lại
74
Java Simplified / Session 22 / 75 of 45
Khai báo ◦<Type>[] [] []… <arrayname>;◦<Type> <arrayname>[][]…;
Khai báo,tạo lập:◦Ex: int [][] A=new int[4][5];
Khởi tạo: khai báo, tạo lập, gán gtriEx: int [] [] matrix = { {3,5,6,0}, {1,2,0,3}, {0,1,2,4}}int c[][] = new int[2][];c[0] = new int[5];c[1] = new int[10];
Multi Dimensional Array
75
Java Simplified / Session 22 / 76 of 45
import java.util.Scanner;class vd_math {public static int n =2;public static int m =3;public static int [][] A;public static void nhap() {int i,j;Scanner nhap = new Scanner(System.in);for ( i=0; i<=n-1; i++)for ( j=0; j<=m-1; j++) { System.out.print("Nhap pt " + i + "," + j + ": ");A[i][j]=nhap.nextInt();
}}
Example – Multi Dimensional Array
76
Java Simplified / Session 22 / 77 of 45
public static void xuat() {int i,j;for ( i=0; i<=n-1; i++)
{for ( j=0; j<=m-1; j++)System.out.print(A[i][j] + " ");System.out.println();
}}public static void main(String [] args) {A = new int [n][m];nhap();xuat();
}}
Example – Multi Dimensional Array
77
Java Simplified / Session 22 / 78 of 45
� System.arraycopy(src, s_off, des, d_off, len)◦ �src/ des : mảng nguồn, ◦s_off/ d_off : offset của mảng nguồn/đích◦ len: số phầntử cần copy�
Copy nội dung của� dữ liệu nguyên thủy, copy tham chiếu đối với đối tượng
Cung cấp 4 phương thức static◦ �fill(): khởi tạo các phần tử của mảng vớimột giá trị như
nhau◦sort(): xắp� xếp mảng◦equals(): so sánh hai mảng�◦binarySearch(): tìm kiếm� nhị phân trên mảng đã sắp xếp
Tiện ích
78
Java Simplified / Session 22 / 79 of 45
import java.util.Arrays;class vd_math {public static void main(String [] args) {
int a[] = { 5, 3 , 7 , 4 };int b[] = new int[a.length];System.arraycopy(a,0,b,0,a.length);System.out.println(Arrays.equals(a,b)); Arrays.sort(a);for (int i=0; i<= a.length-1; i++)System.out.print(a[i] + " ");
}}
ex
79
Java Simplified / Session 22 / 80 of 45
Hằng số�◦Math.E◦Math.PI
Các phương thức static�◦type abs(type), sqrt(double)◦double ceil(double), double floor(double)◦int round(float), long round(double)◦type max(type, type), type min(type, type)◦double random(): sinh số ngẫu nhiên trong đoạn
[0.0,1.0]
Xử lý toán học: Math class
80
Java Simplified / Session 22 / 81 of 45
Lũythừa�◦double pow(double, double)◦ double exp(double)�◦ double log(double)�◦ double sqrt(double)�
Lượng giác�◦ double sin(double)�◦ double cos(double)�◦ double tan(double)�
Math class
81
Java Simplified / Session 22 / 82 of 45
Java cung cấp 2 lớp: ◦String: dùng cho xâu ký tự bất biến (giá trị được
khởi tạo ban đầu và không thay đổi; chỉ đọc)
◦StringBuffer: dùng cho xâu ký tự động, thay đổi tùy ý.
Xử lý chuỗi
82
Java Simplified / Session 22 / 83 of 45
Khởi tạo xâu: ◦String str=“cong hoa xa hoi” (ko dung constructor)◦Dùng toán tử new:◦String str= new String(“cong hoa”);◦String str= new String(mang); nhập xâu từ mảng◦String str= new String(buff); buff là chuỗi động
Độ dài xâu: int length() Ký tự thứ i: char charAt(int i) Hoa: String toUperCase(), Chữ thường: String toLowerCase() Xâu bắt đầu là s: boolean startWith(String s) Xâu kết thúc là s: boolean endWith(String s)
String class
83
Java Simplified / Session 22 / 84 of 45
Ghép xâu: String concat(String s) hoặc dùng + So sánh xâu
◦ boolean equals(Object obj)◦ boolean equalsIgnoreCase(String str2)◦ int compareTo(String str2)◦ int compareTo(Object obj)
Ex: String str1=new String("hello"); String str2=new String("Hello"); String str3=new String("hello all");boolean b1= str1.equals(str2);boolean b2=str1.equalsIgnoreCase (str2);int c1=str1.compareTo(str3);String str4=str1.concat(str2);
Methods: ghép, so sánh
84
Java Simplified / Session 22 / 85 of 45
Vị trí xuất hiện đầu tiên/cuối cùng của ch (bắt đầu từ start)
◦ indexOf(int ch); lastindexOf(int ch); ◦ indexOf(int ch, int start); lastindexOf(int ch, int start)
Vị trí xuất hiện đầu tiên/cuối cùng của xâu con str (bắt đầu từ start)
◦ indexOf(String str); lastindexOf(String str); ◦ indexOf(String str, int start); lastindexOf(String str, int start);
Thay thế: ◦String replace(char old, char new);◦String replaceAll(String src, String dst)
Method: xâu con
85
Java Simplified / Session 22 / 86 of 45
Lấy xâu con từ vị trí start đến cuối (đến end)◦String substring(int start);◦String substring(int start, int end);
Chuyển các đối tượng của Object về String◦static String valueOf(Object obj);Object có thể là các giá trị kiểu nguyên thủy
Ngoại lệ: StringIndexOutOfBoundsException
Method: trích xâu con
86
Java Simplified / Session 22 / 87 of 45
Tạo lập:◦ StringBuffer(String str); đối tượng mới =str◦ StringBuffer(int len); đối tượng mới rỗng dài len◦ StringBuffer(); đối tượng mới rỗng dài 16 (defa
Ex: StringBuffer strbuf=new StringBuffer(s1) Chiều dài xâu: int length() đọc 1 ký tự tại i: char charAt(int i): thay đổi ký tự tại i thành ch
◦ void setCharAt(int I, char ch) Chuyển xâu buffer về xâu của lớp String
◦ String toString() Thay thế: o StringBuffer replace(int start, int end, String str)
Lấy xâu con:◦String substring(int start);◦String substring(int start, int end);
StringBuffer class
87
Java Simplified / Session 22 / 88 of 45
Thêm một chuỗi (object) vào cuối chuỗi:◦StringBuffer append(Object obj):
Chen một chuỗi (Object) vào từ vị trí offset◦StringBuffer insert(int offset, Object obj)
Xóa một chuỗi trong chuỗi hiện hành từ vị trí start đến cuối (đến vị trí end):◦StringBuffer delete(int i) (ko dùng)◦StringBuffer delete(int start, int end)
Đảo ngược một chuỗi: StringBuffer reverse() Đặt lại độ dài xâu: void setLength(int newlen)
Thay đổi trong StringBuffer (private)
88
Java Simplified / Session 22 / 89 of 45
StringBuffer strbf= new StringBuffer(“hello everyone”);StringBuffer strbfap=strbf.append(“xxxx”);StringBuffer strbfin=strbf.insert(3, str3);StringBuffer strbfde=strbf.delete(2,2);StringBuffer strbfre=strbf.reverse();
ex
89
Java Simplified / Session 22 / 90 of 45
Obtaining the Characters in a String as an Array of Bytes
String text = "To be or not to be"; byte[] textArray = text.getBytes(); Construct string from subset of char arraybyte ascii[] ={65, 66, 67, 68, 69, 70 };String s1 = new String(ascii);String s2 = new String(ascii, 2, 3);
String vs. Byte Array
90
Java Simplified / Session 22 / 91 of 45
Converting Char array to Stringchar[] ch = {'a','b','c','d'};System.out.println(String.valueOf(ch));
String text = "To be or not to be";char[] textArray = text.toCharArray();
Char array vs String
91
Java Simplified / Session 22 / 92 of 45
Giới thiệu Java Đặc điểm Java Các thành phần
◦Biến, hằng, toán tử, kiểu dữ liệu◦Cấu trúc điều khiển
Xử lý Ngoại lệ Cấu trúc mảng Lớp String và StringBuffer
Tóm tắt
92