1. Code snippet 1.

To understand automatc garbage collecton, consider the example given in Code Snippet 1.

 class TestGC { //tạo class có tên TestGC
    int num1;  // khai báo biến num1 kiểu int
    int num2;  //khai báo biến num2 kiểu int
    public void setNum(int num1, int num2){ //tạo phương thức void setNum
        this.num1= num1;
        this.num2= num2;
    }
    public void showNum(){//tạo phương thức showNum
        System.out.println("Value of num1 is: "+ num1);
        System.out.println("Value of num2 is: "+ num2);
    }
    public static void main(String[] args) { // main
        TestGC obj1 = new TestGC(); // tạo đối tượng 1
        TestGC obj2 = new TestGC(); // tạo đối tượng 2

        obj1.setNum(2, 3); // Gọi phương thức setNum, truyền tham số cho đối tượng 1
        obj2.setNum(4, 5); // Gọi phương thức setNum, truyền tham số cho đối tượng 2
        obj1.showNum();    // gọi phương thức showNum cho đối tượng 1
        obj2.showNum();    // Gọi phương thức showNum cho đối tượng 2

        //Kiểm tra thử
        //TestGC obj3; // line 1
        //obj3=obj2; // line 2
        //objGC3.showNum(); // line 3
        //obj2=null; // line 4
        //obj3.showNum(); // line 5
        //obj3=null; // line 6
        //obj3.showNum(); // line 7
    }
}

capture1

Bây giờ, nếu line 1 và line 2 uncommented  và code re-run.

Capture2.JPG

Tiếp theo, khi line 4, line 5  uncommented và code re-run.

Capture3.JPG

Và bây giờ, nếu line 6 và line 7 uncommented và code re-run.

Capture

 

Vì vậy, một số điều quan trọng về  garbage collecton như sau:

  1. Làm cho đối tượng phù hợp với garbage collection, nên đặt null cho biến tham chiếu của nó.
  2. Cần lưu ý rằng, các loại primitve là không phải đối tượng. Do đó, nó không thể được gán null. Ví dụ như, int x = null là sai.

2. Code snippet 2.

//Tạo 1 class sử dụng phương thức Math Class
public class MathClass {
    int num1;//Khai báo biến num1 kiểu int
    int num2;//Khái báo biền num2 kiểu int
    //Khai báo contructors
    public MathClass() {
    }
    public MathClass(int num1, int num2){//Contructors có tham số
        this.num1= num1;
        this.num2= num2;
    }
    //sử dụng phương thức max()
    public void doMax(){
        System.out.println("Maximun is: "+ Math.max(num1, num1));
    }
    //sử dụng phương thức min()
    public void doMin(){
        System.out.println("Minimum is: "+ Math.min(num1, num1));
    }
    //Sử dụng phương thức pow()
    public void doPow(){
        System.out.println("Result os power is: "+ Math.pow(num1, num1));
    }
    //Sử dụng phương thức random()
    public void getRandom(){
        System.out.println("Random is generateted is: " + Math.random());
    }
    //sử dụng phương thức sqrt()
    public void doSquareRoot(){
        System.out.println("Square roor of: " + num1 + "is: "+ Math.sqrt(num1));
    }

}

public class TestMath {//tạo class Test Math
    public static void main(String[] args) {//main
        MathClass objMath= new MathClass(4,5); // Tạo đối tượng đồng thời truyền giá trị cho đối tượng
        //Gọi các phương thức đã được khởi tạo
        objMath.doMax();
        objMath.doMin();
        objMath.doPow();
        objMath.getRandom();
        objMath.doSquareRoot();
    }
}

Capture5.JPG

3. Code snippet 3.

Code Snippet 3 shows the use of some of the methods of System class.

public class SystemClass {//khai báo public class SystemClass
    int arr1[]= {1, 3, 2, 4}; //khai báo mảng 1 gồm 4 phần tử
    int arr2[]={6,7, 8, 0};   //khai báo mảng 2 gồm 4 phần tử
    public void getTime(){ // khai báo phương thức getTime
        System.out.println("Current time in milliseconds is: "+ System.currentTimeMillis());
    }
    //khai báo phương thức copyArray()
    public void copyArray(){
        System.arraycopy(arr1, 0, arr2, 0, 3); //syntax
        System.out.println("Copied array is: ");
        for(int i=0; i<4; i++){ //in mảng được sao chép
            System.out.println(arr2[i]);
        }
    }
    //khai báo phương thức getPath()
    public void getPath(String variable){
        System.out.println("Value of Path variable is: " + System.getenv(variable));
    }
}

public class TestSystem { //tạo class Test System
    public static void main(String[] args) {//main
        SystemClass objSys= new SystemClass();//khởi tạo đối tượng
        //invoke method
        objSys.getTime();
        objSys.copyArray();
        objSys.getPath("Path");
    }
}

Capture6.JPG

4. Code snippet 4.

Code Snippet 4 shows the use of some of the methods of Object class.

public class ObjectClass {//tạo class ObjectClass
    Integer num;//khai báo biến
    //Tạo constructors
    public ObjectClass(){}
    public ObjectClass(Integer num){
        this.num= num;
    }
    //phương thức sử dụng toString()
    public void getStringForm(){
        System.out.println("String form of num is: "+ num.toString());
    }
}
public class TestObject {//tạo class Test Object Class
    public static void main(String[] args) { //main
        //Khởi tạo đối tượng
        ObjectClass obj1 = new ObjectClass(1234);
        ObjectClass obj2 = new ObjectClass(1234);
        obj1.getStringForm();//invoke method
        //checking for equality of objects
        if (obj1.equals(obj2)) //so sánh chuỗi vs ob đã cho
            System.out.println("Objects are equal");
        else
            System.out.println("Objects are not equal");
            obj2=obj1; // assigning reference of obj1 to obj2
        // checking the equality of objects
        if (obj1.equals(obj2))
            System.out.println("Objects are equal");
        else
            System.out.println("Objects are not equal");
    }
}

Capture7.JPG

5. Code snippet 5.

class ClassClass extends MathClass{//class ClassClass kế thừa lớp MathClass VD trên
    public ClassClass() { //khởi tạo constructor
    }
}
public class TestClass { //tạo lớp test class
    public static void main(String[] args) {//main
        ClassClass obj = new ClassClass();//tạo ob
        System.out.println("Class is: " + obj.getClass());//in
    }
}

Capture8.JPG

6. Code snippet 6.

char[] name = { ‘J’, ‘o’, ‘h’, ‘n’ };//Khai bảo mảng kiểu kí tự
String nameStr = new String(name);//khởi tạo ob
System.out.println(nameStr);//in

7. Code snippet 7.

Code Snippet 7 shows an example using String methods.

class StringClass {//Khởi tạo class String Class

    public void manipulateStrings(String str1, String str2) {
        // concat strings
        System.out.println("Concatenated string is: " + str1.concat(str2));
        // get substring
        System.out.println("Substring is: " + str1.substring(0, 2));
        // get character at an index
        System.out.println("Character at index 3 is: " + str1.charAt(3));
        // convert string to upper case
        System.out.println("UPPERCASE string form is: " + str1.toUpperCase());
        // get length
        System.out.println("Length of string is: " + str1.length());
        // split string
        String[] splitted = str1.split("l");
        for (int i = 0; i < splitted.length; i++) {
            System.out.println("Split string is: " + splitted[i]);
        }
    }
}
public class TestString {//khởi tạo class Test StringClass
    public static void main(String[] args) {//main
        StringClass objStr = new StringClass();//khởi tạo obj
        objStr.manipulateStrings("Hello World!", "Good Morning");//invoke method
    }
}

Capture8.JPG

8. Code snippet 8.

Code Snippet 8 explains the use of StringBuilder.

class StringBuild {//tạo class String Build
    // creating string builder
    StringBuilder sb = new StringBuilder(); // line 1
        public void addString(String str){//khởi tạo method có giá trị truyền vào kiểu String
        // appending string to string builder
        sb.append(str); // line 2
        System.out.println("Final string is: " + sb.toString());
    }
}
public class TestStringBuild {//tạo class test StringBuilt
    public static void main(String[] args) {//main
        StringBuild sb = new StringBuild();//khởi tạo đối tượng
        //invoke methods
        sb.addString("Java is an ");
        sb.addString("object-oriented ");
        sb.addString("programming ");
        sb.addString("language.");
    }
}

Capture9.JPG

9. Code snippet 9.

Code Snippet 9 shows the use of StringTokenizer.

package javalang.codesnippet9;
import java.util.StringTokenizer;
/**
 *
 * @author viquy
 */
class StringToken {//khởi tạo lớp String Token
    public void tokenizeString(String str, String delim){//tạo phương thức truyền tham số
        StringTokenizer st = new StringTokenizer(str, delim); //khởi tạo đối tượng cùng gia trị
        while (st.hasMoreTokens()) { //đk
            System.out.println(st.nextToken());
        }
    }
}
public class TestProject {//tạo class Test String Token
    public static void main(String[] args) {//main
        StringToken objST = new StringToken();//khởi tạo đối tượng
        objST.tokenizeString("Java,is,a,programming,language", ",");//invoke method
    }
}

Capture10.JPG

10. Code snippet 10.

Code Snippet 10 explains the use of Pattern and Matcher for creatng and evaluatng regular
expressions:

package javalang.codesnippet10;

import java.util.regex.Pattern;//import
import java.util.regex.Matcher;//import

/**
 *
 * @author viquy
 */
public class RegexTest {//class

    public static void main(String[] args) {//main
        String flag; //khai báo biến flag kiểu String
        //vòng while điều kiện
        while (true) {
            Pattern pattern1 = Pattern.compile(System.console().readLine("%nEnter expression: "));
            Matcher matcher1 = pattern1.matcher(System.console().readLine("Enter string to search:"));
            boolean found = false;
            while (matcher1.find()) {
                System.console().format("Found the text" + "\"%s\" starting at " + "index %d and ending at index %d.%n", matcher1.group(), matcher1.start(), matcher1.end());
                found = true;
            }
            if (!found) {
                System.console().format("No match found.%n");
            }
            // code to exit the application
            System.console().format("Press x to exit or y to continue");
            flag = System.console().readLine("%nEnter your choice: ");
            if (flag.equals("x")) {
                System.exit(0);
            } else {
                continue;
            }
        }
    }
}

Capture11.JPG

11. Code snippet 11.

Capturing groups are numbered by countng their opening parentheses from lef to right. For example, in the expression ((X)(Y(Z))), there are four such groups namely, ((X)(Y(Z))),(X), (Y(Z)), and(Z).

It is required to have a clear understanding of how groups are numbered because some Matcher methods accepts an int value. The value specifes a partcular group number as a parameter. These are as follows:

  • public int start(int group): Returns the start index of the subsequence captured by the given group during the previous match operaton.
  • public int end (int group): Returns the index of the last character, plus one, of the subsequence captured by the given group during the previous match operaton.
  • public String group (int group): Returns the input subsequence captured by the given group during the previous match operaton.

An example of using groupCount() is shown in Code Snippet 11 .

package javalang.codesnippet11;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
 *
 * @author viquy
 */
public class RegexTest1 {
    public static void main(String[] args) {
        Pattern pattern1 = Pattern.compile("((X)(Y(Z)))");
        Matcher matcher1 = pattern1.matcher("((X)(Y(Z)))");
        System.console().format("Group count is: %d",matcher1.groupCount());
    }
}

Capture12.JPG

12. Code snippet 12.

To understand the use of flags, frst modify the code of RegexTest.java class to invoke the alternate version of compile as shown in Code Snippet 12.

Pattern pattern = Pattern.compile(console.readLine("%nEnter expression: "), Pattern.CASE_INSENSITIVE);

Capture13.JPG

13. Code snippet 13.

The split() method of Pattern class is used for obtaining the text that lies on either side of the patern being matched. Consider the SplitTest.java class shown in Code Snippet 13.

import java.util.regex.Pattern; //import
import java.util.regex.Matcher;
/**
 *
 * @author viquy
 */
public class SplitTest {//class
    private static final String REGEX = ":"; //khai báo private static final chuỗi Regex
    private static final String DAYS = "Sun:Mon:Tue:Wed:Thu:Fri:Sat"; //chuỗi
    public static void main(String[] args){//main
        Pattern objP1 = Pattern.compile(REGEX);// khởi tạo ob
        String[] days = objP1.split(DAYS);// Truyền giá trị
        for(String s : days) { //vòng for
            System.out.println(s);
        }
    }
}

14. Code snippet 14.

The split() method can also be used to get the text that falls on either side of any regular expression. Code Snippet 14 explains the example to split a string on digits.

import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
 *
 * @author viquy
 */
public class SplitTest {

    private static final String REGEX = "\\d";
    private static final String DAYS = "Sun1Mon2Tue3Wed4Thu5Fri6Sat";

    public static void main(String[] args) {
        Pattern objP1 = Pattern.compile(REGEX);
        String[] days = objP1.split(DAYS);
        for (String s : days) {
            System.out.println(s);
        }
    }
}